teleren/devto huggingface dataset:
2187. Leetcode Solution in cpp
Tags: cpp
Published: 2023-03-07 03:24:56

#description:
You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip.

Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.

You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.

 

Example 1:

Input: time = [1,2,3], totalTrips = 5
Output: 3
Explanation:
- At time t = 1, the number of trips completed by each bus are [1,0,0]. 
  The total number of trips completed is 1 + 0 + 0 = 1.
- At time t = 2, the number of trips completed by each bus are [2,1,0]. 
  The total number of trips completed is 2 + 1 + 0 = 3.
- At time t = 3, the number of trips completed by each bus are [3,1,1]. 
  The total number of trips completed is 3 + 1 + 1 = 5.
So the minimum time needed for all buses to complete at least 5 trips is 3.
Example 2:

Input: time = [2], totalTrips = 1
Output: 2
Explanation:
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.
 

Constraints:

1 <= time.length <= 105
1 <= time[i], totalTrips <= 107
************************************************
#solution:
```cpp
class Solution {
 public:
  long long minimumTime(vector<int>& time, int totalTrips) {
    long long l = 1;
    long long r =
        *min_element(begin(time), end(time)) * static_cast<long>(totalTrips);

    while (l < r) {
      const long long m = (l + r) / 2;
      if (numTrips(time, m) >= totalTrips)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  long numTrips(const vector<int>& times, long m) {
    return accumulate(begin(times), end(times), 0L,
                      [&](long subtotal, int t) { return subtotal + m / t; });
  }
};

```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/minimum-time-to-complete-trips/
Traversing a Binary Tree in Level-Order
Tags: tutorial, c, writing
Published: 2023-03-07 03:20:32

Traversing a binary tree in level-order means visiting all the nodes in the tree level by level, starting from the root and moving down to the leaves.

In this post, we will take a look at the implementation in C using a queue data structure.

#### Data Structures

```c
struct binary_tree_s
{
	int n;
	struct binary_tree_s *left;
	struct binary_tree_s *right;
};

typedef struct binary_tree_s binary_tree_t;
```

#### Implementation
- First, we check that the input binary tree is not empty.
```c
/* if tree is NULL */
if (tree == NULL)
{
	return;
}
```
- Next, we create a queue data structure to store the nodes of the binary tree that need to be added.
```c
/* create queue to store node items */
binary_tree_t **queue = malloc(sizeof(*queue) * 1024);
if (queue == NULL) /* malloc fails */
{
	return;
}
```
- We add the root node of the tree to the queue, the queue's tail and size are then incremented.
```c
int head, tail, size, i;
head = tail = size = 0; /* initialize to zero */
queue[0] = tree; /* add root node to queue */
tail = size = 1; /* tail and size increases by 1 */
```
- Our function then enters a loop that iterates over the items in the queue.
- For each item in the queue, the function prints the value of the node's data.
- If the current node has a left child, the left child is added to the queue, and the queue's tail is incremented.
- If the current node has a right child, the right child is added to the queue, and the queue's tail is incremented.
- Once all the nodes in the current level have been added to the queue, the head and size indices are updated to prepare for adding the next level. This continues until all nodes in the tree have been added.
```c
while (head < size) /* iterate over the items in the queue */
{
	for (i = head; i < size; i++)
	{
		printf("%d\n", queue[i]->n); /* print value */

		if (queue[i]->left) /* check if a left child exists */
		{
			queue[tail] = queue[i]->left; /* last item in queue now points to left */
			tail++; /* tail increases */
		}

		if (queue[i]->right) /* check if a right child exists */
		{
			queue[tail] = queue[i]->right; /* last item in queue now points to right */
			tail++; /* tail increases */
		}
	}

	/* head becomes size this indicates the number of items that have been iterated/printed */
	head = size;
	/* size becomes tail, this is the number of items in the queue */
	size = tail;
}
```
- Finally, we free the memory allocated for the queue.
```c
free(queue); /* free queue */
```

#### Output
Tree is printed using level-order traversal.
```c
binary_trees$ ./level_order
       .-------(098)-------.
  .--(012)--.         .--(402)--.
(006)     (056)     (256)     (512)
98
12
402
6
56
256
512
binary_trees$
```
O que é e para o que serve Git Flow?
Published: 2023-03-07 03:16:09

Git Flow é um modelo de fluxo de trabalho para gerenciamento de versionamento de código utilizando o sistema de controle de versão Git. 

O Git Flow se concentra em fornecer um conjunto de práticas recomendadas para o gerenciamento de branches, o que permite uma maior colaboração e uma gestão mais organizada do ciclo de vida do código.

O Git Flow é amplamente utilizado na indústria de desenvolvimento de software e é considerado uma abordagem padrão para gerenciamento de versionamento de código em equipes maiores. Ele é composto por uma série de branches que servem para diferentes propósitos. A seguir, serão explicados os principais branches do Git Flow:

**Branch master**: é a branch principal que contém a versão mais atualizada e estável do código. Ela é atualizada somente quando um novo release é criado.

**Branch develop**: é a branch onde o desenvolvimento do código acontece. É aqui que as features são mescladas e os bugs são corrigidos. Essa branch é atualizada frequentemente.

**Branch feature**: é onde o desenvolvimento de novas funcionalidades acontece. Cada nova feature é criada a partir da branch develop e, assim que estiver pronta, é mesclada de volta para a develop.

**Branch release**: é a branch onde a versão do software está sendo preparada para ser lançada. É aqui que os últimos ajustes e correções são realizados antes de criar um novo release.

**Branch hotfix**: é usada para corrigir bugs críticos em produção. Ela é criada a partir da branch master e, após a correção do bug, é mesclada de volta para a master e para a develop.

O Git Flow tem como objetivo organizar o fluxo de trabalho do desenvolvimento de software em diferentes fases, o que permite que as equipes trabalhem juntas de forma mais eficiente e com menos conflitos. Ao utilizar esse modelo de fluxo de trabalho, é possível ter maior controle sobre o versionamento do código, permitindo que os desenvolvedores trabalhem em suas próprias features sem afetar o código principal, além de tornar mais fácil a identificação de bugs e a correção de problemas.

Além disso, o Git Flow também ajuda a manter a estabilidade do software em produção, permitindo que correções críticas sejam feitas rapidamente e sem afetar outras partes do código. Ele também fornece uma visão clara do status do desenvolvimento de uma nova versão do software, o que pode ajudar os gerentes de projeto a tomar decisões mais informadas.

Em resumo, o Git Flow é uma abordagem de gerenciamento de versionamento de código que fornece um conjunto de práticas recomendadas para uma gestão mais organizada do ciclo de vida do software. Ele permite uma maior colaboração entre as equipes de desenvolvimento e ajuda a manter a estabilidade do software em produção. Se você ainda não utiliza o Git Flow em sua equipe, vale a pena experimentar e avaliar os benefícios que essa abordagem pode trazer para o seu projeto.
failed to open stream: No such file or directory in /home/acifinan/public_html/send-email-attachment.php on line 3
Tags: programming, php
Published: 2023-03-07 03:15:57

Hi Team

I need help with my phpmailer and i am trying to create send mail with pdf attached on the email but on the server logs its getting this message
PHP Warning:  require(..\_lib\vendor\phpmailer\phpmailer): failed t`o open stream: No such file or directory in /home/acifinan/public_html/send-email-attachment.php on line 3


require '..\_lib\vendor\phpmailer\phpmailer';
use PHPMailer\PHPMailer;



$msg = '';
if (array_key_exists('bankstatement', $_FILES)) {
    //Create a message
    $mail = new PHPMailer();
    $mail->setFrom('info@acifinance', 'ACI Finance');
    $mail->addAddress('gcobani.mkontwana@agilelimitless.org.za', 'ACI Finance');
    $mail->Subject = 'ACI Finance Application Loan';
    $mail->Body = 'My message body';
    //Attach multiple files one by one
    for ($ct = 0, $ctMax = count($_FILES['bankstatement']['tmp_name']); $ct < $ctMax; $ct++) {
        //Extract an extension from the provided filename
        $ext = PHPMailer::mb_pathinfo($_FILES['bankstatement']['name'][$ct], PATHINFO_EXTENSION);
        //Define a safe location to move the uploaded file to, preserving the extension
        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['bankstatement']['name'][$ct])) . '.' . $ext;
        $filename = $_FILES['bankstatement']['name'][$ct];
        if (move_uploaded_file($_FILES['bankstatement']['tmp_name'][$ct], $uploadfile)) {
            if (!$mail->addAttachment($uploadfile, $filename)) {
                $msg .= 'Failed to attach file ' . $filename;
            }
        } else {
            $msg .= 'Failed to move file to ' . $uploadfile;
        }
    }
    if (!$mail->send()) {
        $msg .= 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        $msg .= 'Message sent!';
    }
}
?>

// html code
 <fieldset>
                                SELECT A pdf FILE TO UPLOAD
                                <br>
                                
                                 <label>ID </label><br>
                                <input type="File" name="id" id="id" accept=".pdf">
                                
                                <br>
                                <label>Bank Statement </label><br>
                                <input type="File" name="bankstatement" id="bankstatement" accept=".pdf">
                                <br>
                                <label>Pay Slip </label><br>
                                <input type="File" name="payslip" id="payslip" accept=".pdf">
                                <br>
                                <input type="Submit" id="btnNow" class="btn apply-btn mt-30" name="button" value="APPLY NOW">
                                </fieldset>`
Zerando HackerRank ( 8 )
Published: 2023-03-07 03:11:30

O oitavo desafio do HackerRank é um problema intrigante que testa nossas habilidades de programação e raciocínio lógico. Neste artigo, vamos examinar como resolver esse desafio passo a passo.

Na descrição deste exercício podemos observar alguns elementos em um tipo de terreno, neles existem duas arvores e uma casa que  é representada por uma faixa vermelha na imagem abaixo:

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

Para isso, recebemos uma série de inputs:

**s**: ponto inicial da localização da casa de Sam.

**t**: localização final da localização da casa de Sam.

**a**: localização da macieira.

**b**: localização da laranjeira.

**apples** (Maças): distâncias em que cada maçã cai da árvore.

**oranges** (Laranjas): distâncias em que cada laranja cai da árvore.

A localização da macieira é indicada por A, e a localização da laranjeira é indicada por B. A posição da fruta que cai é representada pela matriz das maçãs e laranjas.

Para isso a função usa dois loops for para percorrer os arrays de maçãs e laranjas usando dois loops for e verificar se a localização da fruta caída está dentro da área determinada pelos parâmetros definidos, que é a casa. 

Por fim, é imprimado o número de maçãs e laranjas descartadas usando console.log igual a 1,1.

A função para resolver essa questão deve ficar mais ou menos assim:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bz8wl9o1hxv090anww5k.png)
Intro to Supabase: The Complete Backend for Web & Mobile Apps
Tags: supabase, serverless, firebase, webdev
Published: 2023-03-07 03:04:56


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

When it comes to building an app, the biggest challenge is not writing code, but rather architecting a complete system that works at scale. Firebase and Amplify have addressed this barrier, but there's one big problem - they lock you into proprietary technology on a specific cloud platform.

This is where Supabase comes in. Created in 2019 specifically as an open source Firebase alternative, it provides two things on the back end. Firstly, infrastructure like a database, file storage, and edge functions that run in the cloud. Secondly, on the front end, client-side SDKs that can easily connect this infrastructure to your favorite front-end JavaScript framework, React Native, Flutter, and many other platforms.

As a developer, you can manage your Postgres database with an easy-to-understand UI that automatically generates REST and GraphQL APIs to use in your code. The database integrates directly with user authentication, making it almost trivial to implement row level security. And, like Firebase, it can listen to data changes in real-time while scaling to virtually any workload.

To get started, you can self-host with Docker or sign up for a fully managed account that starts with a free tier. On the dashboard, you can create tables in your Postgres database with a click of a button, insert columns to build out your schema, then add new rows to populate it with data. By default, every project has an authentication schema to manage users within the application. This opens the door to row level security, where you write policies to control who has access to your data.

In addition, the database supports triggers to react to changes in your data and Postgres functions to run stored procedures directly on the database server. It's a nice interface, but it also automatically generates custom API documentation for you. From here, you can copy queries tailored to your database and use them in a JavaScript project. Install the Supabase SDK with NPM, then connect to your project and sign a user in with a single line of code. And now, you can listen to any changes to the authentication state in real-time with "on/off" stage change.

When it comes to the database, you don't need to write raw SQL code. Instead, you can paste in that JavaScript code from the API docs or use the REST and GraphQL APIs directly. And that's all it takes to build an authenticated full-stack application. However, you may still want to run your own custom server-side code. In which case, serverless Edge functions can be developed with Deno and Typescript, then easily distributed around the globe.

In summary, Supabase provides a complete back end for web and mobile applications based entirely on free open source software. It's a flexible and scalable solution that allows developers to easily build, deploy and manage their applications.
Daily UX Writing Challenge Day 5
Tags: beginners, ux, uxwriting
Published: 2023-03-07 02:16:38

[Day 1](https://dev.to/fuwa/daily-ux-writing-challenge-day-1-50la) | [Day 2](https://dev.to/fuwa/daily-ux-writing-challenge-day-2-4d6p) | [Day 3](https://dev.to/fuwa/daily-ux-writing-challenge-day-3-3cog) | [Day 4](https://dev.to/fuwa/daily-ux-writing-challenge-day-4-5cg8)


![Challenge: Write a message that the user will read immediately upon opening the app. What do they need to know? What steps (if any) do they need to take to recover their content? What if they can't recover the content? ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdv4xk3yqcahb9jva9k7.png)

For this one, I made a few assumptions. 1, the app has an auto save function (if it doesn't then that's bad UX - autosave should be built into everything with the ability to turn it off). 2, that the app detected it as crashing when the phone turned off. 

To help relieve the 'fear of loss' feeling the user might be feeling, I went for a short direct message to the user explaining what happened and letting them know that they can recover their work easily.
Karate API Testing Tutorial || Creating Karate API Framework From Start (Intro)
Tags: webdev, beginners, programming, tutorial
Published: 2023-03-07 02:15:45

In this video of Karate API Testing Tutorial, We are going to start our journey to learn API Testing with Karate even as a Complete Beginner. 

{% embed https://youtu.be/CSaBRZ9a2L4 %}

✅ Download Source Code - https://apitesting.co/2cKG

✅ Download Notes(PPT) -  https://sdet.live/karate-ppt

✅ Official Website for Learning Karate API Framework - https://github.com/intuit/karate


✅ What is Karate API?
Karate is an open-source API test automation tool. API tests are written using Behaviour Driven Development (BDD) Gherkin syntax

✅  We will learn difference between Karate vs Rest-assured.
Download the Doc. - https://sdet.live/karate-vs-restassured


✅ What is Karate Framework?
In this Karate Framework Tutorial, We are going to create the Own Karate API Testing Automation Framework, We will use the Person APIs(with JSON Server).

After that We will automate APIs of GitHub Repo V3.

There are multiple Karate API testing examples we are going to show you in this series.

✅ Why we Need Karate API Testing?
- Open source
- API Testing, Mocking,
- Performance Testing,
- UI Automation, Reporting
- Parallel Execution
- BDD Style, Native JSON/XML support.
- Readable syntax.
- Mix API and UI test-automation 

✅ What is Karate Test Framework?
- Karate is BDD testing framework
- Developer by Peter Thomas in 2017 (intuit).
- Cucumber style of writing the program which follows the BDD approach.
- Easy to understand by non-programmers
- Only API testing tool that can Mock, Do performance testing, Mix UI
- Automation Testing.
- Written in Java.
- Reuse features, Embed JS engine., Multi Thread parallel Execution. 

✅  What You should Know before Learning Karate API?
HTTP Protocols
JSON
Java Knowledge, (Basics of Javascript also)
Maven
Gherkin Syntax

✅ First GET Call with Karate.
- Install JDK 8(Java in path) - https://sdet.live/jdk18

- Install Maven - https://sdet.live/maven

- Sad no Intelli-sense
- Install Visual Studio Code. 
-- Extensions
Karate Runner

Sadly, We don't have karate framework setup intellij, but you can visual studio for that which is recommended.
Web Development: Day 1
Tags: css, beginners, react, nextjs
Published: 2023-03-07 02:00:52

# Day 1 - NavBar Component

Today I undertook to develop a custom navigation bar from scratch for the first time since learning how to utilize the Bootstrap API. With a wireframe I drew over the weekend to guide me, a trial-by-fire refresher on flexboxes, and responsive CSS units, I wound up with a  **still in development** Navigation bar that conformed with my skeletal mock-up.

## Challenges

Historically, I've had difficulty tracking the `display` property when planning a front-end. I credit React's functional components with forcing me to think much more atomically about the DOM, and thus children elements and their inheritance. 

## globals.css

I knew that I wanted the NavBar to display on every single page across the application, so I scoped it's styling globally. To start, I set properties for the entire document:
```
html,
body {
  padding: 0;
  margin: 0;
  max-width: 100vw;
  overflow-x: hidden;
  overflow-y: hidden;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
```
Next.JS adds in a root `<div>` with an id of `__next`. In order to frame the content of the application proportionally inside of the page, I added styling to this root element. 

```
#__next {
  height: 83.3vh;
  width: 83.3vw;
  display: flex;
  flex-direction: row;
  align-items: center;
}
```
The NavBar itself consisted of five buttons evenly spaced out in a column. I wanted the buttons to all stretch to fill the same space regardless of their text input. Here's what I came up with: 
```
.navbar {
  height: 83.3vh;
  width: 27.7vw;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}

.navitem {
  width: 100%;
  height: 20%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.navbar button {
  width: 16.6vw;
  height: 8.3vh;
}
```
## Takeaways

### Responsive Units

CSS has built-in units which make proportional, responsive sizing easy to do. `vh` and `vw` stand for 'viewport height' and 'viewport width,' respectively, and 1 unit of each represents 1% of the viewport's corresponding dimension. I used a straight-edge and pencil when developing the wireframe for the webpage, and I had anticipated a maze of ``` .nav { height: ??%; width: ??% }``` in getting the page to render as desired. Instead, using some middle-school mathematics, I was able to quickly determine the desired sizes in relative terms that translated directly into `vw`s and `vh`s. Not only does the sizing quickly translate, but it is *already responsive*. 

### Display

I left today thinking that the element that is receiving the `display: flex` property is being told "You will digest your immediate children in this matter." Cronus imagery aside, the flexbox reaches down *only one level*. This insight seriously assisted in reasoning out where and how each element would land. 

## Status Update

I ended the day with an extremely raw form of the navbar, but I am satisfied with it's geometry, so to speak. Tomorrow I'll take to building out the remainder of the homepage.
Checking Whether a Celery Task is Already Running
Tags: python, django, celery
Published: 2023-03-07 01:58:00

Ever tried to check whether a Celery task is already running?
Here is the piece of code I created for checking whether a task is running by its name.

```python
from celery import current_app


class CeleryHelper:
    """Contains helper functionalities to be used while interacting with Celery."""
    @staticmethod
    def is_being_executed(task_name: str) -> bool:
        """Returns whether the task with given task_name is already being executed.
        
        Args:
            task_name: Name of the task to check if it is running currently.
        Returns: A boolean indicating whether the task with the given task name is
            running currently.
        """
        active_tasks = current_app.control.inspect().active()
        for worker, running_tasks in active_tasks.items():
            for task in running_tasks:
                if task["name"] == task_name:
                    return True

        return False
```
I searchedd for that a while ago and I couldn't really find a direct way to do that in a Django project but the above code is tested and works in Django-based projects.
Explain about Linux Architecture
Tags: linux, linuxarchitecture, postgres, programming
Published: 2023-03-07 01:35:00

What is a Linux?

Linux is an operating system that uses a monolithic kernel architecture, where the kernel is the central component of the operating system and controls all hardware and software resources.

The Linux kernel is responsible for managing system resources such as CPU, memory, I/O devices, and network connections.

[](https://youtu.be/RYsr5XGIZmo)