teleren/devto huggingface dataset:
Init container pattern
Tags: kubernetes, tips, pattern
Published: 2022-05-17 05:05:11

##### What and why
Many applications start with an initialization logic. Constructors in a OOP are used to "prepare" the object for it's life-cycle of tasks. It could be set-up connections, handlers, seed-data, set initial/default values, state configurations etc
Point to note is that initialization happens only once (and obviously at the beginning). The purpose of this pattern is to decouple initialization logic from the main business logic. This allows you to make changes to how the object “starts” without affecting how it “works”.


##### How
Kubernetes pods have provision to create multiple such **init** containers to help prepare the main container for it's operation. An init container is the one that starts and executes before other containers in the same Pod. It’s purpose is to perform initialization logic for the main application hosted on the Pod. For example, create the necessary user accounts, perform database migrations, create database schemas and so on.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/niahfxm9g7qhlhlod616.png)

##### Considerations
1. They should be simple and concise => finish fast
2. If there are >1 init containers, all of them are executed sequentially.
3. An init container is not executed unless it's previous init container as per the sequence is done and successful
4. They are restarted when they fail => they should be idempotent
5. Init containers resource limits (if large) can adversely affect the pod scheduling
Configuração básica do Springfox
Tags: java, springfox, springboot, swagge
Published: 2022-05-17 04:57:57

Springfox é uma ferramenta open source com uma UI (interface de usuário) amigável, desenvolvida para integrar Spring Boot com as especificações do Swagger e apresentar a documentação de uma API Rest.

Link do projeto: [**Springfox**](https://springfox.github.io/springfox/)

Antes de prosseguirmos fica uma observação.
Acima da versão 2.4.X do Spring Boot é necessário adicionar a anotação @EnableWebMvc na classe de configuração Springfox ou na classe mainApp, abaixo possui um exemplo.

Iniciaremos com a criação de um projeto no [Spring Initialize](https://start.spring.io/), adicione a dependência **Spring Web**.

Após importar o projeto na sua IDE, adicione a dependência do Springfox ao pom.xml:

```
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-boot-starter</artifactId>
   <version>3.0.0</version>
</dependency>
```
Crie uma classe para configuração de apresentação da UI do Swagger, está classe definirá como o que deve ser exibido na UI, além disso possui o @EnableWebMvc mencionado acima.

```
@EnableWebMvc
@Configuration
public class SwaggerConfig {

	@Bean
	public Docket swagger() {
		return new Docket(DocumentationType.SWAGGER_2).select()
				.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
				.paths(PathSelectors.any())
				.build();
	}
}
```
Crie um controller com os verbos HTTP de exemplo.

```
@RestController
@RequestMapping("/exemplo")
public class ExemploController {

	@GetMapping
	public String getExemplo() {
		return "Retorno exemplo";
	}
	
	@PostMapping
	public void postExemplo() {
	}
	
	@PutMapping
	public void putExemplo() {
	}
	
	@DeleteMapping
	public void deleteExemplo() {
	}
}
```

Start a aplicação, e acesse http://localhost:8080/swagger-ui/index.html

![Swagger](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6e515hl4ep7c3rxa2g2.png)

Apresentei aqui uma configuração básica do Springfox, integrado ao Spring Boot para a apresentação de uma UI amigável dos endpoints de uma API Rest.
Managed Cloud Security: Benefits & Services
Published: 2022-05-17 04:55:31

According to a research conducted by Gartner, the average cost of downtime could be as costly as $5600/minute.  

![Cloud Security Image- Hughes Systique](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qakznapbd7d1cgi34bla.png)
While Cloud adoption is increasing across many industries, security is still one of the major hindrances. So, [is cloud adoption really secure](https://hsc.com/Resources/Blog/While-Cloud-Adoption-May-Be-An-Obvious-Choice-Is-It-Really-Secure)? 

Security is frequently viewed as the largest impediment to a digital transformation journey, but it can also be its greatest enabler.  

A lack of a strong cloud security system in place is like a time-bomb waiting to explode. There are various potential issues with not having a solid security system such as: 

- Operational Inefficiency 
- High Cost
- Potential Harm to a Company's Image in case of a breach 
- Regulatory Compliance Challenges
 
All these difficulties are addressed by using Managed Cloud Security Services. It also allows the company's internal IT team to focus on new business initiatives while an external security team with extensive experience manages all elements of providing enterprise-grade cloud security. 
(_Read:[Importance of cloud migration](https://hsc.com/Resources/Blog/Importance-Of-Cloud-Migration)_)

##Some of the advantages a business avails from Managed Cloud Security Services are: 

- Business Continuity and Disaster Recovery (BCDR) 
- Automation 
- Overcome Business Specific Challenges 
- Accelerate Innovation   
- Cost-Effective 
- Overcome Compliance Challenges 

##What are the major security services offered in the cloud?  

SECaaS ([security-as-a-service](https://dev.to/hughes-systique/security-as-a-service-secaas-a-detailed-overview-4b3b)) is a fast-expanding area that provides [cybersecurity](https://hsc.com/Services/Product-Engineering-Services/Security) services that complement the traditionally managed security service provider.

###9 of the major security services offered are:  

1. Identity and Access Management (IAM)  
2. Data Loss Prevention  
3. Web Security  
4. Email Security  
5. Security Assessments  
6. Intrusion Management  
7. Security, Information and Event Management (SIEM)  
8. Encryption 
9. Network Security

(_Bonus read: A detailed blog about [SECaaS](https://hsc.com/Resources/Blog/Security-as-a-Service-SECaaS-A-Detailed-Overview)_)

Any [cloud computing service](https://hsc.com/Services/Product-Engineering-Services/Application-Engineering/Cloud) must be sufficiently secure. As more organizations move their vital data online and into the cloud, the risk of security breaches or cyber-attacks is growing. Maintaining a responsible cloud presence entails meeting strict security and compliance regulations as well as employing smart security techniques.
Finally Understanding Recursive Functions
Tags: recursion, python, functions
Published: 2022-05-17 02:57:15

---
title: Finally Understanding Recursive Functions
published: true
description: Understanding 3 characteristics of recursive functions.
tags: recursion, python, functions
//cover_image: https://direct_url_to_image.jpg
---

I used to have a hard time wrapping my mind around recursive function. Today, I learned 3 characteristics about recursion that makes them easy to understand. 

The 3 characteristics of recursive functions:
1. Recursive functions **have a state** that is represented by a parameter value. 
2. When calling the inner function, ensure that the parameter (state) **must be modified in some way** that brings it closer to the 'break condition' and **eventually meet it**. 
3. Set the **'break condition'** for which the inner function is not called again (i.e. breaking the recursion).

Let's see examples.

### Function #1
```python 
def run():
  run()

run()
```
This will run until the stack overflows because it's just running itself continuously.

### Function #2
```python 
def run(n):     # the state is represented by the value n
  run(n)        # no break condition; no change of state (n)

run(10)
```
This will also run until the stack overflows because there is no breaking condition.

### Function #3
```python 
def run(n):
  if n == 10:      # break condition (always unsatisfied)
    run(n)         # no change of state (n)

run(10)
```
This will also run until the stack overflows because the state (n) always satisfies the condition for running.

### Function #4
```python 
def run(n):
  if n == 10:      # break condition (always unsatisfied)
    run(n)         # no change of state

run(5)
```
This will never run a second time because the state (n) never meets the conditions for running again.

### Function #5
```python 
def run(n):
  if n > 1:     # breaking condition (satisfied until the state meets breaking condition)
    run(n-1)    # continuous change of state

run(10)
```
This will run recursively until the breaking condition is met.

There you have it. A recursive function has a state that is represented by a parameter value and requires a change of state (n) which eventually meets the 'breaking condition' of the function.

I hope this helps.
What tools/frameworks do you use for styling you web app?
Tags: discuss, javascript, webdev, css
Published: 2022-05-17 04:02:43

One of the most important part of a web app is a good looking and working front end. There are a lot of ways to style your web app from using **vanilla CSS** to using CSS frameworks like **bootstrap** or **Tailwind** or using UI frameworks and component frameworks like **Chakra UI**, **Material UI**, **Mantine** and so on.

I personally use vanilla CSS, Tailwind CSS, chakra UI and Mantine in my projects depending on what I want to achieve. For simple projects, I like using vanilla CSS, but for more complex projects with different UI components I like using Chakra UI, Mantine or Tailwind.

So, what are the tools or frameworks you use for styling your web apps? Let me know in the comments below! 😀
Cloud gurus interaction with data engineers
Tags: cloud, database, devops
Published: 2022-05-17 03:57:22

In my current role there is a constant interaction with, and need for, cloud techies that configure networking and resources in order to enable the functionality that I need to do my job. Any organisation will normally have restrictions in place where certain roles have the ability to create the resources needed by other roles. It would streamline the process if I had the security rights to simply go ahead and create what I need. But restrictions are put in place for a reason. They're good, but they're also restrictive!
Understand Laravel Gates and Policies for Roles & Permissions
Tags: laravel, webdev
Published: 2022-05-17 03:57:05

In [Laravel](https://laravel.com/) implementing Roles & Permission and how to use them is not an easy feat, especially understanding the [Gates](https://laravel.com/docs/9.x/authorization#gates) and [Polices](https://laravel.com/docs/9.x/authorization#creating-policies) in [Laravel](https://laravel.com/).

There are numerous packages available to help you out with it, install it and straight away use it without digging into the complexity of understanding [Gates](https://laravel.com/docs/9.x/authorization#gates) and [Polices](https://laravel.com/docs/9.x/authorization#creating-policies) and how to use them with [Laravel](https://laravel.com/).

I have found this [article](https://laravel-news.com/laravel-gates-policies-guards-explained) on [Laravel News](https://laravel-news.com/) written by [PovilasKorop](https://laravel-news.com/@povilaskorop)  which explains all the bits and pieces you need to understand in a very simple way.

**References**

- https://laravel-news.com/laravel-gates-policies-guards-explained
Mojolicious
Tags: perl, opensource, braziliandevs
Published: 2022-05-16 22:45:44


---

Durante um ano e meio trabalhei com o *mojolicious* em um projeto legado dentro de uma empresa de telecomunicações. Aprendi a fazer diversas coisas com ele e hoje vim contar para vocês como ele funciona.

## O que é?

O *mojolicious* é um _framework_ composto de um conjunto de componentes para desenvolvimento Web em tempo real com _Perl_ usando um MVC bem estruturado. Abaixo podemos observar alguns dos seus recursos disponíveis:

- Implementação cliente/servidor HTTP e _WebSocket_ com IPv6, TLS, SNI, IDNA, _proxy_ HTTP/SOCKS5, _socket_ de domínio UNIX, _Comet (long polling), Promises_/A+, _async/await_, _keep-alive_, _timeout_, suporte a compressão _cookie_, _multipart_ e _gzip_.
- Servidor da Web de E/S sem bloqueio integrado, com suporte a vários _loops_ de eventos, bem como pré-bifurcação opcional, perfeito para criar serviços da _Web_ altamente escaláveis.
- Analisador JSON e HTML/XML com suporte a seletores CSS.

## Como usar?

### Perlbrew

Recomendo que como primeiro passo para programar em _Perl_ baixem o gerenciador de instalação [_Perlbrew_](https://perlbrew.pl/). Ele vai te ajuda-los a ter várias versões do *perl* instaladas no seu computador e te auxiliar a administra-las de maneira bem simples.

Para instalar o _Perlbrew_ basta executar o seguinte comando no terminal:

```bash
$ curl -L https://install.perlbrew.pl | bash
```

Para instalar a versão estável mais recente e usá-la a partir de agora:

```bash
$ perlbrew install perl-5.34.0
$ perlbrew switch perl-5.34.0
```

Para programar com a versão mais atualizada, mas apenas no terminal atual:

```bash
$ perlbrew install perl-blead
$ perlbrew use perl-blead
```

Para executar *meuprograma.pl* em todas as instalações do perl, muito útil ao fazer testes:

```bash
$ perlbrew exec perl meuprograma.pl

```

Para a folha de dicas de uso básico:

```bash
$ perlbrew -h

```

Para mais descrições sobre comandos:

```bash
$ perlbrew help
```

### Instalação

A instalação do _mojolicious_ pode ser feita de maneira rápida no terminal por meio de apenas uma linha: 

```bash
$ curl -L https://cpanmin.us | perl - -M https://cpan.metacpan.org -n Mojolicious
```

### Hello Word!

Como prometido, abaixo mostro a vocês como é simples escrever uma aplicação Web completa com o _mojolicious_ utilizando apenas as linhas a seguir:

```perl
#!/usr/bin/env perl
use Mojolicious::Lite;

get '/' => {text => 'Hello Word!'};

app->start;
```

Basta salvar o arquivo com a extensão .pl e executa-lo usando *morbo* para inicia-lo com servidor web integrado.

```bash
$ morbo hello.pl
Web application available at http://127.0.0.1:3000

```

```bash
$ curl http://127.0.0.1:3000/
Hello Word!
```

<aside>
👋🏻 Então pessoal, como viram a cima usar o _mojolícious_ não é tão difícil, e como disse no começo ele pode nos ajudar em diversas coisas. Nos próximos posts irei ensinar a vocês todos os principais recursos desse _framework_ e as classes que o compõem. fiquem ligados para os próximos posts. Até a próxima.

</aside>
Getting Started with the React Kanban Board
Tags: react, reactnative, webdev
Published: 2022-05-17 03:46:45

Learn how easily you can create a React app with the create react app tool and add the Syncfusion [React Kanban board](https://www.syncfusion.com/react-ui-components/react-kanban-board) to it. Syncfusion’s React Kanban board is a task-scheduling control that provides a clear user interface for managing multiple stages of work. You will learn how to bind local and remote data sources, add, and customize a tooltip, set a custom height and width, select multiple cards, and change the default layout. 

Product Overview: https://www.syncfusion.com/react-ui-components/react-kanban-board

Tutorial videos: https://www.syncfusion.com/tutorial-videos

Download a getting started example from GitHub: https://github.com/SyncfusionExamples/getting-started-with-the-react-kanban-component

{% youtube bBs0KTr0htM %}
Reduce size of /var/log/journal
Tags: linux, journalctl
Published: 2022-05-17 03:14:30

`$ journalctl --disk-usage`
Journals take up 3.8G on disk.
You can control the size of this directory using this parameter in your /etc/systemd/journald.conf:

`SystemMaxUse=50M`

You can force a log rotation:

`$ sudo systemctl kill --kill-who=main --signal=SIGUSR2 systemd-journald.service
`NOTE: You might need to restart the logging service to force a log rotation, if the above signaling method does not do it. You can restart the service like so:

`sudo systemctl restart systemd-journald.service`
MCIPFE - Cálculo Lambda
Tags: elixir, funcional, braziliandevs
Published: 2022-05-17 03:05:52

#Saga MCIPFE
O **M**anual **C**ompletamente **I**ncompleto de **P**rogramação **F**uncional com **E**lixir é uma série de postagens bem pequenas para explicar um pouco de programação funcional.

## Cálculo lambda
*"No início eram apenas funções"*


O cálculo lambda é a abstração de um sistema formal da matemática lógica baseado na substituição e mapeamento de valores, sendo a base do conceito de **funções puras** que temos hoje.

Usando símbolo λ (lambda), seguido do nome do parâmetro e por fim a expressão.

***Uma soma:***

{% katex %}
\lambda x.\;x + 1 \newline
(\lambda x.\;x + 1)2 \newline
2+1 =3
{% endkatex %}

```elixir
add_one = fn(x) -> x+1 end
add_one(2)
#3
```

 No caso acima temos uma função simples que recebe um valor como parâmetro (**x**) e retorna a soma do parâmetro mais (**+**) 1, ou seja, substitui (**x**) por um valor e mapeia para expressão de (**+1**).

### O poder de uma função

 Com o conceito simples de mapeamento e substituição é possível construir qualquer coisa inclusive a lógica booleana.

> Lógica booleana de forma extremamente resumida é ideia que no universo só existem dois estados **Verdadeiro** ou **Falso**, contendo operadores como **E**, **OU** e **NÃO**.

 Vamos criar a lógica de **Verdadeiro** , **Falso** e o operador **Negação**.
O conceito de **Negação** é basicamente a inversão do valor booleano, dessa forma **NÃO** **Falso** é igual à **Verdadeiro**.


{% katex %}
true = \lambda x.\lambda y. \;x \newline
false = \lambda x.\lambda y. \;y \newline 
(\lambda b. \;b \;false \;true) true \newline
(true\;false\;true) = false \newline
(\lambda b.\; b \;false\; true) false \newline
(false\;false\;true) = true
{% endkatex %}



```elixir
lambda_true = fn(x, _) -> x end 
lambda_false = fn(_, y) -> y end 

lambda_not = fn(bool) -> 
   bool.(lambda_false,lambda_true) end

print = fn(bool) -> 
    IO.puts(bool.("true","false")) end

print.(lambda_not.(lambda_true)) #false
print.(lambda_not.(lambda_false)) #true
```

 Já no exemplo acima criamos duas funções `true` e `false` que recebem dois parâmetros `x` e `y` , a função  `true` retorna somente o parâmetro `x` e a função `false` retorna somente o parâmetro `y` .
Para  a `negação` precisamos criar uma outra função que mapeie uma função booleana, `true` ou `false`, em outra função booleana invertida.

### Conclusão
 Mas qual a **função** do cálculo lambda no dia à dia? O cálculo lambda é a base do que conhecemos hoje como uma função, entender esse conceito, mesmo que de forma mais superficial, é a porta de entrada para entender outros conceitos de programação funcional. 
 
### Bibliográfia

- [ÁLGEBRA BOOLEANA](https://www.inf.pucrs.br/emoreno/undergraduate/EC/cirdig/class_files/Aula02.pdf)
- [Lambda calculus wikipedia](https://en.wikipedia.org/wiki/Lambda_calculus)
- [Lambda Calculus - Computerphile] (https://www.youtube.com/watch?v=eis11j_iGMs) Assistam é incrível
- [Learn You a Haskell for Great Good!](http://learnyouahaskell.com/chapters)
Which open source software makes your daily professional life easy?
Tags: opensource, software, it, easy
Published: 2022-05-17 03:00:32

Following are my personal favorites

1. I'm in love with [Typora](https://typora.io/) as it is easy to use and you can easily add code snippets for day to day notes taking and you can use your favorite markdown and latex syntax what else you can ask for.

2. I remember memorizing password was such a hassle and how many times I had to reset password before i came to know about [bitwarden](https://bitwarden.com/).  

3. If you are like me who have to manage several servers using SSH or may be accessing several services via SSH Tunneling it sucks to open up your terminal each time and then look for IP and credentials. Instead we can use [termius](https://termius.com/) which makes life so much easy. Even though it's not open source but it does have a free plan which work's well for many usecases.

What are your favorite software to use?

I'm eager to read your comment 🙂
Hosting sveltekit on AWS Amplify
Tags: svelte, javascript, aws, webdev
Published: 2022-05-17 03:00:19

If you are using the [`@sveltejs/adapter-static`](https://www.npmjs.com/package/@sveltejs/adapter-static) this might come in handy!

Go to the AWS Amplify project, in the side bar click `App settings: Rewrites and redirects`, Edit, Open Text Editor and paste the following.

```json
[
    {
        "source": "</^[^.]+$|\\.(?!(svelte|css|gif|ico|jpg|js|png|txt|svg|woff|ttf)$)([^.]+$)/>",
        "target": "/index.html",
        "status": "200",
        "condition": null
    },
    {
        "source": "/<*>",
        "target": "/",
        "status": "404-200",
        "condition": null
    }
]
```

next add a `<base href="/" />` to the `<head />` tag in the `app.html`.

# Explanation
The Amplify Redirect and Rewrite Config and the `<base href="/" />` directs all the failed responses back to the index file, making any request that fails fall back to the sveltekit router.
SQL-Quick tip #13 - Index usage
Tags: tsql, sqlserver, sql, mssql
Published: 2022-05-17 02:49:38

## Sql Server tips and tricks

This is part of a series of quick tips and tricks I have accumulated over the year, that I think can be useful for others.
If you have similar short tips and tricks please leave a comment.

### Index usage

It should be common knowledge that when you use a Sql Server database you should use indexes to ensure that your database is performing optimally. Choosing the the correct indexes is kind of an art when you work with big databases with lots of tables because you need to add just the right amount of indexes. Too few indexes and you will not get the optimal performance, but too many indexes can actually slow down the performance.
The script below will show you the seeks, scans, lookups and updates for the current database and you can use that information to determine if an index is not being used.

```sql
SELECT OBJECT_NAME(sts.[OBJECT_ID]) AS [Table name],
       idx.[NAME] AS [Index name],
       user_seeks,
       user_scans,
       user_lookups,
       user_updates
  FROM sys.dm_db_index_usage_stats AS sts
  JOIN sys.indexes AS idx ON idx.[OBJECT_ID] = sts.[OBJECT_ID] AND idx.INDEX_ID = sts.INDEX_ID
 WHERE OBJECTPROPERTY(sts.[OBJECT_ID],'IsUserTable') = 1
   AND sts.database_id = DB_ID()
```

![Sql Server Management Studio screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wc8hckdmyjs3b70gzhgx.png)
Can someone Help me with this CODE?
Published: 2022-05-17 02:44:20

The output of this code is not something that I desired.
----------------
|     CODE      |
----------------


#include <iostream>
#include <stdlib.h>


struct node
{
    int data;
    struct node *link;
};

struct node *add_at_empty(struct node *head, int data)
{
    struct node *temp;
    temp= (struct node*)malloc(sizeof(struct node));
    temp->data=data;
    temp->link=NULL;
    head=temp;
    return head;
}

struct node *add_at_end(struct node *head, int data)
{
  struct node *temp1;
  temp1= (struct node*)malloc(sizeof(struct node));
  struct node *ptr=head;
  temp1->data=data;
  temp1->link=NULL;
  if(ptr=head)
   {
      head->link=temp1;
      ptr=ptr->link;
   }
  else
   {
      ptr->link=temp1;
      ptr=temp1;
   }
return head;
}

struct node *print_data(struct node *head)
{
    struct node *traverse;
    traverse=head;
    while(traverse!=NULL)
    {
        std::cout<<traverse->data<<"   ";
        traverse=traverse->link;

    }
    return head;
}
int main()
{
    struct node *head=NULL;
    struct node *curr=NULL;
    int nodes;
    head=(struct node*)malloc(sizeof(struct node));
    curr=(struct node*)malloc(sizeof(struct node));
    std::cout<<"enter Number of nodes required"<<std::endl;
    std::cin>>nodes;
    std::cout<<"Enter the data of first node "<<std::endl;
    std::cin>>head->data;
    head=add_at_empty(head, head->data);
    nodes=nodes-1;

    for(int i=0;i<nodes;i++)
     {
         std::cout<<"Enter data of next node "<<std::endl;
         std::cin>>curr->data;
         add_at_end(head, curr->data);
     }

head=print_data(head);

return 0;
}