teleren/devto huggingface dataset:
O que é Graceful Degradation e qual a sua função na programação?
Published: 2023-03-14 03:33:49

Graceful degradation é uma técnica de design de software que tem como objetivo de garantir que um sistema continue a funcionar mesmo que algumas de suas partes falhem ou se tornem indisponíveis. Isso é feito por meio da implementação de mecanismos de fallback ou degradação que permitem que o sistema continue a operar em um nível reduzido de funcionalidade, em vez de falhar completamente.

A ideia por trás da técnica de degradação graciosa é que, em vez de tentar evitar completamente as falhas, é melhor planejar para elas. Ao fazer isso, é possível garantir que o sistema possa se adaptar a diferentes circunstâncias e ainda fornecer um serviço aceitável aos usuários. Isso pode ser especialmente importante em sistemas críticos ou de missão crítica, onde a falha completa do sistema pode ter consequências graves.

Os mecanismos de fallback podem incluir coisas como reduzir a qualidade da imagem ou do áudio em um sistema de streaming de vídeo, reduzir a capacidade de processamento ou armazenamento em um sistema de computação em nuvem, ou permitir que um site seja acessado em um modo básico quando certos recursos não estão disponíveis. Esses mecanismos de fallback são implementados em camadas diferentes do sistema, a fim de garantir que cada componente possa se degradar de forma independente sem afetar o restante do sistema.

Um exemplo prático de degradação graciosa é o funcionamento de um site de comércio eletrônico. Se o servidor do banco de dados ficar indisponível, o site pode continuar a funcionar, permitindo que os usuários naveguem pelos produtos e adicionem itens ao carrinho de compras, mesmo que não possam efetuar a compra no momento. Isso é uma forma de fallback, que permite que o site continue a fornecer um serviço aceitável aos usuários, mesmo em condições adversas.

Além disso, a degradação graciosa também pode ser usada para melhorar a escalabilidade do sistema. Em vez de dimensionar cada componente do sistema para lidar com o pico máximo de tráfego, é possível planejar para acomodar uma redução na capacidade de processamento ou armazenamento. Dessa forma, o sistema pode se adaptar a diferentes níveis de tráfego sem precisar de recursos adicionais.

Em resumo, a degradação graciosa é uma técnica importante para garantir que os sistemas possam se adaptar a diferentes condições e continuar a fornecer um serviço aceitável aos usuários, mesmo que algumas partes do sistema falhem. Isso pode ser especialmente importante em sistemas críticos ou de missão crítica, onde a falha completa do sistema pode ter consequências graves. A implementação de mecanismos de fallback pode ajudar a garantir que o sistema continue a operar em um nível reduzido de funcionalidade, em vez de falhar completamente.
Docker command for beginners
Tags: docker, beginners, tutorial, devops
Published: 2023-03-14 03:32:21


**Create container**
```bash
docker create <container_image>
```

**Remove image**
```bash
docker rmi <container_image>
```

**Start container (start container without output)**
```bash
docker start <container_id>
```

**Start container (start container with output)**
```bash
docker start -a <container_id>
```

**Run container (install, create and start container)**
```bash
docker run <container_image> <command_when_start>
```  

```bash
# -p is port mapping <local_browsing_port>:<container_running_port>
docker run -p 8000:8080 <container_image>
```

```bash
# -d is to executed in background
docker run -d <container_image>
```

```bash
# -p <host>:<container>
# -v <not_included> -v <host_path>:<container_path>
docker run -it -p 8080:80 -v /app/node_modules -v $(pwd):/app <container_id>
```

**List running container**
```bash
docker ps
```

**List all container**
```bash
docker ps -a
```

**Removing stopped container**
```bash
docker system prune
```

**Get log for certain container**
```bash
docker logs <container_id>
```

**Stop container (it will wait maybe 10 sec before it kill it)**
```bash
docker stop <container_id>
```

**Kill container (kill container immediately)**
```bash
docker kill <container_id>
```

**Execute an additional command in container**
```bash
# -i allow to enter in text (input) to containers terminal
# -t show a nice formatted input (eg: root@ip_address ~%  )
# -it is combined flag between -i and -t
docker exec -it <container_id> <command_to_execute>
```

**Getting full access or command prompt terminal in container**
```bash
# name_of_programs (eg: bash, powershell, zsh, sh)
docker exec -it <container_id> <name_of_program>
```

**Run docker file / Create docker image**
```bash
# go to Dockerfile/project directory
docker build <Dockerfile directory>
```

```bash
# create docker image with name
docker build -t <my_docker_id>/<project>:<version> <Dockerfile directory>
```

```bash
# -f is for custom filename other than Dockerfile
docker build -f <filename> <Dockerfile directory>
```

**Create docker image from container**
```bash
# -c is to set default command (in array) when image is running
docker commit -c "CMD ['ls', '-lah', '/var/www/html']" <container_id>
```

**Run docker compose**
```bash
docker-compose up
```

```bash
# —build is to build/rebuild containers
docker-compose up —build
```

```bash
# -d is to executed in background
docker-compose up -d
```

**Stop docker compose**
```bash
docker-compose down
```

**List container in project with docker-compose**
```bash
docker-compose ps
```
129. Leetcode Solution in Javascript
Tags: javascript
Published: 2023-03-14 03:21:46

```js
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumNumbers = function(root) {
    if (!root) return 0;
    var total = [];
    helper(root, 0, total);
    var sum = 0;
    for (var i = 0; i < total.length; i++) {
        sum += total[i];
    }
    return sum;
};

var helper = function(root, sum, total) {
    sum = 10 * sum + root.val;
    if (root.left === null && root.right === null) {
        total.push(sum);
        return;
    }
    if (root.left) {
        helper(root.left, sum, total);
    }
    if (root.right) {
        helper(root.right, sum, total);
    }
};

// a better and more concise solution
var sumNumbers = function(root) {
    return helper(root, 0);
};

var helper = function(root, sum) {
    if (!root)  return 0;
    if (root.left === null && root.right === null) {
        return 10 * sum + root.val;
    }
    return  helper(root.left, 10 * sum + root.val)
            + helper(root.right, 10 * sum + root.val);
};

// a third DFS method. Top-down
var sumNumbers = function(root) {
    if (!root) return 0;
    return helper(root, 0, 0);
};

function helper(root, currNum, sum) {
    if (!root) return sum;
    currNum = root.val + 10 * currNum;
    if (!root.left && !root.right) {
        sum += currNum;
        return sum;
    }
    return helper(root.left, currNum, sum) + helper(root.right, currNum, sum)
}
```
#leetcode
#solution
Here is the link for the problem:
https://leetcode.com/problems/sum-root-to-leaf-numbers/
¿Qué son los argumentos de la línea de comandos y para qué nos sirven en nodejs?
Tags: node, spanish, beginners, backend
Published: 2023-03-14 03:09:53

Hace unos días trabajaba con unos repositorios que tenían una extraña manera de ser inicializados:

```shell
npm start <auth_token>
```
Analizando mejor el código di con `process.argv` que es un array que contiene los argumentos que le pasemos en la línea de comandos. 

Al inicio puede sonar algo que no tenga mucha utilidad, pero en ciertos casos puede ahorrarnos tiempo al ejecutar node. 
Te daré dos ejemplos.

Imaginemos que tenemos este sencillo código:
```js
const express = require("express");
const app = express();
const port = 4000;

app.get("/", (req, res) => {
  res.send({message: "works!"});
});

app.listen(port, () => {
  console.log("Servidor levantado en puerto:", port);
});
```
Una manera de cambiar el número de puerto es directamente en el código o con el uso de variables de entorno. Pero también podemos definirlo directamente cuando iniciamos el servidor desde la línea de comandos:

```shell
npm start 4001
```

```javascript
const express = require("express");
const app = express();

console.log(process.argv);
app.get("/", (req, res) => {
  res.send(process.argv[2]);
});

app.listen(process.argv[2], () => {
  console.log("Servidor levantado en puerto:", process.argv[2]);
});
```
Ahora nuestra app inicia en el puerto 4001 ¿Qué pasó? Cómo indique anteriormente process.argv es un array que contiene los argumentos que le pasemos. Pueden ser uno o más argumentos y son tomados a partir del índice 2 (los dos primeros índices están reservados). 
Ahora podemos iniciar la app desde el puerto que queramos sin modificar ninguna línea de código. 

En el segundo ejemplo, supongamos que tenemos una API que necesita de un token para trabajar, hasta aquí nada del otro mundo, pero este token debe ser renovado cada hora. 
Podemos ejecutar la renovación, copiar y pegar el token en el código cada hora o simplemente aprovechar la facilidad que nos da process.argv.

```shell
npm start uVMjbebCEFnj3=zl?Ha91fbddeoXjPcu!rO!aCd-UdbbNjWAVEVthegd5HEbgYs!
```
Aquí inicio el servidor con un token random. Guardo este token en una variable y funciona correctamente. 

```javascript
const token = process.argv[2] 
```
Espero te haya servido este dato, si no lo usas activamente quizá te lo encuentres en algún momento y no está demás conocerlo.
Why I choose CRA ( Create-react-app) over Vite for this React project ?
Tags: react, javascript, vite, webdev
Published: 2023-03-14 03:00:27

You must have stumbled upon many posts praising Vite and how it should be the de-facto standard to get started with React apps. Vite is awesome, nothing wrong with it. But, sometimes I just believe when you're put into this decision-making situation, you should give yourself some time instead of blindly picking the new tech upgrade in the market and ditching the older one.

I still use both CRA (create-react-app) and Vite for my React projects. In the organization (Mercedes Benz) I work, we had to start a new project from nothing. We had interns, and junior developers to collaborate with on that project. The project requirements were mostly already defined and were not likely to change in a short period. It was established to be a small to medium-sized full-stack application with an estimated completion time of two months. There weren't major performance-related concerns so I decided to pick CRA even though I, myself am a big admirer of Vite.

CRA has been proven successful over these many years and got support from Facebook. It was easier to find help related to deployment, installation of new packages and more issues in case they show up in the development process (which they would). It is not an app which is likely to be in the development phase for a long period. Had that been the case, or we were likely to face performance-related issues in the long run because of the app being too bulky, I'd have opted to go with Vite. But, that wasn't the case here. Sticking with CRA ensures that we have more help available on the internet, less time spent on learning and more in development. Most packages have stable compatible versions with CRA available with proper documentation. So, why not stick with it?

I've seen some developers blindly going for the upgrades in the market instead of considering the older technology while making architectural-level decisions in designing an application from scratch. In my opinion, it is completely fine to sometimes stick with older tech stack even while creating new applications. I'd bring Vue into the picture for a moment where there is a buzz in the market about why you should ditch Vue 2 ever since a stable version of Vue 3 has been released. But, why always? Why can't I use Vue 2.6 in my apps in 2023? Maybe there is a UI library that only has a stable version for Vue 2. It is your choice to still use Vue 2 or create-react-app, it is not obsolete and not likely to be so for the next few years. So relax, and use what you love. You should however have a pretty convincing reason to justify your choice.

So, that's it for this post. Here, I just put my two cents on why it's fine to continue using existing technologies despite them having better upgrades available. If you have anything to say, please comment in the comments section. See you in the next post. 😀
Server Sent Events in Go
Tags: go, javascript, programming, webdev
Published: 2023-03-14 02:59:45

👉 [Read the complete article on TheDeveloperCafe](https://thedevelopercafe.com/articles/server-sent-events-in-go-595ae2740c7a)

# Introduction

In this article, I will demonstrate how to set up a basic SSE (Server Sent Events) endpoint in Go. The complete code related to this article is available in [this](https://github.com/gurleensethi/go-server-sent-event-example) GitHub repository.

**Example:** We are going to assume an example of a live crypto price api.

# Project Setup

Initialize a new go project.

```bash
mkdir go-server-send-events-examples
cd go-server-send-events-examples
go mod init github.com/gurleensethi/go-server-send-events-examples
```

Create a `main.go` file with basic http server setup.

```go
package main

import (
	"net/http"
)

func main() {
	http.ListenAndServe(":4444", nil)
}
```

# Mocking live data

Write a function that generates random integers every second. This function will simulate live crypto price data that you will send back to the client.

```go
func main() {
	...
}

// generateCryptoPrice generates price as random integer and sends it the
// provided channel every 1 second.
func generateCryptoPrice(ctx context.Context, priceCh chan<- int) {
	r := rand.New(rand.NewSource(time.Now().Unix()))

	ticker := time.NewTicker(time.Second)

outerloop:
	for {
		select {
		case <-ctx.Done():
			break outerloop
		case <-ticker.C:
			p := r.Intn(100)
			priceCh <- p
		}
	}

	ticker.Stop()

	close(priceCh)
}
```

The `generateCryptoPrice` function accepts a **one-way** write-only channel to which it sends the live price. It uses `time.Ticker` with a duration of 1 second to send a price update.

Furthermore, we receive a `context` that we can use to stop sending price updates. For instance, if the client disconnects, the context is cancelled, and price updates cease.

`math/rand` package is used to generate random integers.

...

👉 [Read the complete article on TheDeveloperCafe](https://thedevelopercafe.com/articles/server-sent-events-in-go-595ae2740c7a)
Better online presence with ChatGPT For Search Engines
Tags: chatgpt, ai, api
Published: 2023-03-14 02:38:53

If you're an Internet user who often searches for information online, you may have noticed how frustrating it can be to sift through countless search results that don't quite answer your questions. That's where the [ChatGPT For Search engines](https://chrome.google.com/webstore/detail/chatgpt-for-search-engine/feeonheemodpkdckaljcjogdncpiiban) comes in that leverages the power of artificial intelligence to help you find what you're looking for faster and more accurately.

So, what exactly can ChatGPT For Search engines do? Let's take a look at some of its new version’s functions and features:

##Top ChatGPT Prompts: 

This is one of the standout features. Available questions or prompts are suggested by world-wide users. By clicking on one of these prompts, you can refine, add and edit your search and get more specific results.

You can choose a topic you like, from Economics to Architecture or  Code, the results that appear can also be sorted by Top/Latest Prompts or Most upvoted ones and you can also search prompt by typing key words.

##Template Content:

ChatGPT Extension offers a wide range of template content that users can take  as a starting point for their writing projects. These templates include Blog Outline, Interview Questions, Product Review and more. Even with just a quick click to the taskbar on the left, you can select what kind of content you want to write, ranging from Blog, to Email, to Website Copy.

##Trigger Mode: 

There are currently 3 options available: Always (to respond right away), Question (to respond when there is a question mark at the end of a phrase) and Manual (to click on the searchbar to ask). 

These features which suit each user’s preference allow them to customize how ChatGPT replies to their requests.

##Api options:

The API options include ChatGPT WebApp, which is free but often unstable due to user overload. OpenAI's API, in contrast, is more consistent but charges based on usage.

ChatGPT For Search Engines can be a helpful tool for anyone who wants to search the web quickly and get more accurate online information.
Implement browser history
Published: 2023-03-14 02:27:48

**Problem Statement -**

You must be familiar with browser history and its functionality where you can navigate through the browsed history. Implement the same.

It will have the following functionality

visit(url): Marks the entry of the URL in the history.
● current(): Returns the URL of the current page.
● backward(): Navigate to the previous url.
● forward(): Navigate to the next url.

Example

```
Input:
const bh = new BrowserHistory();
bh.visit('A');
console.log(bh.current());
bh.visit('B');
console.log(bh.current());
bh.visit('C');
console.log(bh.current());
bh.goBack();
console.log(bh.current());
bh.visit('D');
console.log(bh.current());
Output:
"A"
"B"
"C"
"B"
"D"


```
We can implement this with the help of an array and index tracker for navigation.

For each visit, add the URL at the next index. while navigating backward return the URL of the previous index, going forward return the URL at the next index. Add checks to prevent the under and overflowing of the indexes.

```
function BrowserHistory() {
  // track history
  this.history = [];
  this.index = -1;
  // add new url at next index
  this.visit = function(url){
    this.history[++this.index] = url;
}
  // return the url of the current index
  this.current = function() {
    return this.history[this.index];
}
  // go to previous entry
  this.backward = function() {
     this.index = Math.max(0, --this.index);
}
  // go to next entry
  this.forward = function() {
     this.index = Math.min(this.history.length - 1, ++this.index);
} }
```
**Test Case**

```
Input:
const bh = new BrowserHistory();
bh.visit('A');
console.log(bh.current());
bh.visit('B');
console.log(bh.current());
bh.visit('C');
console.log(bh.current());
bh.backward();
console.log(bh.current());
bh.visit('D');
console.log(bh.current());
bh.backward();
console.log(bh.current());
bh.forward();
console.log(bh.current());
Output:
"A"
"B"
"C"
"B"
"D"
"B"
"D"

```
Db accident
Published: 2023-03-14 02:08:52

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author A
 */
public class accident {

    public static void main(String args[]) throws ClassNotFoundException, SQLException {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practice", "root", "");
            Statement stmt = (Statement) con.createStatement();
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter report no");
            int report_no = sc.nextInt();
            System.out.println("Enter acc date");
            int acc_date = sc.nextInt();
            System.out.println("Enter Location");
            String location = sc.next();

           String sql = "INSERT INTO accident values('" + report_no + "','" + acc_date + "','" + location + "'); ";
            stmt.executeUpdate(sql);

     /*  ResultSet rs=stmt.executeQuery("select count(*) as query from accident where acc_date='2008-01-01';");
                rs.next();
                int query=rs.getInt("query");
                rs.close();
                System.out.println("mytable has "+ query +" rows");*/
       
       ResultSet r=stmt.executeQuery("SELECT count(*) as query FROM car,accident WHERE car.model='abc' AND report_no=1 ;");
                r.next();
                int query=r.getInt("query");
                r.close();
                System.out.println("mytable has "+ query +" rows");
            
                
  //              while (rs.next()) {
  //              System.out.println(rs.getInt(1) + " " + rs.getInt(2) + " " + rs.getString(3));


            }
        } catch (SQLException ex) {
            System.out.println(ex);

        }
    }
Db emp id above 18
Published: 2023-03-14 02:08:10

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author A
 */
public class age {
    public static void main(String args[]) throws ClassNotFoundException, SQLException {
       
        try{
                Class.forName("com.mysql.jdbc.Driver");
            try (
                    Connection Con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","")) {
                Statement stmt =(Statement) Con.createStatement();
                Scanner sc= new Scanner(System.in);
                
                ResultSet rs = stmt.executeQuery("Select * from emp where id<18");
                while (rs.next()){
                    System.out.println(rs.getInt(1)+" " + rs.getString(2));
                }
            }
        } catch (ClassNotFoundException | SQLException ex) {
            //Logger.GetLogger(java.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex);
    
}
        }
    }
Save to db
Published: 2023-03-14 02:06:37

import java.sql.*;
import java.util.Scanner;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author A
 */
public class department {
     public static void main(String args[]){
       
        try{
                Class.forName("com.mysql.jdbc.Driver");
            try (Connection Con = DriverManager.getConnection("jdbc:mysql://localhost:3306/department","root","")) {
                Statement stmt =(Statement) Con.createStatement();
                Scanner sc= new Scanner(System.in);
                
                System.out.println("enter department you want to diplay:");
                String dept=sc.next();
                ResultSet rs = stmt.executeQuery("Select * from emp where dept='"+dept+"'");
 
                while (rs.next()){
                    System.out.println(rs.getInt(1)+" " + rs.getString(2)+" " +rs.getInt(3)+" "+rs.getInt(4)+" "+rs.getString(5));
                }
            }
            
        } 
                    catch (ClassNotFoundException | SQLException ex){
            //Logger.GetLogger(java.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex);
    
}
        }
     }