teleren/devto huggingface dataset:
Microservices E-commerce Boutique Tutorial — Part 1
Tags: python, microservices, eventdriven, tutorial
Published: 2022-02-10 18:40:54

Welcome to the [Minos Framework](https://github.com/minos-framework/minos-python) tutorial.
The idea of ​​this tutorial is to create an **Online E-commerce Boutique with Minos cloud-native microservices**. 
The project consists of an application of 9-tier microservices. The final result will be an API REST that will allow you to perform the basic operations of an e-commerce.
![Ecommerce Architecture View](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ajguk12f87ah3u7yarzu.png)
**What is Minos**
Minos is a framework that helps you create reactive microservices in Python. Internally, it leverages Event Sourcing, CQRS and a message-driven architecture to fulfill the commitments of an asynchronous environment.
**Requirements**

- python 3.9+
- Poetry
- Docker and docker-compose

**Installation**
install the minos-cli

`$:(venv)> pip install minos-cli`

**Create the Project**

`$:(venv)> minos new project myboutique`

The cli will ask you:

- the name of the project ( myboutique )
- the description of the project ( My fantastic online boutique )
- The version ( 0.1.0 ), is not necessary to modify this information during the quickstart

With this, the project structure is created, now we will configure the database and the broker message.
Go to the myboutique folder and let’s start by configuring the database.

`$:(venv)> minos set database postgres`

The CLI will ask:

- where do we want to deploy our project? for this project we will use docker-compose
- Where will be PostgreSQL database hosted? we have two options self-hosted and remote.
   - Self-Hosted: which mean that we install a POD in our 
     kubernetes, which is our case.
   - Remote: this option would be if we already have a 
     PostgreSQL instance in our laptop or in a remote server.
     Select self-hosted option.

Now we will continue by configuring the broker service

`$:(venv)> minos set broker kafka`

the CLI will ask if we want to use a self-hosted or a remote Kafka broker, we choose self-hosted option.

**Deploy the project**
before we start creating the microservices, we have to test our project and deploy the project.

`$:(venv)> docker-compose up`

after some time, we will see the required services already up.
Now, finally, we can create the first Microservice.

> If you found this article interesting, then remember to leave a star in the [Minos repository](https://github.com/minos-framework/minos-python)
A reminder to self
Published: 2022-02-10 18:33:47

I should have posted this earlier - it happened last week - but here goes a reminder to future self:

When you're tired and it feels like your mind is stretched too thin, just take a break and do something - whatever! - else.

A couple of weeks back I was trying to recreate a simple about page from a image that had been provided as reference. 

It was all going well until I tested the fluidity of the page and although it all looked great on full screen, any changes to screen size would cause the image to flow out of the section.

I tried several tips from all over StackOverflow, but they were more directed at images inside their own containers and didn't help me much.

Almost at the point of giving up I realized a super tiny detail: I hadn't set a max width to the section.

Boom, fixed it. The image stayed put, increasing or decreasing in size with the rest of the content.

That took me too long to fix, but I'm aware this is just a small taste of things to come.
Display Messages in Browser Console using Figlet
Tags: javascript, beginners, programming, tutorial
Published: 2022-02-10 18:24:34

Here how you can display beautiful messages in a browser console using Javascript. You just need to download a library called [Figlet](https://github.com/patorjk/figlet.js/).

After download, you need to extract the zip file and copy the file **lib/figlet.js** in your project. You also need to copy the **fonts** folder too.

Then you need to include that library in your project using the script tag:

```
<script src="figlet.js"></script>
```

Right after that, you can display the message you want in the browser console:

```
<script>
	// initialize the library

	const textDisplay = "adnan-tech.com";
	const font = "Speed";

	figlet(textDisplay, font, function (error, text) {
		// display the text in console
		console.log(text);
	});
</script>
```
Serverless SWOT analysis
Tags: serverless, swot, aws, lambda
Published: 2022-02-10 18:23:14

Building a serverless application means you usually trade in old issues for new ones. This is an attempt to create a decision framework and break down arguments for and against using serverless vs. other computing models.

If you ever find yourself deciding for or against serverless the following tries to make the decision easier for you. Maybe you should save this post for future reference if you find it useful. Or don't, it's up to you. No seriously, save it.

This is also an open document which I will keep improving in the future. Edits are welcome!

## Strengths

1.  **Faster time to market** -- The real benefit of serverless is that developers only focus on the business logic and that drastically increases development speed and time to market.
2.  **Scalability** -- If you follow the right architectural patterns, serverless is very scalable.
3.  **Cost effectiveness** -- In most cases, serverless is cheaper than other computing models although exceptions apply for some forms of compute heavy data processing/background jobs.

## Weaknesses

1.  **Troubleshooting and testing** -- It's difficult to test locally and it's difficult to navigate debugging data. You can set up a local environment for testing but it will take a lot of effort. [Dashbird](https://dashbird.io/features/) is good for observing and debugging production architectures.
2.  **Learning curve** -- New patterns and tooling can take a while to learn and adopt.
3.  **Developer onboarding** -- Bigger learning curve for new developers mid-project.

## Opportunities

1.  **Observable by default** -- All serverless architectures are **observable** by default. Keep in mind that it does not mean you'll get any visibility, it just means that most of the data necessary to understand your service is actually available in AWS through:

-   **APIs** (CloudFormation, Lambda, API Gateway)
-   **Logs** (CloudWatch and CloudTrail)
-   **Metrics** (CloudWatch)

Services like [Dashbird](https://dashbird.io/) structure and visualize that information to make it navigable and simplify troubleshooting.

2.  **SAML and other services** -- If done well, you can get large parts of your service just by using available Lambda functions and services for auth etc.
3.  **Hype** -- Developers are excited to work with new technologies, meaning that they are less likely to quit and it's easier to hire.

## Threats

1.  **Performance issues and latency** -- Poorly constructed architectures, cold starts and database connections running out.
2.  **Lock in** -- Hard to migrate to Docker containers later if for some reason that's necessary.
3.  **Security** -- Bigger surface area for loopholes and higher complexity for security audits.

## Conclusion

As you can see there are significant upsides and downsides, but if you make sure to structure your software right, the benefits greatly outweigh the downsides!

If you have any feedback, the comment section is all yours. I'd love to hear what you have to say. I will be updating this analysis regularly.
Day-21 Training at Ryaz
Published: 2022-02-10 18:20:03

Date:10/02/2022
Day:Thursday

Today I started at about 10:10 am today I was to trouble shoot the website that I was been creating and was to deploy it. I was able to troubleshoot all changes and deploy it successfully.As I started with troubleshooting the appearance of images and I was able to solve it out.As It took me about 4-5 days to compleate the demo website that was to be created while viewing the course provided of HTML/CSS. As this journey was very interesting journey of Learning things and doing practice 
side-by-side it helped me a lot and have enhanced my skill. As I found my approach that I was using at beginning of course was totally different from that I have practiced now a days while building the website. I get to know many new concepts like concept of .svg file, declaring colour at root level and many new things.
Python #7 - estruturas de repetição
Tags: beginners, python, codenewbie, programming
Published: 2022-02-10 18:01:38

_Esse post faz parte dos meus cadernos **pessoais** de estudos. Todas as anotações são baseadas nas aulas da Mentorama - Cientista de Dados do zero e organizadas sob o meu ponto de vista. M3A2._

---

### Estruturas de repetição 

Repetir blocos de código de maneira automática. 

### FOR

**`for`:** Executa um número fixo de vezes 

`notas = [9, 9.5,8,8.5,7,6.5]
for nota in notas:
print(nota)`


- iterar em listas (percorrer a lista)

`for num in range(1,10,2):
    print(num)`


- iterar em strings 

`for letra in "PYTHON":
    print(letra)`

- Iterar em dicionários 

`​dic_aluno_nota = {"Maria": 7.5, "Joao": 9, "Pedro":6, "Mariana":10, "Paulo": 6.5}`

com duas variáveis iteradoras:

`for aluno, nota in dic_aluno_nota.items():
    print(aluno,":", nota)`

`Maria : 7.5
Joao : 9
Pedro : 6
Mariana : 10
Paulo : 6.5`

- Combinar o loop for com a estrutura if-else

`alunos_reprovados = {}
alunos_aprovados = {}
for aluno, nota in dic_aluno_nota.items():
    if nota < 7:
        alunos_reprovados.update({aluno:nota})
    else:
        alunos_aprovados.update({aluno:nota})`

#### Alterar execução de loops

**`break:`** interrompe o loop 

`L1 = range(1,50,2)
L2 = range(1,50,1)
for i, j in zip (L1,L2):
    if i*j > 100:
        break
    else:
        print("i vezes j é:", i*j)
print("Aqui o loop já parou!")
print("Os próximos i e j seriam:", (i,j))`

**`continue:`** não para o loop, e sim ignora o que está abaixo dele e avança para a próxima iteração 

---
#### WHILE

**`while`:** Executa enquanto uma condição é verdadeira

`erro = 30 
while erro > 11:
    print("O erro ainda é maior que 11, é", erro)
    erro = erro - 2 #sem essa linha ele nao para
print ("\n fim do while com erro igual a", erro)`

dentro do while é necessário iterar a variável para que em algum momento ela seja falsa
Blank Page when running in localhost:3000
Published: 2022-02-10 17:43:20

When trying to run my React App locally I get a blank page (I believe this is index.html) when I go into tools>console I get these messages in response:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u0f563xr038ler6i5it5.png)
When I click (bundle.js:62158:33) I'm shown:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ueoqdm1t11d8hbne1pfp.png)

Is this preventing the page from loading?
Set theory(with PHP)
Tags: php, logic, set, sheet
Published: 2022-02-10 17:41:01

Heres a Cheat Sheet I made for joins! Also, here are some PHP 8 examples with sets. It`s important to master the basics, because in the future you`ll spend less time trying to build workarounds for simple solutions.


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

`<?php

$array_a = [1,2,3,4,5];
$array_b = [2,3,4,5,6];

function left_excluding_join($left, $right) {
    return array_diff($left, $right);
}

function left_outer_join($left, $right) {
    return $left;
}

function right_excluding_join($left, $right) {
    return array_diff($right, $left);
}

function right_outer_join($left, $right) {
    return $right;
}
     
function full_join($left, $right) {
    return array_unique(array_merge($left, $right));
}     

function inner_join($left, $right) {
    return array_intersect($left, $right);
}  

function outer_excluding_join($left, $right) {
    return array_diff(full_join($left, $right), inner_join($left, $right));
}  
echo "=== LEFT EXCLUDING JOIN ===\n";
print_r (left_excluding_join($array_a, $array_b));

echo "=== LEFT OUTER JOIN ===\n";
print_r (left_outer_join($array_a, $array_b));

echo "=== RIGHT EXCLUDING JOIN ===\n";
print_r (right_excluding_join($array_a, $array_b));

echo "=== RIGHT OUTER JOIN ===\n";
print_r (RIGHT_outer_join($array_a, $array_b));

echo "=== FULL JOIN ===\n";
print_r (full_join($array_a, $array_b));

echo "=== INNER JOIN ===\n";
print_r (inner_join($array_a, $array_b));

echo "=== OUTER EXCLUDING JOIN ===\n";
print_r (outer_excluding_join($array_a, $array_b));
`

And the results:

`=== LEFT EXCLUDING JOIN ===
Array
(
    [0] => 1
)
=== LEFT OUTER JOIN ===
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
=== RIGHT EXCLUDING JOIN ===
Array
(
    [4] => 6
)
=== RIGHT OUTER JOIN ===
Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
    [4] => 6
)
=== FULL JOIN ===
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [9] => 6
)
=== INNER JOIN ===
Array
(
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
=== OUTER EXCLUDING JOIN ===
Array
(
    [0] => 1
    [9] => 6
)
`
What are CSS Variables and How to Use Them
Tags: css, css3, webdev, beginners
Published: 2022-02-10 17:39:07

CSS variables give you the opportunity to declare variables in your CSS code. Currently, the support is around 96%, which means you should be able to use it without worrying. Of course to be at 100% confidence, you can always check Can I use to make sure that you are not trying to target a browser that is not capable.

### Using the :root psuedo-class

Custom properties or CSS variables allow us to re-use a variable property to substitute inside of a CSS property. Let's take a look at an example.

```css
:root {
 --my-bg-color: blue;
}

.my-class {
 font-size: 16px;
 background-color: var(--my-bg-color);
}

.my-other-class {
 font-size: 20px;
 background-color: var(--my-bg-color);
}
```

In our example above, we are declaring a variable name under :root psuedo-class. When we define our variable --my-bg-color under this psuedo-class, we are able to use this anywhere globally in our code. We call the variable in our code using the var() function provided. This injects the property value of --my-bg-color inside our property value so the output would replace the statement with the color blue in this case.

### Using the var() function
The var() function can accept a default or fallback value to the property value if our custom variable name is not defined or available.

```css
.my-other-class {
 font-size: 16px;
 background-color: var(--my-bg-color-value, red);
}
```

In the scenario above, if the value of --my-bg-color-value is not available, then the default value of red will be called in this case and used. We can also add more variables to the check if needed.

```css
.my-other-class {
 font-size: 16px;
 background-color: var(--my-bg-color, (--my-bg-color-value, red));
}
```

Here we are checking for two variables, and if neither are found then we default the value to be red. Do note that doing this may cause performance issues as it takes more time to parse through the variables.

### Quick Takeaways
- CSS variables are great to use in your CSS to declare custom values
- We declare our variables inside the :root psuedo-class
- Using the var() function we can call our custom property inside of a property
- You can chain multiple calls as the second argument to var(), but there may be performance implications
Flask: template context processors
Tags: python, flask
Published: 2022-02-10 17:38:27

---
title: "Flask: template context processors"
published: true
description: Notes about how and why to use template context processors in Flask
tags: python, flask
//cover_image: https://direct_url_to_image.jpg
---

Template context processors allow values to be injected into the the template rendering context before rendering occurs.

They are essentially very simple functions that return a map whose keys will be available as "global" variables in the template rendering phase.

It allows you to avoid boilerplate code in the request handlers and makes sure that the data passed in the `render_template` is specific to that route and handler.

## Use cases

Template context processors work best when the data you want to use is relatively static, say configuration information that is fixed at app initialisation, cached data or things that are easy to programatically generate, such as the names of the last six months.

Because the processor is called on every render call you want to make sure it is either fast and efficient or necessary.

Commonly you use it for information that is needed on every page; things that are part of your root template. Typically this means things like analytics configuration, exception reporting, navigation and footer links.

While you can use them to attach information to the user context or calculate data based on the current user I think that can be quite dangerous and its better to keep user-dependent data out of the template processors.

## Installing your processors

There is a processor annotation that you can apply to a function or you can call `context_processor` on the app object itself which I think is clearer.

You can register multiple processors by calling the `context_processor` multiple times with different arguments but that's not completely obvious and it might be better to compose your processors into a single function yourself.

## Further reading

* [Flask's documentation](https://flask.palletsprojects.com/en/2.0.x/templating/?highlight=context%20processors#context-processors)
API router wrapper for Express node.js
Tags: javascript, node, express, router
Published: 2022-02-10 17:10:53

Hello everyone 👋, I'm Naren.

I have developed a plugin to declare express api routes in node js in a easy way.

Feel free to check it out. Any corrections in plugin is highly appreciated. 

Here's the npm [link](https://www.npmjs.com/package/@naren_codes/server-router) and brief explanation of the plugin.

## Installation

```npm i @naren_codes/server-router```

### Getting Started

```
const Router = require("@naren_codes/server-router");

const API_ROUTE = {
     // API url
     path : "user",
     // API method
     method : "get",
     /* Before Enter middleware - called before calling api handler 
        If returned Promise will call next() on resolve and ends api request without calling handler on reject
        If returns nothing calls next() after beforeEnter
        @params - request object
     */
    // Optional
     beforeEnter : (req) => {
          return Promise.resolve();
     },
     /* Api Handler - should return promise 
        @params - request object
     */
     handler : (req => {
          return Promise.resolve({
               data : "Hello World", // Response data for the api request
               status : 200, // Send any HTTP statuses
               headers : {
                    // Declare any response header to be binded in the request here
                    "Content-Type" : 'application/json', // Optional by default express will evaluate Content-Type
                    "Cache-Control" : `max-age=1000`
               },
               // Declare any cookies to be set in the client's browser
               cookies : {
                    auth_token : token
               }
          });
     }),
     // Child routes based on current route
     children : [
          {
               // userId will be a Dynamic value
               path : ":userId",
               method : "get"
               // Declare handler, beforeEnter, children
          }
     ]
}

/* @params { app, options }
 * app - app object obtained by called express() middleware
 * options - params to be passed for the router
*/

new Router(app, {
     routes : [
          API_ROUTE
          // other api routes
     ],
     /* For static based compressions and serving index.html on all routes 
      * path - folder containing static files (js/css/html)
      * entry_point - for single page applications html mentioned here will sent to browser for all routes that does not match declared routes
     */
     static : {
          path : path.resolve("./server/public"),
          entry_point : "index.html"
     }
});
Topological Sorting in a directed acyclic graph(DAG)
Tags: python, algorithms, graph
Published: 2022-02-10 16:52:44

#What is Topological Sort ?
It is an ordering of vertices in DAG, such that for every edge u to v, u comes before v.

**Important point to note**
1) It is not possible to do a topological sort if the graph has a cycle, since in a cycle it is impossible to know the order of vertices
2) There can be many possible orders of topological sorting

**Example**
![img](https://i.stack.imgur.com/8Nt1U.png)
**Possible Topological Orders:**

[1, 2, 3, 4, 5, 6, 7, 8]
[3, 2, 1, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 7, 6, 5, 8]

#Uses of topological sorting
1) Managing tasks which are dependent on other tasks, suppose task B can only be completed if task A has been completed. So the graph would be: 
**A --> B** 
and the topological order would be **[A, B]**.
2) Managing courses and prerequisite courses, for example we have an Algebra(Al) course which has a prerequisite of Basic-Math(BM) course, the graph would be:
**BM --> Al**
and the topological order would be **[BM, Al]** meaning a student should complete BM course before taking Al course.

#Algorithm
We need a **hash set** to store the vertices we have visited and a **stack** to store the order.

1) Pick a vertex(v) let's name it current-vertex from the graph and 

2) If the current-vertex is not in hash set
- add the current vertex to hash set
- get all the children of current-vertex and **recursively** call the step 2 for each child vertex
- add the current-vertex to stack

3) reverse the stack, and we get the topological order

#Code
```python
    def topological_sort(self, graph, seen, stk, current_vertex):
        # 2) if current_vertex not in hash set
        if current_vertex not in seen:
            seen.add(current_vertex)
            current_vertex_children = graph[current_vertex]
            for child in current_vertex_children:
                self.topological_sort(graph, seen, stk, child)
            stk.append(current_vertex)
            
    
    # *** Main function ***
    def topoSort(self, v, graph):
        # v = no of vertices in the graph
        # graph is represented using an adjacency list
        stk = []
        seen = set()
        # 1) pick a vertex
        for vertex in range(v):
            self.topological_sort(graph, seen, stk, vertex)
        # 3) reverse the stk
        stk.reverse()
        return stk
```

#Problems which can be solved using topological sort

Implementing topological sort for a DAG: [geeks-for-geeks-problem-link](https://practice.geeksforgeeks.org/problems/topological-sort/1/)

Order of courses in topological order: [leetcode-problem-link](https://leetcode.com/problems/course-schedule-ii/)

Check if all the courses can be completed: [leetcode-problem-link](https://leetcode.com/problems/course-schedule/)