teleren/devto huggingface dataset:
Limpiar la pantalla en Rust
Tags: rust
Published: 2023-03-21 01:58:00

Publicado originalmente (2021-10-11) en mi [sitio web.](https://diniremix.web.app)

Muchas maneras, el mismo efecto?

Mientras desarrollamos una aplicación que utiliza la línea de comandos, una de las tareas más triviales y necesaria (en muchos casos) es limpiar la pantalla....

Rust provee un par de opciones para tal fin.


### Utilizando **std:**

```rust
use std::process;

fn clear_screen() {
    process::Command::new("clear").status().unwrap();    
}
```

funciona muy bien en sistemas Gnu/Linux y Mac OS.
> En sistemas Windows, basta con cambiar "clear" por "cls"


&nbsp;

### Usando códigos de escape ANSI.
Todos los códigos de escape comienzan por los caracteres **ESC** (carácter ASCII número 27 decimal, **1B** en hexadecimal) seguido del carácter **[**, tienen cero o más parámetros delimitados por **;**

ejemplo:

```rust
fn clear_screen() {
    print!("\x1B[2J");
}
```


&nbsp;

Una variante del anterior, que posiciona el cursor en la fila 0, columna 0.

```rust
fn clear_screen() {
    print!("\x1B[2J \x1B[0;0f");
}
```


&nbsp;
Otro ejemplo casteando el número 27 como **char**.


```rust
fn clear_screen() {
    print!("{}[2J", 27 as char);
}
```

&nbsp;
Donde:

- '**\x1B**' es el código de escape, que indica que lo que sigue es una secuencia de control.
- '**[**' indica el comienzo de una secuencia de control.
- '**2**' indica el tipo de secuencia de control. En este caso, '2' indica que la pantalla debe ser borrada.
- '**J**' indica cómo se borrará la pantalla. En este caso, 'J' indica que se borrará todo el contenido de la pantalla.

&nbsp;

## Referencias

- [Códigos de escape_ANSI](https://es.wikipedia.org/wiki/Código_escape_ANSI)
- [termion](https://github.com/redox-os/termion/blob/master/src/clear.rs)
- [clearscreen](https://github.com/watchexec/clearscreen)
- [stackoverflow](https://stackoverflow.com/questions/4062045/clearing-terminal-in-linux-with-c-code/4062051#4062051)
- [rosettacode](http://rosettacode.org/wiki/Terminal_control/Clear_the_screen#Rust)
Create API Gateway with Step Function Integration
Tags: api, stepfunction, terraform
Published: 2023-03-21 01:56:31

Often we need to integrate Lambda with API Gateway which is a very popular pattern, however as we think about asynchronous processing we need to integrate Step Functions (which will have a chain of actions) with API gateway. 

Below is a simple terraform example of how to create an API Gateway with Step Function Integration
```
provider "aws" {
  region = "us-east-1"
}

resource "aws_api_gateway_rest_api" "example_api" {
  name = "example_api"
}

resource "aws_api_gateway_resource" "example_resource" {
  rest_api_id = aws_api_gateway_rest_api.example_api.id
  parent_id   = aws_api_gateway_rest_api.example_api.root_resource_id
  path_part   = "example"
}

resource "aws_api_gateway_method" "example_method" {
  rest_api_id   = aws_api_gateway_rest_api.example_api.id
  resource_id   = aws_api_gateway_resource.example_resource.id
  http_method   = "POST"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "example_integration_step_function" {
  rest_api_id = aws_api_gateway_rest_api.example_api.id
  resource_id = aws_api_gateway_resource.example_resource.id
  http_method = aws_api_gateway_method.example_method.http_method
  integration_http_method = "POST"
  type = "AWS"
  
  uri = aws_sfn_state_machine.example_step_function.execution_arn
}

resource "aws_sfn_state_machine" "example_step_function" {
  name = "example_step_function"
  definition = <<EOF
{
  "Comment": "A simple AWS Step Functions state machine",
  "StartAt": "FirstState",
  "States": {
    "FirstState": {
      "Type": "Pass",
      "Result": "Hello, world!",
      "End": true
    }
  }
}
EOF
}

resource "aws_api_gateway_deployment" "example_deployment" {
  depends_on = [
    aws_api_gateway_integration.example_integration_step_function
  ]
  
  rest_api_id = aws_api_gateway_rest_api.example_api.id
}

```
```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "states:StartExecution"
            ],
            "Resource": [
                "arn:aws:states:<REGION>:<ACCOUNT_ID>:stateMachine:<STATE_MACHINE_NAME>"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:<REGION>:<ACCOUNT_ID>:log-group:/aws/lambda/<LAMBDA_FUNCTION_NAME>:*"
            ]
        }
    ]
}
```
Context in PRs is not being solved
Tags: programming, codereviewvillains, productivity, devtools
Published: 2023-03-21 01:39:10

Bottlenecks in PRs are everywhere - but the core issue is lacking context.  Devs & managers don't know how close a PR is to shipping.  Reviewers don't know if major changes are coming or how the author got to the final code. They also lack a product that shows them the key data to review w/o jumping around.  No tools fix this, and the latest start-ups aren't working on the core problem.
Animation -11 : Loading Bars CSS Animation
Tags: css, animation, webdev, design
Published: 2023-03-21 01:07:00

Are you looking for animations to enhance your website? We've got you covered with our wide selection of creative and engaging #animations. Say goodbye to endless searching and hello to seamless integration on your website!

#### We're excited to introduce our latest YouTube series, which features diverse creative and inspiring website animations.

---

In our short videos, you'll find a variety of #animations that can be easily implemented on your website to enhance user experience.


---

### Loading Bars CSS Animation 

---

{% youtube z-OFEBUMjII %}

 ---
### [Source code](https://democoding.netlify.app/loaders/loading-bars-css-animation)


---
## For more information

1. Check my GitHub profile
[https://github.com/amitSharma7741](https://github.com/amitSharma7741)

2. Check out my Fiver profile if you need any freelancing work
[https://www.fiverr.com/amit_sharma77](https://www.fiverr.com/amit_sharma77)

3. Check out my Instagram
[https://www.instagram.com/fromgoodthings/](https://www.instagram.com/fromgoodthings/)

4. Linktree
[https://linktr.ee/jonSnow77](https://linktr.ee/jonSnow77)

5. Check my project

- EVSTART: Electric Vehicle is the Future
[https://evstart.netlify.app/](https://evstart.netlify.app/)
-  News Website in react
 [https://newsmon.netlify.app/](https://newsmon.netlify.app/)
-  Hindi jokes API
 [https://hindi-jokes-api.onrender.com/](https://hindi-jokes-api.onrender.com/)
- Sudoku Game And API
[https://sudoku-game-and-api.netlify.app/](https://sudoku-game-and-api.netlify.app/)

---
---
DockerFile para aplicaciones en Rust
Tags: rust, archive
Published: 2023-03-21 00:08:32

publicado originalmente (2018-05-01) en mi [sitio web](https://diniremix.web.app)


Creando una imagen de [Docker](https://www.docker.com) para una aplicación en Rust.

Este archivo, se extrajo del repositorio [rocket-rust](https://github.com/HomeInside/rocket-rust) facilitando la creación de una imagen de Docker para aplicaciones en [Rust](rust-lang.org), usando [Rocket](https://rocket.rs/v0.4/guide/) como Web framework.

```docker
FROM ubuntu:16.04

MAINTAINER Awesome User <awesome-user@example.como>

RUN apt-get update \
    && apt-get install -y curl nano file net-tools build-essential

RUN curl https://sh.rustup.rs -s > /home/install.sh && \
    chmod +x /home/install.sh && \
    sh /home/install.sh -y --verbose --default-toolchain nightly

ENV PATH "/root/.cargo/bin:$PATH"

ENV SOURCES=/sources

RUN mkdir -p $SOURCES

ADD ./ $SOURCES

WORKDIR $SOURCES

RUN rustup update

RUN cargo update

RUN cargo build --release

EXPOSE 80
EXPOSE 8080

# CMD ROCKET_ENV=development ./target/release/rocket-rust

CMD ROCKET_ENV=production ./target/release/rocket-rust
```

### referencias

- [documentación oficial de Rust](https://doc.rust-lang.org/stable/book/)
- [Rocket](https://rocket.rs)
- [HomeInside/rocket-rust](https://github.com/HomeInside/rocket-rust)
🐯 Opening New Tabs on Mobile Devices with JavaScript, Safari-Friendly
Tags: devrel
Published: 2023-04-22 19:28:33

---
title: 🐯 Opening New Tabs on Mobile Devices with JavaScript, Safari-Friendly
published: true
date: 2023-03-21 00:00:00 UTC
tags: DeveloperExperience
canonical_url: https://bstefanski.com/javascript-open-new-tab-mobile-safari-fix
---

I recently encountered a situation where I needed to open a new tab on mobile devices using JavaScript. Initially, I used the following code:

```

window.open(url, '\_blank');

```

It worked well, but when I tested it on Safari, I quickly discovered that Safari's security policies prevent opening a new tab within an asynchronous function, such as inside a promise. To address this issue, I had to find a workaround.

The most effective workaround I found involved the following steps:

```

var windowReference = window.open();

myService.getUrl().then(function(url) {

 windowReference.location = url;

});

```

The key here is to declare a variable with a reference to the `window.open()` object outside of the asynchronous function. Then, reassign the location to the desired URL where you previously called the window.open function.
🛠️ Quickly Launch VSCode from Terminal as Admin (2023)
Tags: devrel
Published: 2023-04-22 19:28:37

---
title: 🛠️ Quickly Launch VSCode from Terminal as Admin (2023)
published: true
date: 2023-03-21 00:00:00 UTC
tags: DeveloperExperience
canonical_url: https://bstefanski.com/running-vscode-as-an-administrator
---

I wanted to utilize the code . command in the terminal to directly open VSCode in my desired directory. To achieve this, I navigated to the VSCode Command Palette and chose `>Shell Command: Install 'code' command in PATH`. However, I encountered an error message stating "permissions denied" and that administrator access was required for this action.

After some searching, I discovered several solutions to run VSCode as an administrator. The following command was the only one that worked for me:

```

$ sudo /Applications/Visual Studio Code.app/Contents/MacOS/Electron; exit

```

Upon executing this command, VSCode should open, allowing you to select the `>Shell Command: Install 'code' command in PATH` option.
Instalar Kazam en Korora 24 (2016)
Tags: kazam, gnu, linux, archive
Published: 2023-03-20 23:59:34

publicado originalmente (2016-09-07) en mi [sitio web](https://diniremix.web.app)


[Kazam](https://launchpad.net/kazam) proporciona una interfaz bien diseñada y muy fácil de usar para grabar y hacer capturas de pantalla.

![kazam1](https://c1.staticflickr.com/9/8372/28908063724_160041bce3_o.png)

Se puede grabar vídeo y audio del escritorio en múltiples canales simultáneamente. Cuenta con un control de los niveles de audio y permite también seleccionar una región de la pantalla para ser capturada.

El Soporte para códecs H264 y VP8 está integrado por defecto.

Aunque existen numerosos programas para realizar esta labor en Gnu/Linux, Kazam brilla por su simplicidad y potencia a la hora de hacer un screencast de tu escritorio.


### Instalando Kazam en Korora 24:
Agregamos el repositorio de [home:Kenzy:packages/kazam](http://software.opensuse.org/download.html?project=home%3AKenzy%3Apackages&package=kazam) para Fedora 24.

```bash
dnf config-manager --add-repo http://download.opensuse.org/repositories/home:Kenzy:packages/Fedora_24/home:Kenzy:packages.repo
```

Realizamos la instalación:

```bash
dnf install kazam
```

A la hora de escribir estas líneas, Kazam se encuentra en su [versión 1.4.5](https://launchpad.net/~kazam-team/+archive/ubuntu/stable-series)

listo!.

![kazam2](https://c2.staticflickr.com/9/8101/29533150345_e975c9bdf2_z.jpg)

## **Usando Kazam en Korora 24**

{% embed https://www.youtube.com/watch?v=3DRzO9zz5xE %}

### Problemas comunes

En el caso de Korora 24, Kazam puede no funcionar bien y lanzar un error al iniciar, como se aprecia en la siguiente imagen.

![kazam3](https://c5.staticflickr.com/9/8692/29499414116_68767cc930_z.jpg)

Esto es debido posiblemente a un cambio en la versión de python usada (**3.5.1** para este caso), para solucionar esto, basta con editar los archivos: 

- **/usr/bin/kazam** y seguidamente
- **/usr/lib/python3.5/site-packages/kazam/backend/config.py**

Con tu editor favorito editamos primeramente, el archivo **/usr/bin/kazam** y agregar las siguientes líneas antes de:

```python
...
from gi.repository import Gtk
...
```


Quedando de la siguiente manera:

```python
...
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
...
```

Guardamos los cambios y a continuación editamos el archivo **/usr/lib/python3.5/site-packages/kazam/backend/config.py** 

Ubicamos el metodo get y lo reescribiremos.

**Antes:**
```python
def get(self, section, key):
    try:
        return ConfigParser.get(self, section, key)
```

**Después:**
```python
def get(self, section, key, raw=True, fallback='rest'):
    try:
        return super(KazamConfig,self).get(section, key, raw=raw, fallback=fallback)
```

Estos cambios funcionan bien en Korora 24.

El fallo expuesto aquí, fué [reportado y solucionado](https://bugs.launchpad.net/ubuntu/+source/kazam/+bug/1500083) en la sección bugs del proyecto, estamos atentos a una actualización proximamente.
Azure Private Endpoint
Published: 2023-03-20 23:52:03

## Introduction
Azure Private Endpoint is a feature that allows you to access your Azure services privately from your virtual network (VNet). It provides secure and private connectivity to Azure services over a private endpoint in your VNet, removing the need for a public IP address or internet connectivity.

## Why do you need Azure Private Endpoint?
As a user, you might need Azure Private Endpoint for various reasons. For example, you might have sensitive data that you don’t want to expose to the internet or don’t want to use public IP addresses. Azure Private Endpoint provides a secure way to connect to your Azure services from your virtual network, eliminating the need for public IP addresses or internet connectivity.

## What does it solve?
Azure Private Endpoint helps to solve the problem of exposing your services to the public internet, reducing your attack surface and improving your security posture. It enables you to create private connections to Azure services over a private IP address, removing the need for a public IP address or internet connectivity.

## Best Practices
Here are some best practices to keep in mind when working with Azure Private Endpoint:

- Use it with Virtual Network Service Endpoints: Virtual Network Service Endpoints provide secure and private connectivity between your virtual network and your Azure service, improving security and network performance.
- Ensure that your Azure services are in the same region as your virtual network: This helps to reduce latency and improve performance.
- Use Network Security Groups (NSGs) to restrict access to your private endpoints: NSGs provide a way to control network traffic by filtering it based on source and destination IP addresses, ports, and protocols.
- Monitor your private endpoints using Azure Monitor: Azure Monitor provides a way to monitor your private endpoints and receive alerts when they’re down or not functioning as expected.

## Conclusion
Azure Private Endpoint provides a secure and private way to connect to your Azure services over a private IP address. It eliminates the need for public IP addresses or internet connectivity, reducing your attack surface and improving your security posture. By following best practices such as using Virtual Network Service Endpoints and Network Security Groups, you can ensure that your private endpoints are secure and performant.
Teoria de Grafos em Everything Everywhere All at Once
Tags: programming, ai, algorithms, braziliandevs
Published: 2023-03-20 23:14:05

> Já vou deixar claro logo no inicio que o texto contém **SPOILERS** então se você não assistiu o filme aconselho assistir e depois voltar aqui. Depois não diga que eu não te avisei.


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

Depois de ver algumas noticias sobre o Oscar desse ano fiquei curiosa e acabei decidindo assistir _Everything Everywhere All at Once_. 

Para ter mais impacto resolvi assistir sem ler a sinopse então eu não tinha ideia sobre o que era o filme nem qual o gênero. Confesso que nos momentos iniciais achei parado, não estava curtindo muito, porém simplesmente do nada o filme da uma virada completa e você fica olhando a tela assim 😮

Uma coisa que me chamou atenção quando o Waymond estava explicando o conceito dos multiversos pra Evelyn foi que de maneira simplificada toda a narrativa é construída em cima de Teoria de Grafos.


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



Basicamente existem diferentes universos que são criados a partir de escolhas feitas, por exemplo ao decidir se deve ou não tomar café em uma cafeteria do shopping você acabou de criar dois universos distintos:

- Universo A: você **foi** na cafeteria
- Universos B: você **não foi** na cafeteria.

No filme a Evelyn utiliza saltos multiversais para acessar esses universos e obter habilidades que "seu eu" naquele universo possui (saber artes marciais, ser cantora, etc).

Para isso foi desenvolvido um algoritmo que calcula qual ação improvável deve ser feita para posicionar a Evelyn na borda de um universo vizinho e a partir dele ela será lançada para o universo desejado.


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


Ta, mas como isso tem haver com grafos?

Cada universo é um nodo e suas conexões são feitas através dessas situações bizarras realizadas ~~Waymond comer batom ou se cortar com papel~~. Para fazer o salto pro universo desejado é encontrada uma ação que faz uma conexão com um nodo vizinho dentro de um clusters de nodos que contenha o menor caminho (_Shortest path problem_) para o nodo desejado.  

 

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

Na hora que vi fiquei exatamente assim:


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

Quem já trabalhou ou conhece grafos deve ter reconhecido também! 

É intrigante ver como nos últimos anos Grafos tem sido cada vez mais usados, principalmente em aplicações de _Deep learning_. 

Não sei se o filme tinha como objetivo evidenciar isso  ~~provavelmente não~~, mas mesmo assim foi interessante ver o jeito que utilizaram e que, abstraindo o quesito ficção, trouxeram veracidade na utilização.

E vocês o que acharam do filme? 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqikzykq6zhlmqmy0ue2.gif)
World of Goo
Tags: javascript, gamedev
Published: 2023-03-20 23:06:34

[World of Goo](https://store.steampowered.com/app/22000/World_of_Goo) es un videojuego de lógica, con un fuerte énfasis en la física, Producido por [2D Boy](https://2dboy.com), una desarrolladora de videojuegos independiente compuesta por Kyle Gabler y Ron Carmel, ambos exempleados de Electronic Arts.
<!-- more -->


No hablaremos del juego en sí, sino de unos curiosos y fascinantes mensajes que aparecen cuando el juego va iniciando, hemos hecho una recopilacion de estos (no sé si están todos) e hicimos una función en **Javascript** que genera mensajes de Goo aleatorios. :smile:


```js
var messages = [
  'Excediendo la capacidad de la CPU',
  'Construyendo capacidad emocional',
  'Comprobando ozono',
  'Cargando',
  'Agitando',
  'Extrayendo',
  'Girando con violencia alrededor del eje de las Y',
  'Debatiendo el arte de los videojuegos',
  'Despreocupandose de los problemas de pareja',
  'Metiendo espectativas en sacos de arena',
  'Licuando Bytes',
  'Yodizando',
  'Probando la perfección',
  'Revolviendo la independencia',
  'Filtrando la moral',
  'Diagramando meticulosamente la diversión',
  'Homogeneizando Goo',
  'Aplacando los editores',
  'Destilando belleza',
  'Autofirmando',
  'Cambiando tiempo por espacio',
  'Fabricando responsabilidad social',
  'Reimaginando con exactitud',
  'Doblando la cuchara',
  'Construyendo una narración no lineal',
  'Aplicando innovación'
];

var tot = messages.length;

function getGoo (max=26) {
  for (i = 0; i < max; i++) {
    var pos = Math.floor(Math.random() * tot);
    var message = messages[pos];
    console.info(message, '...OK');
  }
}

getGoo(7);
```

### referencias

- [Sitio oficial](https://2dboy.com)
- [Wikipedia](https://es.wikipedia.org/wiki/World_of_Goo)
- [Fandom](https://worldofgoo.fandom.com/wiki/World_of_Goo)
- [Steam](https://store.steampowered.com/app/22000/World_of_Goo)

publicado originalmente (2016-02-07) en mi [sitio web](https://diniremix.web.app)
Tealium iQ basics concepts pt 1
Tags: javascript, tealium, beginners
Published: 2023-03-20 22:55:03

:alien: **What is Taelium?**
Tealium provides to customers the tools more robust that supply management data, in addiction connect you and your customers in real time. Summarize, Tealium collect data from a variety of touchpoints your costumer make in your brand- including websites, mobile apps,etc - that are integrate into a customer data center.

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


:satellite: **Data Tracking in Tealium** 
Exists two types of data tracking:

- 
:inbox_tray: **Client-side tracking:** tracking resources t that includes tags manegement, Javascript code and pixels.

- 
:outbox_tray: **Server-side tracking:** data management  resources  with the use of cloun infrastructure with a set of libraries , SDKs, APIs and others.
 
In that post series I will only deal with **client-side data tracking**

---
:globe_with_meridians: **How the Tealium suply chain works** 


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

1. Firstly the data are colected through vendor endpoints - which in turn is a way to identify, verify, and build complete profiles for all devices on a network.  

2. This vendor endpoints will be standardized and can turn into variables, forming the Data Layer.  The Data Layer gathers all website data will feed your analytics and digital marketing initiatives. To create variables in data layer, it will ne necessary to make settings tha will be applied in the next posts. 
3. In the phase of transforming and enriching, it is possible to use any variable present in the data layer.It is in this phase. For data processing in this step , it is possible to use the Load Rules and Extensions , which will modify the data and information according to the supplier's needs. These concepts will also be explained later.
4. In the integration stage, Tealium has a variety of ways to integrate with vendors, including client-side tags , serve-side tags and API calls , SDK for mobile and etc. In the post series about Tealium, more focus will be placed on client-side tags. These tags will also be managed here, and by tag management is understood  as a system to manage the configuration , testing and release os third-party vendor tags for a digital property.
5. After all the data processing, definition of vaiables and configuration of tags (with application of load rules and extensions), the activation stage for triggering tha tags is entered, which are sent to their respective suppliers.