teleren/devto huggingface dataset:
Creating multiple instances of OctoPrint for Raspberry Pi 3
Published: 2023-02-28 04:55:12

To set up two instances of OctoPrint on a single Raspberry Pi 3, you will need to follow the steps below:

1. Install OctoPrint on the Raspberry Pi 3 using the official installation guide.
2. Create a copy of the OctoPrint installation directory by using the command `sudo cp -R /home/pi/OctoPrint /home/pi/OctoPrint2`. This command will create a copy of the OctoPrint directory named OctoPrint2.
3. Edit the config file for the second instance of OctoPrint by using the command `sudo nano /home/pi/OctoPrint2/config.yaml`.
4. Change the port number for the second instance of OctoPrint. The default port number is 5000, so you can change it to another number like 5001 or 5002.
5. Save the changes made to the config file and exit the editor.
6. Start the second instance of OctoPrint by running the command `~/OctoPrint2/venv/bin/octoprint serve --port 5001` in the terminal.
7. Access the second instance of OctoPrint by going to `http://<Raspberry Pi IP address>:5001` in a web browser.

That's it! You now have two instances of OctoPrint running on a single Raspberry Pi 3. Repeat the above steps if you need to set up more instances. Note that running multiple instances of OctoPrint may require additional resources, so make sure your Raspberry Pi has sufficient memory and processing power to handle the load.

\#AI
Programming In python - Recursion made easy
Tags: python, beginners, programming
Published: 2023-02-28 04:47:10

## **Recursion in Python**

Recursion is a programming technique used in Python where a function calls itself repeatedly until a certain condition is met. The recursive function breaks down a problem into smaller subproblems and calls itself for each of the subproblems. It comprises of a base case (also known as a terminal case) and a recursive case. The base case is the condition that the function must meet to stop calling itself, while the recursive case calls the function repeatedly until the base case is satisfied.

When a function calls itself within its own body, it creates a new instance of the function with a new set of parameters. This process continues until the base case is reached, at which point the function stops calling itself and returns the results.

An exemplary illustration of a recursive function is the factorial function:
```
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)
```
In this instance, the factorial() function takes an integer `n` as input and returns its factorial. The base case is when `n` equals 1, and the function returns the final result.

Now, let us examine the function by analyzing each step of execution using an example `factorial(5)` which returns 120. When the function runs, the base case is not met as `n` (i.e., 5) does not equal 1. The function multiplies 5 by the function (i.e., the function calls itself), and this time `n` is 4 (which is 5-1). The function multiplies 4 by the function again with (4-1) as an argument, and the function calls itself repeatedly until the condition (2-1) is met, which equals 1. At this point, the function returns 1, and everything is multiplied out. The steps of the iteration are as follows:

**1.** 5 * factorial(4)
**2.** 4 * factorial(3)
**3.** 3 * factorial(2)
**4.** 2 * factorial(1)
**5.** 1 * 1 (because the base case was met and 1 is returned in that case)
Thus, the result of the function is `5 * 4 * 3 * 2 * 1 = 120`

However, it is important to note that recursive functions can be slower and consume more memory than iterative functions, as each function call creates a new instance of the function on the call stack. Therefore, it is crucial to use recursion judiciously and consider optimizing your code for performance.

In conclusion, we have now gained a deeper understanding of recursion. Should you have any further inquiries or suggestions to enhance the quality of this post, please do not hesitate to share them in the comments section. Thank you.
Send Email using Nodemailer to Google SMTP
Published: 2023-02-28 04:37:31

Express.js TypeScript function that takes in an email body and sends it to the Google SMTP server using an access and refresh token, as well as allowing the addition of CSS to the email template:

```
import express, { Request, Response } from 'express';
import nodemailer from 'nodemailer';

const app = express();

app.use(express.json());

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    type: 'OAuth2',
    user: process.env.GOOGLE_EMAIL,
    clientId: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    refreshToken: process.env.GOOGLE_REFRESH_TOKEN,
    accessToken: process.env.GOOGLE_ACCESS_TOKEN,
  },
});

app.post('/send-email', async (req: Request, res: Response) => {
  try {
    const { to, subject, body, css } = req.body;

    const mailOptions = {
      from: process.env.GOOGLE_EMAIL,
      to,
      subject,
      html: `
        <html>
          <head>
            <style>
              ${css}
            </style>
          </head>
          <body>
            ${body}
          </body>
        </html>
      `,
    };

    await transporter.sendMail(mailOptions);

    res.send('Email sent successfully');
  } catch (err) {
    console.error(err);
    res.status(500).send('Error sending email');
  }
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
```

In this example, we create an Express.js server and use the `nodemailer` library to create a transporter object that connects to the Google SMTP server using OAuth2 authentication. We then define an endpoint at `/send-email` that accepts a POST request with a JSON payload containing the to, subject, body, and css fields. The to field specifies the email address of the recipient, the subject field specifies the subject of the email, the body field specifies the body of the email, and the css field specifies any custom CSS styles to be applied to the email template.

In the endpoint `handler` function, we create a `mailOptions` object that contains the from, to, subject, and html fields.

Html field contains an HTML string that specifies the email template. This string includes a <style> tag that injects the CSS styles provided in the css field, as well as the body field that contains the body of the email.

We then use the `transporter` object to send the email using the `sendMail` method, passing in the `mailOptions` object.

If there are any errors during the sending process, we catch them and return a 500 error response. Otherwise, we return a success response indicating that the email was sent successfully.

Note that in order to use this function, you'll need to provide the required environment variables for the Google OAuth2 authentication, including the `GOOGLE_EMAIL`, `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GOOGLE_REFRESH_TOKEN`, and `GOOGLE_ACCESS_TOKEN` fields.
NGINX vs Apache, quem é o melhor?
Published: 2023-02-27 20:28:45

Além do Apache, existem muitos outros servidores de internet. Cada aplicação de servidores de internet foi criada com propósitos e características diferentes, enquanto o Apache é o mais usado no mundo atualmente, ele tem algumas alternativas e rivais.

Neste artigo vamos ver as principais diferenças entre o Apache HTTP Server e seu mais novo concorrente, NGINX.
NGINX é a mais nova aplicação de servidores de internet disponível. Criada em 2004 ela tem ganhado popularidade por proprietários de sites em todo o mundo.

O NGINX foi criado para um conhecido problema chamado **_c10k_**, em resumo este problema se trata de um servidor que utiliza seus mecanismos de manipulação de solicitações de usuário, mas que não consegue gerenciar mais de 10 mil conexões simultâneas. 

Sem mais delongas vamos ver qual deles é melhor:

1 - Como o Apache usa uma estrutura baseada em mecanismos, donos de sites com tráfego mais pesado podem ter problemas de desempenho. O NGINX é um dos servidores de internet que conseguem lidar com o problema c10k e é, provavelmente, o que mais eficiente nisso.

2 - O NGINX tem uma particularidade na arquitetura que não cria um processo para cada solicitação. Em vez disso, ele manipula todas as solicitações recebidas em um único encadeamento. Esse processo mestre gerencia vários processos de trabalho que executam o processamento real de solicitações. O modelo baseado em eventos do NGINX distribui as solicitações do usuário entre os processos do trabalhador de maneira eficiente. Isso leva a uma escalabilidade muito melhor.

3 - Apache é grátis, mesmo para usos comerciais, além de ter atualizações frequentes e novidades de segurança, além de ter uma comunidade gigantesca com suporte a qualquer caso de problema.

4 - Se você precisa gerenciar um site com grande tráfego, o NGINX é uma excelente escolha, pois, ele gerencia tudo isso usando o mínimo de recursos. Não é uma coincidência que ele seja usado por sites de grande visibilidade, como a Netflix, Hulu, Pinterest e Airbnb.

5 - Para sites menores e negócios que estão apenas começando, o Apache é a melhor escolha. Ele tem uma configuração mais fácil, vários módulos e um ambiente inicial de uso bastante amigável ao usuário. E essas são vantagens a se considerar em relação ao NGINX.

Em resumo, sites pequenos que bem provavelmente não terão muitos usuários (menos de 10 mil) podem, sim, utilizar o Apache visando facilidade de configuração e a ser mais amigável com o usuário, porem para aplicações de maior porte, pensadas para escalabilidade necessitam de servidores como NGINX.
How to read and write JSON files using Node.js
Tags: node, javascript, tutorial
Published: 2023-02-28 04:34:35

JSON is a lightweight format for storing and transporting data. Because JSON is easy to read and write it’s used by many programming languages not just JavaScript. In this tutorial I’ll show you how to read and write JSON files using Node.js.

Let’s start by first writing data to a JSON file.

Create new JavasScript file named `index.js` and include the File System (fs) module:

```javascript
const fs = require("fs");
```

Next we’ll declare a `books` variable that contains our JSON data:

```javascript
const books = [
  {
    title: "The Great Gatsby",
    author: "F. Scott Fitzgerald",
  },
  {
    title: "Frankenstein",
    author: "Mary Shelley",
  },
  {
    title: "The Call of the Wild",
    author: "Jack London",
  },
];
```

We then need to convert the JSON object to a string:

```javascript
const data = JSON.stringify(books);
```

Without converting to a string the data would be written as `[object, object]`.

Now we can write the data to a file using `fs.writeFile`:

```javascript
fs.writeFile("./data.json", data, "utf8", (error) => {
  if (error) {
    console.log(error);
  } else {
    console.log("writeFile complete");
  }
});
```

Run the code using `node index.js` and a new `data.json` file with the JSON data should have been created alongside the `index.js` file. If no file was created check the error messages that have been logged in the console to debug the problem.

Ok, now that we know how to write JSON data to a file let’s now read that data.

To read data we’ll use `fs.readFile` in the `index.js` file as follows:

```javascript
fs.readFile("./data.json", "utf8", (error, json) => {
  if (error) {
    console.log(error);
    return;
  }
  try {
    const books = JSON.parse(json);
    books.forEach((book) => {
      console.log(`${book.title} by ${book.author}`);
    });
  } catch (error) {
    console.log(error);
  }
});
```

This loops through each of the books in our JSON file and logs that data to the console:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5irekmlat41bbv08cwi5.gif)

That’s all for this tutorial. You should now have an understanding of how to use a simple JSON file to read and store data. While you’re here you may be interested in reading some of our other [Node.js tutorials](https://w3collective.com/tag/node/).
Ai Project management tools
Published: 2023-02-28 04:21:00

Project Planner has [AI project management tools](https://projectplanner.ai/) that helps streamline workflow and increase productivity. It offers features such as project scheduling, task management, resource allocation, and cost tracking. It also integrates with popular cloud services such as Dropbox, Microsoft Teams, and Google Drive. With Project Planner, users can easily set-up and manage projects, assign tasks to team members, and track progress. It also offers intelligence-driven analytics to help identify risks and opportunities, as well as optimize resources. The intuitive user interface makes it easy to manage projects and keep teams on track. Project Planner is designed to help organizations of any size get organized and work smarter, faster, and better.
Interview requirements nowadays !
Tags: aws
Published: 2023-02-28 04:05:28

**AWS + Devops + SQL **
EC2, VPC, Components of a VPC, S3, Glacier, Cloud front with S3 and EC2, AWS WAF, Kinesis,
App stream, Workspaces, Auto scaling, Load Balancers, Cloud watch, AWS Config, AWS Shield, Trusted Advisor, AWS Guard duty, Lambda (start stop EC2 instances), AWS Backup, AMI, EFS, Light Sail, VPC Peering, Landing Zone, AWS Organization, RDS, SNS, IAM, Cloud Trail, Route53, Ad Connector, Proxy, Reverse Proxy, Systems Manager, EBS, VPN – site to site and client VPN,
AWS Devops, Generic Devops, Terraform, Linux, Docker, SQL, bashscripting, Python
(I am mastering MYSQL, Bash Scripting, Python Programming)
652. Leetcode Solution in cpp
Tags: cpp
Published: 2023-02-28 03:51:25


```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
 public:
  vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
    vector<TreeNode*> ans;
    unordered_map<string, int> count;
    encode(root, count, ans);
    return ans;
  }

 private:
  string encode(TreeNode* root, unordered_map<string, int>& count,
                vector<TreeNode*>& ans) {
    if (!root)
      return "";

    const string encoded = to_string(root->val) + "#" +
                           encode(root->left, count, ans) + "#" +
                           encode(root->right, count, ans);
    if (++count[encoded] == 2)
      ans.push_back(root);
    return encoded;
  }
};
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/find-duplicate-subtrees/
3-part series on Create and Deploy applications using CodeDeploy and CodePipeline with Amazon S3 bucket versioning enabled
Tags: pipeline, codedeploy, s3, ec2
Published: 2023-02-28 02:55:35

For **better understanding and reading purposes**, I am linking all my previous 3 articles together with step-by-step instructions in this 3-part series, on how to create and Deploy applications using CodeDeploy and CodePipeline with Amazon S3 bucket versioning enabled.

1st article - **[3-part series - (1) Launch an EC2 Instance, Install CodeDeploy Agent and upload App_Linux.zip file to version enabled S3 bucket](https://dev.to/awsmine/3-part-series-1-launch-an-ec2-instance-install-codedeploy-agent-and-upload-applinuxzip-file-to-version-enabled-s3-bucket-dhp)**

2nd article - **[3-part series - (2) Create a CodeDeploy application and Deployment group](https://dev.to/aws-builders/3-part-series-2-create-a-codedeploy-application-and-deployment-group-47gk)**

3rd article - **[3-part series - (3) Create a CodePipeline pipeline and deploy the application on the instance](https://dev.to/aws-builders/3-part-series-3-create-a-codepipeline-pipeline-and-deploy-the-application-on-the-instance-1bbc)**

Please visit my **[GitHub Repository for CI-CD/Docker/ECS/ECR articles](https://github.com/awsmine/Docker_projects)** on various topics being updated on constant basis.
13 Concepts you must know to master Kubernetes
Tags: devops, kubernetes, devjournal, programming
Published: 2023-02-28 02:31:00

Kubernetes has become a defacto standard for hosting applications. 

Here are 13 K8s specific definitions you must understand to excel at it:


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


## 1/13: Node:
It is a machine that runs containerized workloads as part of a Kubernetes cluster. A node can be a physical machine or a virtual machine and can be hosted on-premises or in the cloud.

## 2/13: Docker:
Helps in the creation of containers that include apps and their binaries.

## 3/13: Pods
A basic building block of Kubernetes. It is the smallest and simplest unit in the K8S object model. It's also a group container. Only containers of same pod can share shared storage.

## 4/13: Service:
It is an abstraction which defines a logical set of pods and a policy by which to access them.

## 5/13: Jobs:
It creates pod(s) and ensures that a specified number successfully completed. When it completes specified number successfully, the job is considered complete.

## 6/13: Cronjobs:
Job scheduler in K8s. It creates Jobs on a repeating schedule.

## 7/13: Replicasets:
It ensures how many replica of pod should be running at any given time.

## 8/13: Namespaces:
Logical separation between teams and their environments. It allows various teams to share k8s cluster by providing isolated workspace.

## 9/13: Deployment:
It specifies the desired state of pods for declar­­ative updates.

## 10/13: Daemonset:
It ensures a particular pod is run on some or all nodes.

## 11/13: Persistent Volume:
Persistent storage in the cluster with an indepe­­ndent lifecycle.
It is a convenient way to request and consume storage resources. They live within a k8s cluster and can outlive other k8s pods to retain data for long periods of time.

## 12/13: Persistent Volume Claim:
Request for storage (for a Persi­­ste­­nt­V­o­lume) by a user. Claims can request specific sizes and access modes (e.g., they can be mounted once read/write or many times read-only).

## 13/13 Ingress:
An Ingress is a collection of rules that allow inbound connec­­tions to reach the cluster services.


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 in 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/).
New boost
Free Tailwind Css UI Kit with Material Design 3
Tags: tailwindcss, materialdesign, tailwindtemplate, css
Published: 2023-02-28 01:50:47

If you're looking for a UI kit for a Tailwind css project, Tailmater might be the perfect fit for you. Tailmater is an open source UI Kit based on Tailwind css framework. Built with Material Design 3 the latest version of Google's open-source design system.

![Tailwind css Ui kit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56b98m29u6k3j2jfb5sy.png)

## What's in the Tailmater UI kit?
Many components are ready for you to use to build a Tailwind css web project. The following are the components available in Tailmater.

- **Action** component contains various buttons such as the general button, floating action buttons (FAB), extended Fabs, icon buttons and segmented buttons.
- **Communication** component contains badges, progress indicators, and snackbar.
- **Containment** component contains cards, divider, lists, bottom sheets, dialogs, side sheets, and full screen dialogue.
- **Navigation** component contains the bottom app bar, navigation ba, bar, avigation drawer, navigation rails, search, top app bar and tabs
- **Selection** component contains a check box, radio, chip, switch, slider range and menu (dropdown)
- **Text input** component contains input text with the filled and outline.

In this project I have also completed it with a simple Vanilla Javascript so it is ready to use.

Demo component in here [https://aribudin.github.io/tailmater/](https://aribudin.github.io/tailmater/)

You can find a tailmater project at [https://github.com/aribudin/tailmater](https://github.com/aribudin/tailmater)

## How to start?
To start using tailmater is quite easy

- Clone the repository with the following command:
- `git clone https://github.com/aribudin/tailmater.git`
- Run in terminal this command:
- `npx tailwindcss -i ./src/tailwindcss/tailwind.css -o ./src/css/style.css --watch`
- Open html file in browser and start editing

Tailmater use the MIT license so you can use it included in a commercial project. Credit to the Github page will always be appreciated.

## Closing
If you like the “TailMater” project, please give a star on our [github page](https://github.com/aribudin/tailmater). We always accept contributions and proposals. You can also follow my Twitter [https://twitter.com/ari_budin](https://twitter.com/ari_budin) to get the latest updates.
How the heck a C program is compiled from human comprehensible language to 0's and 1's
Published: 2023-02-28 01:38:09

You may wondered how the programming languages lexemes are turned into a series of 0's and 1's aka binary files ?

Figure 2.11 - Book reference : Operating system concepts.

Let's discover that together step by step :

Usually programs a.out or program.exe ( games , word processors , web browsers ..) resides in your disk as a binary executable file , and in order to execute one of them , you need to fetch it from disk and put in memory , and it waits until it's scheduled to run and becomes a running program also known as a "process" which have a specific amount of memory addresses and executed by the units of cpu's core with the help of specific registers like program counters , IR ... and general-purpose registers .

but we don't write operating systems and Enterprise systems with binary right?

We need a human readable language , let's chose a compiled programming language like C to know the process of compilation .

After writing your program.c source code with human readable C , the source code is compiled & assembled to a relocatable object file program.o ( machine code that can be disassembled and turned into a geek-readable assembly ) ( we will talk about phases of compilation ( lexing , parsing , AST...) in future articles ) .

So we have now a object file , but we may called several functions like printf() which is also written by system programmers before to give us a layer of abstraction and increase our productivity , and compiled aka turned into an object file , it's part of GCC .

we need now to link all those object files and make them a single binary executable file that can be loaded into memory , this mechanism is done by what we call a " Linker " . (this is static linking)

the mechanism of loading the binary executable file into memory so it can be executed by one of the cpu's core is done by the loader , it's also responsible of addresses reallocation in memory..

You may heard about DLL ( dynamically linked libraries ) files in Windows right ? now we speak about dynamic linking . actually , most systems allows programs to dynamically link the libraries even if the program is already loaded and started execution ( that's good from memory optimization prospective, because the programmer may include a library and doesn't use it during runtime , i am sure we all did that before )

you know that modern systems allows multiple processes to share DLL ? yes they do!

And now you have a binary executable program into memory , also known as a process , with it's own memory addresses .

I will talk deeper next time about the compilation phases , and how the cpu fetch & decode & execute instructions & data from the bounded virtual memory of the process.