teleren/devto huggingface dataset:
Insertion Sort in PHP
Tags: algorithms, php, beginners, programming
Published: 2023-02-09 15:32:57


## Table of Contents

- [About Insertion Sort](#about-insertion-sort)
- [Insertion Sort Algorithm](#insertion-sort-algorithm)
- [Function](#function)
- [Script](#script)
- [Time Complexity](#time-complexity)

## About Insertion Sort

Insertion sort is a simple sorting that compares each element in the list to the elements that come **before** it and inserts it into its correct position in the sorted list. This process is repeated until all elements have been inserted into their correct positions and the list is sorted.

**In insertion sort, we always start at the second index and compare values to the left (before).**

### Insertion Sort Algorithm

***Explanation:***

In insertion sort, we need to check all values, so we use two loops. 

1. Firstly, we start the loop from the index 1. 

2. To track the value of that index, we create a temporary variable `temp` in case we need to swap it. 

3. To compare to the left, we create a temporary variable `j` equal to `i-1`. 

4. Since we do not know how many times we need to loop, we use a while loop. 

If the value of `temp` is less than the value on the left, we swap it and decrement `j` to check the next value to the left.

![Insertion Sort](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nib9uwk080ldurcr6ymw.jpg)

We also need to stop once there is nothing to check. We add the condition `j >= 0` to ensure that we stay within the bounds of the list.

5, we return the sorted array.

## Function

```php
function insertionSort(array $a): array
{
  for ($i = 1; $i < count($a); $i++) {
    $temp = $a[$i];
    $j = $i - 1;
    while ($temp < $a[$j] && $j >= 0) {
      $a[$j + 1] = $a[$j];
      $a[$j] = $temp;
      $j -= 1;
    }
  }
  return $a;
}

// $list = [5, 2, 8, 9, 1];
// insertionSort($list);
// [1, 2, 5, 8, 9]
```

## Script

Try it on replit:
 
https://replit.com/@stafura/InsertionSort#main.php

## Time Complexity

The time complexity of the insertion sort algorithm is O(n^2) in the worst-case scenario, where n is the number of elements in the list. 

Despite its quadratic time complexity, insertion sort is a simple sorting algorithm that is well-suited to small lists or lists that are nearly sorted.

## More Info:

https://en.wikipedia.org/wiki/Insertion_sort
pyaction 4.16.0 Released
Tags: showdev, python, github, docker
Published: 2023-02-09 15:25:31

## TL;DR

I just released [pyaction](https://github.com/cicirello/pyaction) 4.16.0, a [Docker container with Python, git, and the GitHub CLI](https://dev.to/cicirello/pyaction-a-docker-container-with-python-git-and-the-github-cli-930).


## Changelog 4.16.0 - 2023-02-09

### Changed
* Bumped Python to 3.11.2.
* Bumped GitHub CLI to 2.23.0.


## Current Version List

This latest release of pyaction includes:
* Python 3.11.2
* [GitHub CLI 2.23.0](https://github.com/cli/cli/releases/tag/v2.23.0)
* git 2.30.2
* curl 7.74.0
* gpg 2.2.27



## More Information

For more information, see my earlier post about pyaction here on DEV, as well as pyaction's GitHub repository.

{% link https://dev.to/cicirello/pyaction-a-docker-container-with-python-git-and-the-github-cli-930 %}

{% github cicirello/pyaction %}



## Where You Can Find Me

Follow me here on DEV:

{% user cicirello %}

Follow me on GitHub:

{% github cicirello/cicirello %}

Or visit my website:

{% embed https://www.cicirello.org/ %}
🔥 Build CI/CD workflows for security and cost optimization of your Terraform infrastructures
Tags: cloud, architecture, security, opensource
Published: 2023-02-09 15:15:44

![Cloud designer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u5b8ev6z7la6fllczr80.png)


As cloud architects, it’s crucial to remember that our Terraform code is not only responsible for provisioning and managing resources in the cloud, but also for securing sensitive data and systems, and keeping cloud costs under control. However, not optimizing for costs and security can lead to various risks such as unexpected high costs that could have a significant financial impact on an organization, unauthorized access or breaches of sensitive data and systems that can result in data loss, system downtime, and reputational damage.


![CI/CD Engine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i9kubn3trqrde3bk4zhq.png)

But how do we overcome these challenges? One way is by integrating tools such as Infracost, Terraform Plan and Validate, Terrascan, Tfsec and OPA into our CI/CD workflow. These tools help you to identify and prevent potential security risks, as well as monitor and control cloud costs in a more automated way. By integrating them into the CI/CD pipeline, we can ensure that our Terraform code is always secure and cost-efficient.

{% youtube APO3Ns5-adg %}

Infracost, for example, can be integrated into the pipeline to provide detailed cost estimates for our Terraform code and ensure that our cloud resource costs are optimized. Terraform Plan and Validate are great for testing our Terraform code and identifying potential issues before they occur. Terrascan and Tfsec can be integrated to detect and prevent potential security issues. OPA can be integrated to validate and enforce policies in the Terraform code.

In short, optimizing for costs and security is crucial for cloud architects, and by integrating tools like Infracost, Terraform Plan and Validate, Terrascan and Tfsec, as well as OPA into our CI/CD workflow, we can ensure that our cloud infrastructures are always secure and cost-efficient. 

About Brainboard solution: https://www.brainboard.co/ 
Sign up for free: https://app.brainboard.co/register
Book a demo with our team: https://www.brainboard.co/resources/contact-brainboard
How to implement lazy loading in your website
Published: 2023-06-12 17:14:58

---
title: How to implement lazy loading in your website
published: true
date: 2023-02-09 15:00:42 UTC
tags: 
canonical_url: 
---

As web applications grow larger and more complex, it's important to consider how to optimize the user experience for slow internet connections or underpowered devices. One way to achieve this is by implementing lazy loading, which is a technique that delays loading of images or other content until it is needed.

Here's a simple implementation of lazy loading using the Intersection Observer API:

```
const images = document.querySelectorAll("img");

const options = {
  root: null,
  rootMargin: "0px",
  threshold: 0.1
};

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > 0) {
      const image = entry.target;
      image.src = image.dataset.src;
      observer.unobserve(image);
    }
  });
}, options);

images.forEach(image => {
  observer.observe(image);
});

```

The Intersection Observer API makes it easy to detect when an element enters or leaves the viewport, which is ideal for lazy loading. In this example, we query all `img` elements on the page and observe each one. When the observer determines that an image has entered the viewport, it sets the `src` attribute to the value stored in the `data-src` attribute, effectively loading the image.

Note that this is just one example of how to implement lazy loading, and there are many other techniques and libraries available. No matter what approach you take, the goal is to make your web applications fast and responsive, regardless of the network or device conditions. For example, one of the easiest ways to lazy load images in HTML is by using the `loading="lazy"` property:

```
<img src="/image.png" loading="lazy">

```

It's also recommended to lazy load content. An easy and fast way to use this is, for example, to make multiple fetches. Or you can even use WebSockets!
🗺️ AWS VPC Creation: Set up Subnets and Security Groups on 2 Availability Zones
Tags: aws, security, cloud
Published: 2023-02-09 14:58:28

{% youtube s4HKoaT6SZE %}

✅ Here is the summary of what you’ll learn in this video:

1️⃣ Best practice of Terraform and Infrastructure-as-code
2️⃣ Syntax (HCL)
3️⃣ How to configure Cloud resources 
4️⃣ Inheritance between cloud resources and how Brainboard detects and populates the information automatically
5️⃣ Variables: Types of variables: strings, bool, map, lists - simple and more complex declarations. Flag their values as sensitive.
6️⃣ All your Terraform files: main.tf, outputs.tf, providers.tf, terraform.tfvars, variables.tf and locals.tf
7️⃣ Document all your steps in the Readme
8️⃣ Terraform actions: Terraform Plan & Apply
9️⃣ Customize your cloud infrastructure's design for you and your team

😍 You design your infrastructure, and the Terraform code is automatically generated and ready to be deployed within minutes.

🎁 You can find the [AWS VPC with subnet and security groups](https://www.brainboard.co/cloud-architecture-template/vpc-with-subnets-security-groups) on 2 AZs  infrastructure in the template catalog for you and your team to use, here 👉 https://app.brainboard.co
📌 Manage Multi-cloud infrastructures using infrastructure as code and Terraform
Tags: cloud, terraform, codereview, azure
Published: 2023-02-09 14:42:33

{% youtube VZGZmaucVmc %}

We hear more and more people wanting to adopt a multi-cloud approach to deliver new business and customer value more quickly and at a large scale.
One of the biggest challenges when moving to multi-cloud is preparing the teams for the operational complexity that comes with operating across multiple cloud providers.

As teams continue to grow, some of them use tools and workflows that only align with a single vendor. Not only can these teams waste time switching between these tools but as companies grow, different teams develop different habits, making it difficult to coordinate work.


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

To address these challenges those teams must ask the following questions:
◈ Strategy: Should you even consider multi-cloud? It all comes down to your business, your product, and your users' expectations.
◈ People: How can we enable a team for a multi-cloud reality, where skills can be applied consistently regardless of the target environment and cloud providers?
◈ Process: How do we position central IT services as a self-service enabler of speed, versus a ticket-based gatekeeper of control, while retaining compliance and governance?
◈ Tools: How do we best unlock the value of the available capabilities of the cloud providers in pursuit of better customer and business value?

One of the first goals of a shared service for infrastructure provisioning is to deliver reproducible infrastructure as code consistent set of environments.

In today’s video, you will see how you can
1️⃣ Integrate the Terraform plan into your review process so that your architecture and security teams can understand what is about to happen too.
2️⃣ Build cross-environment strategies for multiple teams, regardless of the cloud provider you’re using by creating templates and cloning/syncing infrastructures
3️⃣ Segregate the infrastructure by cloud providers.

**By adopting a multi-cloud approach you can**
✅ Optimize return on investment (ROI). It allows you and your team to choose the specific services that work best based on contracts, payment flexibility, and customizable capacity. You can then maximize the resources and pay only for what gets used.
✅ Create redundancies that minimize the risk of a single point of failure.
✅ Reduce latency and improve user experience, you can choose cloud regions and zones that are close to your clients.

When using an orchestration platform,
✅ You and your teams use a common workflow for teams provisioning resources across public cloud vendors (AWS, Azure, GCP, Oracle) and ensure consistent deployments
✅ By using the same processes across different clouds you can reduce the time to onboard engineers.

Reduce operational complexity and embrace infrastructure as code to manage multi-cloud infrastructures here 👉  https://www.brainboard.co/resources/contact-brainboard
How To Set Up Jenkins on Linux
Tags: jenkins, linux, aws
Published: 2023-02-09 14:31:08

Jenkins provides CI/CD functionality, making sysadmin and developer lives easier. See how to install and set up this useful service on an AWS Linux VM instance.

## 1. Spin Up An AWS Instance
On your EC2 Dashboard, spin up a new t2.medium instance with a RedHat Linux 8/9 HVM at 4GB of RAM space. Create  a Security Group and Open the required ports, 8080 for Jenkins. Once the instance is set up, SSH into the instance from your IDE and proceed to download dependencies.

## 2. Download Dependencies
CD into the /opt directory; which is reserved for the installation of third party software

```
cd /opt
```

install java, git, tree, unzip and wget

```
sudo yum -y install unzip wget tree git
```
install java cookie

```
sudo wget -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm
```

```
sudo yum install jdk-8u131-linux-x64.rpm -y
```

## 3. Add Jenkins Repository and Key

Import Jenkins Repository for RedHat

```
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
```

CD to /etc/yum.repos.d/

```
sudo cd /etc/yum.repos.d/
```

Save file link in the above directory

```
sudo curl -O https://pkg.jenkins.io/redhat-stable/jenkins.repo

```
## 4. Install Jenkins

```
sudo yum -y install jenkins --nobest
```
Start the Jenkins Service

```
sudo systemctl start jenkins
```

Enable Jenkins Service

```
sudo systemctl enabl jenkins
```

## 5. Check Jenkins Status

```
sudo systemctl status jenkins
```
Now you should have your Jenkins successfully
installed!!

NB: To access Jenkins on your browser, enter your instance Public IP address followed by a colon and port number like this (XXX.XXX.XXX:8080). 

Here's how to install Jenkins in other ways ([Installing Jenkins](https://www.jenkins.io/doc/book/installing/))
9 tips on searching for that first job in tech
Tags: career, community
Published: 2023-02-09 14:23:10

I want to share advice on searching for that first job in tech. I hope that these gems of knowledge, that’s been discussed in my tech community, helps you in your tech career.

1. Don’t do it alone. Find yourself a support group to talk about the journey, hold each other accountable, and to help one another. 
> This can include fellow students in a tech boot camp, virtual friends from a Slack/Discord community, or a social media group like 100DaysOfCode/100Devs.

2. Develop different iterations of your resumes for different types of jobs and opportunities.

3. Seek and work with multiple recruiters of different types (agency and in-house).

4. Don’t be afraid of using your past non-tech history or talking about your transferable skills.
> A personal example is using my previous law enforcement background to talk about working in a team, communicating with people, or developing personal projects to help me with challenges I faced. 

5. Use your entire network (friends, family, church, neighborhood, etc.) in your search for a job.

![lots of friendly faces](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cdr33gyutu1djlwawxpw.png)

6. Every “NO” that you receive is a learning opportunity. Use it to shape your resume, the story or pitch you use in an interview, and the way you search for jobs.

7. Learn your local job market by asking questions to the tech community, reviewing job listing, and Googling.

8. Make networking with others a priority (coffee chats, tech meetups, social media, Slack/Discord, LinkedIn, etc.).
> Pro tip: Danny Thompson has a great FREE YouTube channel dedicated to optimizing your LinkedIn profile. https://www.youtube.com/watch?v=YuL_JoDeBDM

9. Finally and most important, this new career search may take a while. The worst thing you can do is to give up and become demotivated. Keep knocking on doors until the one God created for you is opened.

![Door is being opened by a person](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9bqvif2e4g0ofjyie5n.png)

### Before you go:

Please share more tips in the comments or additional thoughts on what has been discussed. Thanks in advance. 

[Code Connector](https://codeconnector.io/) is a non-profit that organized tech meetups to help people start their journey into tech. You can join our daily conversations by clicking this link: [Code Connector slack channel](https://bit.ly/2Fm3aN7).
O uso da CLI Tolls no React
Tags: react, beginners
Published: 2023-02-09 14:22:35

O React é uma biblioteca JavaScript para construir interfaces de usuário. Ele é capaz de criar aplicações web e mobile, tornando-se uma das tecnologias mais populares para o desenvolvimento front-end. No entanto, para aproveitar ao máximo o poder do React, é importante conhecer e utilizar as ferramentas CLI disponíveis, que seriam as linhas de comando de interface. Veremos agora um pouco sobre o CLI

CLI Tools são ferramentas de linha de comando que permitem a criação de projetos, configuração de dependências, geração de código, entre outros, de maneira rápida e fácil. No React, existem diversas ferramentas CLI disponíveis, cada uma com suas próprias funcionalidades e recursos. Aqui estão alguns exemplos dessas ferramentas:

1. Create React App: É uma ferramenta mantida pelo Facebook que permite criar aplicações React sem a necessidade de configurar o ambiente de desenvolvimento manualmente. Com apenas um comando, é possível criar um projeto React pronto para ser utilizado, com as configurações básicas de transpilação e testes já definidas.

```
npx create-react-app my-app
```


2. React Native CLI: É uma ferramenta para o desenvolvimento de aplicações mobile utilizando o React Native. Com a React Native CLI, é possível criar projetos, adicionar dependências, executar o aplicativo em dispositivos móveis e fazer testes.

3. React Router CLI: É uma ferramenta que facilita a criação de rotas em aplicações React. Com a React Router CLI, é possível gerar código para as rotas da aplicação, tornando o processo de criação de rotas muito mais simples e rápido.


Além destes exemplos, existem muitas outras ferramentas CLI disponíveis para o React.Basta utilizar conforme a sua necessidade.

Existem também um artifício que pode ajudar no desenvolvimento do seu projeto web. O Vite é uma ferramenta de construção que visa fornecer uma experiência de desenvolvimento mais rápida e enxuta para projetos web modernos. Para utilizar se usa o comando:

```
vite [root]
```

Em conclusão, as ferramentas CLI em React são uma ótima maneira de otimizar o desenvolvimento de aplicações, permitindo a automatização de tarefas comuns e aumentando a eficiência do processo de desenvolvimento. Conhecer e utilizar as ferramentas CLI disponíveis é fundamental
Imperative X Declarative
Tags: programming, computerscience
Published: 2023-02-09 14:18:48

Before making a comparison between the two models, it's necessary to understand the characteristics of each one of them.

## What is the imperative paradigm?

The imperative paradigm is a programming model that is based on statements of actions or commands. In other words, an imperative program is nothing more or less than a sequence of commands for the computer to execute.

Example of an imperative program:

```ts
const array: Array<number> = [1, 2, 3];

function plus_one(array: Array<number>) {
  const arr = [];

  for (let i = 0; i < array.length; i++) {
    const element = array[i];

    arr.push(element + 1);
  }

  return arr;
};

console.log(plus_one(array));
```

As seen in this example, an imperative program is a sequence of commands given to the computer.

## What is the declarative paradigm?

The declarative paradigm, on the other hand, states that the modeling of the program must be done through assertions about the objects. In other words, the programmer declares what they want the program to do, and the program's compiler or interpreter is responsible for determining the most efficient way to perform those actions.

Example of a declarative program:

```ts
console.log(
  [1,2,3].map((n) => n + 1)
);
```

In this example, the whole process of traversing the array, applying the function, placing it in a new array and returning, is omitted. Instead, a function from the language's own standard library is used, and the interpreter (Node.js, in this case) returns the expected value.

## What's the difference between both?

The main difference between the declarative and imperative paradigm lies in how they express the program. In the imperative paradigm, the programmer directly manipulates the state of the data, while in the declarative paradigm, the programmer declares the relationships between the data and the operations to be performed on them.

The imperative paradigm is more straightforward and easier to understand, especially for novice programmers, while the declarative paradigm is more expressive and can be easier to maintain and scale as the program grows in complexity.

## Conclusion

Ultimately, the choice between the two models depends on the type of problem being solved and the programmer's personal preferences.

---

[Woovi](https://woovi.com/) is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are [hiring](https://woovi.com/jobs/)!

---