teleren/devto huggingface dataset:
How to deny access to a server from the public network?
Tags: iptables, linux, vpn, networksecurity
Published: 2023-06-07 01:37:48

Hello everyone,

I have a CentOS7 server with a public IP address, but I found every day there are many SSH attacks targeted at it. In the future, I also want to deploy some services on the server. But I am a new hand in Linux, to protect my server I searched the Internet, and found using VPN to connect the server is a secure way to avoid attacks.

I chose the tailscale as a VPN provider. Now I want to achieve the following objectives:

**1. All services provided by the server including SSH must be accessed through the VPN.**

**2. Tailscale can funcion properly on the server after setting iptables.**

After intalling tailscale, the filter table of my service is:

```
[root@hecs-9277 ~]# iptables -nvL
Chain INPUT (policy ACCEPT 109K packets, 11M bytes)
 pkts bytes target     prot opt in     out     source               destination
 249K   25M ts-input   all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ts-forward  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 161K packets, 23M bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain ts-forward (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 MARK       all  --  tailscale0 *       0.0.0.0/0            0.0.0.0/0            MARK xset 0x40000/0xff0000
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            mark match 0x40000/0xff0000
    0     0 DROP       all  --  *      tailscale0  100.64.0.0/10        0.0.0.0/0
    0     0 ACCEPT     all  --  *      tailscale0  0.0.0.0/0            0.0.0.0/0

Chain ts-input (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  lo     *       100.81.244.76        0.0.0.0/0
    0     0 RETURN     all  --  !tailscale0 *       100.115.92.0/23      0.0.0.0/0
 9239 1268K DROP       all  --  !tailscale0 *       100.64.0.0/10        0.0.0.0/0
```

As I mentioned, I am a new-hand, I run the following command just want to achieve the goal. But after that, I can't SSH to the sevice. `sudo iptables -t filter -I INPUT ! -s 100.64.0.0/10 -j DROP`. Luckily, I can access the server physically, so I delete the rule I have set.

Now, could anyone teach me how to achieve the goal by setting iptables or something else, please?

Thanks!
The DevOps Revolution
Tags: devops, devjournal, beginners, revolution
Published: 2023-06-07 01:31:00

## "The DevOps Revolution"

'Before' the dark ages to 'After' DevOps Adoption:

## 1. Dev Team: 
Write Code, "toss it over the wall" => Write Code deploy


## 2. Ops Team: 
Rack servers, deploy code => Write code deploy


## 3. Servers: 
Dedicated physical servers => Elastic virtual servers


## 4. Connectivity: 
Static IPs => Dynamic IPs, Service Discovery


## 5. Security: 
Physical, Strong perimeter, high trust => Virtual, end-to-end, zero trust


## 6. Infra provisioning: 
Manual => Infrastructure as Code (IaC) tools


## 7. Server Configuration: 
Manual => Configuration management tools


## 8. Testing: 
Manual => Automated Testing


## 9. Deployments: 
Manual => Automated


## 10. Deployment Cadence:
Weeks or months => Many times per day


## 11. Change process: 
Change request tickets => Self Service


## 12. Change cadence: 
Weeks or months => Minutes



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



Thanks for reading this.

If you have an idea and want to build your product around it, schedule a call with [me](https://calendly.com/pragyanatvade).

If you want to learn more about DevOps and Backend space, [follow me](https://dev.to/pragyanatvade).

If you want to connect, reach out to me on [Twitter](https://twitter.com/pragyanatvade) and [LinkedIn](https://www.linkedin.com/in/pragyanatvade/).
🚀Lancei o meu primeiro package para Python, estou muito feliz com os meus pacotinhos.
Published: 2023-06-07 00:43:17

Caso queira testar, você baixa-lo aqui
https://lnkd.in/dH2pQws7

Ou simplesmente digitando:
pip install apigratis

Você pode obter suas credenciais em
https://apibrasil.com.br

----
Tem para o PHP também
https://lnkd.in/dTdhn-Wp

Ou simplesmente digitando:
composer require jhowbhz/package-apigratis

#php #python
Python Docstrings
Published: 2023-06-06 22:37:25

In Python, if we do not assign a variable to a string, it acts as a comment named docstring. 
They are string literals that appear right after a function, module or class. They are enclosed in triple quotes. 
Docstrings are built-in strings that, when configured correctly, can help your users and yourself with your project’s documentation.

Docstrings Purposes
Their purpose is to provide users with a brief overview of the object(functions, modules, classes or scripts). At a bare minimum, a docstring should be a quick summary of whatever is it you’re describing and should be contained within a single line. Beyond the summary, multi-lined docstrings are used to elaborate on the object. The following are parts of a multi-lined docstrings:
A one-line summary line (picture)
A blank line proceeding the summary
Any further elaboration for the docstring
Another blank line

The maximum length of docstrings 72 characters. 

Docstrings are divided into the following categories:
Class Docstrings
Package and module Docstrings
Script Docstrings

Class Docstrings are used for class and class methods. The docstrings are placed immediately following the class or class method indented by one level:

Package and module Docstrings are placed at the top of the package’s __init__.py file. This docstring should list the modules and sub-packages that are exported by the package.

Scripts are single file executables run from the console. Docstrings in a script are placed at the top of the file and documented well for users to have sufficient understanding on how to use the script.
Teste de Unidade
Published: 2023-06-06 21:48:55


## Definições
Teste de Unidade: é o teste usado para testar unidades do código. O teste de unidade consiste em verificar o comportamento das menores unidades numa aplicação.

Os testes de unidade garantem que cada parte funcione correctamente e cumpra com os requisitos do software. Sem a criação de testes os desenvolvedores correm o risco de encontrar erros muito tarde, principalmente quando o software entra em produção, aumentando os custos da manutenção.

Unidades: podem ser métodos, funções, classes, structs, módulos, pacotes e funcionalidades.

## Elementos principais de um teste
- Pré-condições: condição que deve testada durante a execução do teste;
- Pós-condição: condição que deve ser atendida para a execução bem-sucedida do teste;
- Etapas do teste: ordem das instruções para a execução do teste;
- Resultado esperado: resultado que se pretende alcançar na execução do teste;
- Resultado real: resultado obtido após a execução do teste;
- Estado: estado obtido após a execução de um teste. Pode ser aprovado ou reprovado.

## Biliotecas e Frameworks 
- Java: JUnit, JBehave, Serenity, Spock, etc;
- C#: NUnit, XUnit, Moq, OpenCover, AutoFixture;
- Javascript: Jasmine, Karma;
- Python: Unittest, PyTest;
- PHP: PHPUnit, 
- Go: go testing;
- Elixir: ExUnit.

## Benefícios dos Testes de Unidade
- Identificação dos erros de software com antecedência;
- Mudanças são possíveis sem refletir em outros módulos;
- Simplificação da integração do código;
- Simplifica o design e a documentação;
- Reduz a taxa de erros e o consumo de tempo;
- Reduz os custos de implementação;
- Facilidade na refactoração do código e melhoria do código;
-  Fornece a documentação “viva” do software.

## Exemplo
Criação de testes para uma biblioteca de manipulação de ficheiros. A biblioteca está dividida em 3 partes: Manipulação de ficheiros (criação, remoção e escrita), Compressão de ficheiros e Informação dos ficheiros.
- Nome da biblioteca: FileManager
- Linguagem: Go
- Ferramenta de teste: go testing

## Código Fonte
https://github.com/ortizdavid/filemanager




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


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


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


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


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


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



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


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h42bok5no5nj8nac0bt0.jpg)
Day 756 : Go to sleep
Tags: hiphop, code, coding, lifelongdev
Published: 2023-06-06 22:30:50

_liner notes_:
- Professional : Pretty productive day. Helped out with a couple of community questions. Met with my manager. Finished up post event stuff and submitted my expenses. Now I'll actually get to get back to work. haha.

- Personal : Last night, I went through a bunch of tracks for the radio show and worked on some layouts for a new site project.

![A lake surrounded by trees with with a wooden walkway along the edge with some ducks in the water in Plitvice, Croatia](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yhx66rguuay16azzrlbd.jpg)

I'm outside the venue where a meetup will be happening. I'm going to see if I can stream it. After this, I'll head to my spot and go to sleep.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube rItKbRLmDTk %}
Un nuevo comienzo
Published: 2023-06-06 21:32:57

## **_Hola! mi nombre es Denisa_**

### **_Hoy 06-06-23 doy por iniciado este repositorio dedicado a la práctica de algoritmos y de entrevistas._**

> El primero es un pequeño ejercicio que me tomaron en una entrevista técnica, mi primera entrevista técnica, y el cual fallé.
> Ahora este se convierte en el kick-off que motiva mi estudio con plan de mejorar mis habilidades como desarrolladora y sobre todo a superar el "miedo escénico". Esta entrevista fue para un trabajo que deseaba mucho y no voy a abandonar esa **meta**.
> La próxima vez voy a estar mucho más preparada, es un compromiso conmigo. Cheers!
Mi intención con este pequeño blog es visualizar mi propio avance y perder el miedo al error. Si gustas acompañarme en este camino de autoconocimiento y crecimiento, eres Bienvenidx!


[1. ejercicio - altoVuelo.js](https://github.com/DenkiDenki/practica-jav-algoritmos/blob/main/altoVuelo.js)
Beginner App Developer
Tags: beginners
Published: 2023-06-06 21:30:44

Hello everyone! I hope you're all doing well. I'm reaching out to seek assistance in developing my first application for my recently launched [beauty blogging business site](https://shorturl.at/rwIY1). I'm seeking guidence for coding to create an all-in-one platform that combines blogging, articles, and product listings.

I'm excited to hear any suggestions or advice from the community. Thank you in advance for your support!
How to Save RAM in Java with G1 Garbage Collector
Tags: java, garbagecollector, cloud
Published: 2023-06-06 21:11:37

In the cloud world, you often pay only for what you actually use. So, you want to minimise the resources consumed. And here is one of the tips to save RAM in Java with G1 garbage collector.

If the application is idle most of the time and only runs memory-intensive operations once in a while, then it may not release the memory between operations that could actually be released. This is because garbage collection will not be triggered if there are no heap or object allocations happening.

Here is an example:

```java
public class DeepThought {
    public static void main(String[] args) {
        System.out.println("Press Enter to start...");
        new Scanner(System.in).nextLine();

        calculateTheAnswer();

        System.out.println("Press Enter to exit...");
        new Scanner(System.in).nextLine();
    }

    private static void calculateTheAnswer() {
        System.out.println("Calculating The Answer...");
        for (int i = 0; i < 500; i++) {
            int[] array = new int[1_000_000];
        }
        System.out.println("The Answer is... 42.");
    }
}
```
Here the `main()` method waits for user input to start memory-intensive processing (`calculateTheAnswer()`) and then waits for user input again to complete. These two user inputs are just for convenience so that it is easy to attach to the running program with VisualVM and see what is going on.

Let's run it with `-XX:+UseG1GC`, attach VisualVM, and press Enter to start processing. The memory consumption will look something like this:

![Memory consumption 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxh9jryw7wa3nk4y0gk3.png)

The heap grows during `calculateTheAnswer()` execution and does not shrink after that. And here is the chart after some time:

![Memory consumption 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r0rrz298fg0xhmpa9yjy.png)

The garbage collection happened after 1 hour and 15 minutes when the used heap reached the heap size. However, even after that, the heap size did not shrink. Furthermore, it is increased!

During another run of the same program, you can get something like this:

![Memory consumption 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rj395gwuq0xywnyaamqx.png)

Funny, doesn't it?

So, how can we deal with that?

Java 12 introduced the [-XX:G1PeriodicGCInterval](https://docs.oracle.com/en/java/javase/17/gctuning/garbage-first-g1-garbage-collector1.html#GUID-DA6296DD-9AAB-4955-8B5B-683651936155) VM option. It defines a minimum interval in ms at which G1 considers performing a garbage collection.

Now, let's run the program again with the following VM arguments:

```
-XX:+UseG1GC -XX:G1PeriodicGCInterval=5000
```

Now, the memory consumption will look something like this:


![Memory consumption 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q12m5t5awngcd0n4ddnv.png)

Here we can see that G1 triggered additional garbage collection, and the heap size shrunk significantly after the processing is done.

---

*Dream your code, code your dream.*
Como configurar Etags en Apache Server
Tags: http, html
Published: 2023-06-06 21:03:45

**Introduccion**

Una Etag es una cadena de texto única que representa la versión de un recurso en particular, podria ser una imagen un archivo JS o CSS. Los servidores nos dan la posibilidad de configurarlas a medida para que nuestra web funcione como querramos.

**Configuracion en Apache Server**

Para configurar y habilitar/desabilitar las Etags en nuestro servidor, en nuestro caso Apache Server,debemos acceder al archivo .htaccess .

Algo que debemos tener en cuenta es que para que nuestros Etags tomen efecto, debemos configuramos primero el
mod_write en apache (https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html).

Ahora si, abrimos nuestro archivo .htaccess y agregamos la siguiente linea:

`<IfModule mod_headers.c> 
    Header unset ETag 
</IfModule> 
FileETag None`

Finalmente reiniciamos nuestro servidor apache con el comando 
`"sudo service apache2 restart"`

Luego puede testear sus encabezados con firefox,chrome o con la herramienta de https://hackertarget.com/http-header-check/

Saludos y no se olviden de pensar en la performance de sus sistemas!
Python : Yspeed ⚡⚡
Tags: python, programming, devops, opensource
Published: 2023-06-06 20:59:29

## A new Yspeed library to replace speedtest !!

### What's this Yspeed library? 

YSpeed is a Python library that scrapes the Speedtest site using Selenium and displays the results with Rich. This library makes it easy to retrieve internet connection speed data (upload, download and latency) in an automated manner and display it elegantly using the Rich library.

<u>Link github :</u> [Yspeed](https://github.com/Foufou-exe/Yspeed)

### Why use this library?

There is currently no library maintained on python to provide information such as ping, upload rate, download rate and other ...

Here's the reality: 

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

### What does it have that the others don't?

Mainly, it recovers the information provided on the speedtest dynamically and easily so it is completed by the information given by [**ipinfo.io**](http://ipinfo.io/json)

### How does Yspeed use it?

#### Installation 


Make sure you have Python 3.6 or later installed. To install YSpeed, use the following command:

```python
pip install yspeed
```

or :

Clone the Project

```cmd
git clone https://github.com/Foufou-exe/Yspeed
```

Go to the directory

```cmd
cd Yspeed
```

Install the dependencies

```cmd
pip install -r requirements.txt
```

Run the Yspeed.py script

```cmd
python yspeed.py
```

<br>

#### Usage 
##### Example 1

Here is an example of how to use the YSpeed library:

```python
from yspeed import Yspeed

ys = Yspeed()

result = ys.run_speedtest()
ys.display_results(result)
```

If you would like to see more information about this bookseller, click on the Github link.
🌍How Startups Support Green Tech Initiatives for a Sustainable Future? Top interesting #apps and #startups
Tags: startup, apps, javascript, programming
Published: 2023-06-06 20:56:01

Every year on June 5th we celebrate World Environment Day 🌿 Supporting a sustainable future is no longer a choice; it is a requirement. Startups have emerged as potent change agents in the digital age, strongly supporting green tech initiatives to #design a more sustainable future. Here's a look at how startups are leading the move to a greener, more environmentally responsible future: 

🌱JouleBug 
Programming Language: JavaScript
United States
JouleBug is an app that encourages sustainable habits and behaviors through gamification. Users can track their eco-friendly actions, earn points, and compete with friends to make positive environmental changes.

🌱 SolarGaps
Programming Language: JavaScript, Python, C and C++
Ukraine
SolarGaps is a company that develops and manufactures smart solar blinds. These blinds are equipped with solar panels that capture sunlight and convert it into electricity. The generated energy can be used to power various devices and appliances within a home or office. 

🌱 Ecosia 
Programming Language: JavaScript
Germany 
Ecosia is a search engine that uses its revenue to plant trees. Built with JavaScript, Ecosia directs its profits towards reforestation projects, helping to combat deforestation and promote a greener planet.

🌱FoodKeeper 
Programming Language: Swift, Kotlin
Malaysia 
FoodKeeper is an app developed by the USDA that helps users reduce food waste. It provides information on proper storage methods, shelf life, and safety guidelines for various food items. The app is built using #Swift for iOS and Kotlin for Android.

🌱Powerpal 
Programming Language: Python
Australia
Powerpal is an energy-saving app that allows users to track and optimize their energy consumption. It provides insights into energy usage, suggests energy-saving actions, and rewards users for reducing their carbon footprint. Powerpal is built using #Python.

🌱 GridPoint 
Programming Language: C++, Java
United States
GridPoint is a startup that focuses on smart grid #technology. They provide software and hardware solutions to optimize energy distribution and consumption. Their applications are typically developed using a combination of C++ and Java.

Are you enthusiastic and passionate about supporting green initiatives by your business idea? [Devler.io's ](https://devler.io/)experts in software development are here to help you transform your software idea into a reality while adhering to sustainable standards.  

Have you come across any interesting #software applications or startups that are actively supporting green initiatives? How are they making a positive impact on sustainability?
AWS CloudFormation
Tags: aws, cloudcomputing, infrastructureascode, devops
Published: 2023-06-06 20:48:50

![Day9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ug60l4gixs2arl8u9zmm.png)
[9/30] #30DaysOfAWS Today, AWS CloudFormation & Hands-On.

**AWS CloudFormation** is a service that provides a common language for describing and provisioning AWS infrastructure. It allows you to create, update, and delete AWS resources in a consistent and predictable way.

AWS CloudFormation is a tool that helps users automate the creation and management of AWS resources.** It does this by using a template, which is a text file that describes the resources to be created. CloudFormation templates can be written using JSON or YAML format.

**AWS CloudFormation provides a number of benefits, including**

- Reliability: AWS CloudFormation templates can be used to create a consistent environment for your applications. This can help to reduce the risk of errors and improve the reliability of your applications.

- Repeatability: AWS CloudFormation templates can be used to create the same infrastructure in multiple environments, such as development, staging, and production. This can help to improve the efficiency of your development and deployment processes.

- Scalability: AWS CloudFormation templates can be used to create infrastructure that can be scaled up or down as needed. This can help you to save money on your AWS costs.

**Here are some of the most common uses for AWS CloudFormation**

- Creating and managing AWS resources: AWS CloudFormation can be used to create and manage a wide range of AWS resources, including EC2 instances, EBS volumes, S3 buckets, and RDS databases.

- Automating the deployment of applications: AWS CloudFormation can be used to automate the deployment of applications to AWS. This can be done by using a template to describe the AWS resources that are required to run the application.

- Managing infrastructure across multiple accounts:** AWS CloudFormation can be used to manage infrastructure across multiple AWS accounts. This can be done by using a template to describe the AWS resources that are required to run the application.

- Securing infrastructure: AWS CloudFormation can be used to secure infrastructure by using templates to define the permissions that are required for each AWS resource.

If you are looking for a way to automate the creation and management of AWS resources, then AWS CloudFormation is a good option to consider. It is a powerful tool that can help you to improve the reliability, repeatability, scalability, and security of your AWS infrastructure.

**Step-by-step tutorial** for how to create EC2 instance using AWS CloudFormation and Terraform. You can download it using this [URL](https://lasantha-fileshare-s3-932747549174-v1.s3.us-east-2.amazonaws.com/AWSCloudFormation%26Terraform.pdf).

**Learn More** - [URL](https://aws.amazon.com/cloudformation)

Thanks for reading the Article.