teleren/devto huggingface dataset:
Calculating Transparency of an HTML5 Canvas
Tags: html, javascript, webdev
Published: 2023-03-17 00:57:32

Alright let's get back to basics here. HTML5 Canvas is a very versatile element capable of both 2d and 3d graphics. It is used in majority of the eye-candy websites featured on websites like [awwwards.com](https://www.awwwards.com/) and [siteinspire.com](https://www.siteinspire.com/).

While building one of my older [portfolio websites](https://portfolio-v4-abjt14.vercel.app/), I built a drawable background that auto-fills once half the Canvas has been drawn on. In order to make this work, I had to calculate the transparency percentage of the Canvas.

_You wouldn't believe how simple this can be._

For this article, we'll need to:

1. Create A Canvas
2. Draw A Shape
3. Calculate Transparency

Alright onto **Step 1**. Let's create a basic HTML Canvas.

```html
<canvas height="500" width="500"/>
```

We're already at **Step 2?**

```javascript
// get the context
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");

// add a shape
context.fillStyle = "#000000";
context.fillRect(0, 0, canvas.height/2, canvas.width/2);
```


**Step 3.** Finally we get to write some logic.

```javascript
// retrieving image data
const imageData = context.getImageData(0, 0, canvas.width, canvas.height).data;
```
Let's check the `imageData` values.
```javascript
console.log('imageData', imageData);

// we get the following array of 1000000 values
// [0, 0, 0, 255, 0, 0, 0, 255............, 1, 1, 1, 255, 1, 1, 1, 255]
```
As you might have guessed, these are `rgba` values of each pixel in the canvas, defining the Red, Green, Blue, and Alpha (transparency) values respectively. Each value ranges from `0` to `255`.

What we have to focus on here, is the Alpha values. So let's isolate them.
```javascript
// removing every non-4th value (rgb values)
let alphaValues = imageData.filter((value, index) => index % 4 === (4 - 1));
```

The method to calculate transparency is pretty simple, we just need the transparent pixels and the total pixel count.
```javascript
// reworking the filter to remove non-zero alpha values as well
let alphaValues = imageData.filter((value, index) => index % 4 === (4 - 1) && value === 0);

// get the maximum pixel count
const maxPixels = canvas.width * canvas.height;
```

Now for the finale, let's calculate the transparency ratio and convert it to a percentage.
```javascript
// tada!
const percentage = (alphaValues.length / maxPixels) * 100;

// a good old fashioned console.log()
console.log(`${percentage}%`);
// "75%"
```

That's all folks, told ya it was simple.
"How is the review coming along"...would this be useful?
Tags: codereviewvillains, programming, productivity, codereview
Published: 2023-03-17 00:30:56

As a dev, I write a bunch of code.  I just want to get a PR merged.  I am often frustrated to know if a dev is even looking at my PR, how close they are to wrapping it up, etc.

Would knowing this make you happier or more frustrated?
👍 = yes
👎 = no

React to get your voice heard!!
Determine this in JS
Tags: webdev, javascript, beginners, programming
Published: 2023-03-17 00:30:00

`this` is determined by how a function is called, not how it is defined.

## Things to find `this`:

- When a function is called as a method of an object, `this` refers to the object itself.
- When a function is called without a context, `this` refers to the global object in non-strict mode, or to `undefined` in strict mode.
- When a function is called with the new keyword, `this` refers to a newly created object that inherits from the function's prototype.
- When a function is called with call or apply, `this` is explicitly set to the first argument passed to call or apply.
- Arrow functions do not have their own `this` value, but instead inherit `this` from the surrounding scope.
- The bind method can be used to create a new function that has a specific `this` value.

## Example

#### As a method of an object:
```javascript
const person = {
  name: 'John',
  sayHello() {
    console.log(`Hello, my name is ${this.name}!`);
  }
};

person.sayHello(); // logs "Hello, my name is John!"
```
#### In a regular function:
```javascript
function sayHello() {
  console.log(`Hello, my name is ${this.name}!`);
}

sayHello(); // logs "Hello, my name is undefined!" in non-strict mode, or throws an error in strict mode
```
#### With the new keyword:
```javascript
function Person(name) {
  this.name = name;
}

const john = new Person('John');
console.log(john.name); // logs "John"
```
#### With `call` or `apply`:
```javascript
function sayHello() {
  console.log(`Hello, my name is ${this.name}!`);
}

const person = {
  name: 'John'
};

sayHello.call(person); // logs "Hello, my name is John!"
```
#### In an arrow function:
```javascript
const person = {
  name: 'John',
  greet: () => {
    console.log(`Hello, my name is ${this.name}!`);
  }
};

person.greet(); // logs "Hello, my name is undefined!" since arrow functions do not have their own `this` value
```
#### With `bind`:
```javascript
const person = {
  name: 'John'
};

function sayHello() {
  console.log(`Hello, my name is ${this.name}!`);
}

const sayHelloToPerson = sayHello.bind(person);
sayHelloToPerson(); // logs "Hello, my name is John!"

````
Cloud Migration Strategies: The 6 "R". Part 1/6
Tags: cloudskills, aws, cloudmigration, devops
Published: 2023-03-17 00:28:08

 With the boom on the field of cloud computing, there is more and more need for engineers capable of helping companies make their transition to the cloud smooth. 
Being able to assist an organization  to make safely make their transition to the cloud is a valuable skillset  to have. In this post, I will  go over the 6R of Cloud Migration Strategy.
   
  It is important to mention that  not all applications are optimized to run on the cloud. After careful  evaluation, if you think that your application is still better of on the cloud, take a time  to understand which cloud  Migration Strategy fits your case best.      
 
   In most block posts, you will see the 6R's staring with "Refactor" and end up with "Retire" However, in this post I deliberately decided to go from the migration strategy that requires the  **Least** effort to **Most** effort.

1. **Retire**
2. **Retain**
3. **Repurchase**
4. **Rehost**
5. **Replaftorm**
6. **Refactor**   

 **Retire**:  I will coin this as _"Drop and Go"_ In this option application that have reached end of life (EOL) are simply retired  or decommissioned.


 **Retain**: Also known as _"Re-visit"_
In this case some  applications  are just excluded from the migration strategy to be revisited on a later time. The reason for that may be things like latency, compliance/regulatory constrains for simply costs. In this case you will be running a hybrid environment.
 

 **Rehost** : Mainly referred as _Lift and Shift _. 
 This is known as one of the most basic way of cloud migration strategy . It consists of moving  your application or data without having to go through a code level changes. It is the preferred method for most organizations as it carries least amount of risks or complication. 
     

 **Repurchase**:   This is also known as _"Drop and Shop"_ 
In this case, on prem or legacy applications are just dropped in favor of cloud-native vendor software packages It is like moving from proprietary application to SAAS
        
      
 **Replaftorm**:  This also know as _Lift Tinker and Shift_ Method 
 In this method, candidate applications are packaged , tweaked a little bit and moved to the cloud via tools like AWS Data Migration Service 

             
 **Refactor** :   I will coin this as " Go from scratch "
In this case,  an application is rewritten re-architectured from scratch to make cloud native. It is a an expensive and time consuming method  that require a team of qualify cloud engineers. Most companies goes that route if their existing applications are not cloud compatible.

In the following series I will have a full blog post of each of the 6R mentioned here. 

Let me know if you find this post useful.

 Lets link up on twitter : [@asksouley](https://twitter.com/asksouley) 
 or visit my site. www.asksouley.com 

Cheers!
How to Retrieve Data from Contentful CMS in a React App
Tags: webdev, javascript, contentful, react
Published: 2023-03-17 00:07:30

Contentful is content infrastructure. it lets you you create, manage and distribute content to any platform. In this article, I'll walk through the steps involved in fetching data from Contentful using the Contentful Delivery API in a React app.

The first step is to set up a Contentful account and create your content model and its fields. Afterward, you can proceed to create your content

secondly, Install the contentful npm package in your React app. This package provides a JavaScript client for the Contentful Delivery API.

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


The next step is to import createClient from the Contentful package that we just installed, and then create a new instance of the Contentful client in your React application.


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

Next thing is to obtain your space ID and access token by logging into the Contentful web app and navigating to the "Settings" tab for your space. You will find your space ID and access token under the "API keys" section. then copy and paste them in the above snippet or your contentful instance.

The final step is to use the client to retrieve the data you need. You can utilize the client to fetch data from any Contentful content type, including entries, assets, and content types themselves.


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

In the code above, we're creating a new instance of the contentful client and using it to fetch entries from our Contentful space. Once we receive the response, we're updating the component's state with the retrieved data.

We're then rendering a simple list of the retrieved items' titles.

And that's it! With just a few lines of code, we're able to fetch data from Contentful using the Contentful Delivery API in a React app.
How did making coffee help me find a bug in my code?
Published: 2023-03-17 00:27:21

---
title: How did making coffee help me find a bug in my code?
published: true
date: 2023-03-17 00:00:00 UTC
tags: 
canonical_url: https://karas.codes/posts/how-did-making-making-coffee-help-me-find-a-bug-in-my-code/
---

I know what you're thinking. Did that really happened? My answer is yes, it happened.

# Context

It happened a couple of months after I started working in a team that developed browser extension. I got some bug to investigate related with one key feature of its extension.

When I found a code that was the potential culprit of a bug, I just set breakpoints in the browser and started trying to incrementally move through the code to examine it.

But I had no luck. I spent a big chunk of my time trying to trigger it in different ways… but still the corner case I wanted to find was hidden.

# Coffee

After a couple of minutes I needed a quick break to make a cup of coffee and to think about other approaches that I could follow to find the culprit. But when I got back to my browser and IDE I spotted that the breakpoint was active! Something had triggered the correct code.

# Solution

It turned out that feature I was testing, was using `idle` browser API. As a name says that API was allowing the user to track a device idle state. Inside a code I found an event handler responsible for doing the rest of the work. Solving a bug was super easy in the end.

That history is still funny after couple years… I still can’t believe that I solved a bug by preparing a coffee :)
Então, você quer aprender Rust?
Published: 2023-03-16 22:55:51

Bom momento, pessoal. Comecei a aprender a linguagem de programação Rust e a partir deste post começarei uma nova série de artigos para compartilhar o que eu venho aprendendo até o momento.

Saindo um pouco da temática de acessibilidade na web na qual eu venho escrevendo, irei listar alguns conteúdos que você pode acessar para começar a aprender essa linguagem que é bem divertida.

Alguns conteúdos estão em português, porém outros estão em inglês. Vamos lá!

## Websites (Livro)

- [A linguagem de programação Rust](https://rust-br.github.io/rust-book-pt-br/title-page.html) - **pt-br**

- [Comprehensive Rust] (https://google.github.io/comprehensive-rust/pt-BR/index.html) - **pt-br**

- [Dar seus primeiros passos com o Rust] (https://learn.microsoft.com/pt-br/training/paths/rust-first-steps/) - **pt-br**

- [Rust by Example](https://doc.rust-lang.org/rust-by-example/) - **en**

- [A half-hour to learn Rust](https://fasterthanli.me/articles/a-half-hour-to-learn-rust) - **en**

- [Effective Rust](https://www.lurklurk.org/effective-rust/types.html) - **en**

## Youtube

- [Aprenda Rust - Bruno Rocha](https://www.youtube.com/playlist?list=PLjSf4DcGBdiGCNOrCoFgtj0KrUq1MRUME)

- [Rust - Série "Aprenda com quem não sabe" - Fernando Daciuk](https://www.youtube.com/watch?v=mWh49ZpmQwk&list=PLr4c053wuXU-igL9KSptwKK5XdyGX13FB)

- [Let's Get Rusty](https://www.youtube.com/channel/UCSp-OaMpsO8K0KkOqyBl7_w)

## Livros

- [Rust
Concorrência e alta performance com segurança](https://www.casadocodigo.com.br/products/livro-rust)

- [Programação Funcional e Concorrente em Rust](https://www.casadocodigo.com.br/products/livro-rust-funcional-concorrente)


## Conclusão
Bom pessoal, esse foi meu primeiro post falando sobre Rust, em breve irei trazer mais conteúdos sobre essa linguagem bem divertida. Se você achar que esta faltando algum material sobre rust nesse artigo, escreve ele nos comentários, por favor. Qualquer coisa estou à disposição para ajudar em dúvidas sobre acessibilidade, rust, JavaScript....e o que não souber, a gente aprende juntos. Até Mais!!
Next.js 13 Image Cheatsheet
Tags: nextjs, react, image
Published: 2023-03-16 23:33:08

This cheat sheet is meant to provide an overview of the important features and usage of the Next.js Image Component, which helps to optimize and enhance your images.

## Basic Usage

```js
import Image from 'next/image';

export default function Page() {
  return (
    <Image
      src="/profile.png"
      width={500}
      height={500}
      alt="Picture of the author"
    />
  );
}
```

## Required Props

- `src`: The image source, can be an internal path or an external URL.
- `width`: The rendered width in pixels.
- `height`: The rendered height in pixels.
- `alt`: Description of the image for screen readers and search engines.

## Optional Props

- `loader`: A custom function used to resolve image URLs.
- `fill`: Boolean that causes the image to fill the parent element.
- `sizes`: A string that provides information about how wide the image will be at different breakpoints.
- `quality`: The quality of the optimized image, an integer between 1 and 100.
- `priority`: When true, the image will be considered high priority and preload.
- `placeholder`: A placeholder to use while the image is loading.
- `style`: Allows passing CSS styles to the underlying image element.
- `onLoadingComplete`: A callback function that is invoked once the image is completely loaded and the placeholder has been removed.
- `onLoad`: A callback function that is invoked when the image is loaded.
- `onError`: A callback function that is invoked if the image fails to load.
- `loading`: The loading behavior of the image. Defaults to lazy.
- `blurDataURL`: A Data URL to be used as a placeholder image before the src image successfully loads.
- `unoptimized`: When true, the source image will be served as-is instead of changing quality, size, or format.

## Configuration Options

Configure the Image Component in `next.config.js`. The following options are available:

- `remotePatterns`: Configuration required for using external images.
- `domains`: A list of allowed hostnames for external images.

_Recommended way_
```
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.example.com',
      },
    ],
  },
}
```

```
module.exports = {
  images: {
    domains: ['assets.acme.com'],
  },
}
```


Example usages of the Image component can be found at this repo: 

[Image Examples](https://github.com/vercel/next.js/tree/canary/examples/image-component/pages)
How Our Mobile App Development Educational Content on YouTube Has Evolved with Ionic Framework
Tags: ionic, mobile, startup
Published: 2023-03-16 23:05:05

> A #ThrowbackThursday inspired blog post, not the normal content that I post but more of an explanation of what I do and why I do it. 

At my company [Clearly Innovative Inc](https://www.clearlyinnovative.com/), we've been creating educational content on YouTube since 2012, related to our experiences while creating solutions for clients. Our goal has always been to share our knowledge and expertise with others who are interested in learning about the latest trends and technologies in our industry.

While our early videos were well-received, we soon realized that we needed to up our game to stand out in the crowded market. That's when we discovered the Ionic framework.

For those who are not familiar, the [Ionic Framework](https://ionicframework.com/) is a powerful tool for building mobile apps using web technologies like HTML, CSS, and JavaScript. We were impressed by its versatility and ease of use, and we knew that we had to incorporate it into our educational content.

Our first video on the [Ionic Framework](https://ionicframework.com/) was posted in 2015, and it was an instant hit. We received comments and messages from people who were excited to learn more about this powerful tool, and we knew that we were onto something.

{% youtube iM_KjhY4lL0 %}
**First Ionic Framework Video**

Since then, we have been incorporating the [Ionic Framework](https://ionicframework.com/) in the majority of our educational content on YouTube. We believe that the framework's ability to work with ReactJS, AngularJS, or VueJS adds value regardless of what JavaScript programming library you use. Whether we're creating tutorials, how-to guides, or deep dives into specific features, we always make sure to incorporate the latest and greatest tools and technologies.

We believe that the [Ionic Framework](https://ionicframework.com/) is essential for our educational content. It is incredibly versatile, and both beginners and experienced developers can use it to create amazing mobile apps that work seamlessly across all devices.

By showcasing our expertise in this powerful tool, we demonstrate our value to potential customers who are looking for a partner to help them build the next big thing. We are proud to have been early adopters of this powerful tool, and we look forward to sharing our knowledge and expertise with the world for years to come.

If you are looking to build an amazing cross-platform mobile solution, please feel free to [Clearly Innovative Inc](https://www.clearlyinnovative.com/). Leverage our years of experience in the technology space and our extensive knowledge of the Ionic framework to create something truly unique and innovative.

[Visit Our Website](https://www.clearlyinnovative.com/) | [Visit Our YouTube Channel](https://www.youtube.com/channel/UCMCcqbJpyL3LAv3PJeYz2bg)
Node-based Data Structure
Tags: dsa, algorithms, python
Published: 2023-03-16 22:58:39

while searching for solutions on Google, I came across a new term, _"node-based data structure"_ ,
this term was new to me and I decided to dig in a little bit deeper.
These are some of the concepts that I discovered while researching node-based data structures.

**Node-based data structures** are data structures that organizes and stores data as interconnected nodes. Each node contains data and one or more pointers that point to other nodes. 

This structure allows for efficient traversal and manipulation of the data

**what is a node ?**
I explain this using an analogy;
think of how the TV show **The Amazing Show** worked, contestants reached a given destination and got instructions on how to reach the next destination. Now replace the destination as the data in a node and the instructions as the pointer to the next node 

Simply node-base data structures are a collection of linked nodes that point to each other:

the two main node-base data structures are:
**Linked List:** its a data structure that can have a node that has a single pointer pointing to a next node _**singular linked list**_ or two pointers, one pointing the previous and one pointing to the next _**doubly linked list**_

**Tree:** for trees you can have a multiple pointers pointing to the next nodes. Trees don't have pointers for previous nodes, this create a parent-child relationship between the nodes

**Implementation of A Tree**
we can represent a math equation into a tree
Using BODMAS we can create  tree for this equation

3 * (y + x) as     

         *
        / \
       /   \
      3  (y + x)

and  3 * y + X as

         +
        / \
       /   \
    (3 * y)  x

Below is the code representation of the Tree
```

# represent 3 * (y + x) and  3 * y + X as trees 

class exp():
    pass

class Times(exp):
    def __init__(self,l,r):
        self.r = r
        self.l = l
    
    def __str__(self):
        return str(self.r) +" * "+ str(self.l)

    def eval(self,env):
        return self.r.eval(env) * self.l.eval(env)

class Plus(exp):
    def __init__(self,l,r):
        self.r = r
        self.l = l

    def __str__(self,l,r):
        return str(self.r) + " + " + str(self.l) 
    
    def eval(self,env):
        return self.r.eval(env) + self.l.eval(env)

class Const(exp):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return str(self.val)

    def eval(self):
        return self.val

class Variable(exp):
    def __init__(self,name):
        self.name = name

    def eval(self,env):
        return env[self.name]



# 3 * (y + x)
e1 = Times(Const(3),Plus(Variable('y'),Variable('x')))

# 3 * y + x
e2 = Plus(Times(Const(3),(Variable('y'))),Variable('x'))

# to get the calculations

env = {"x":2,"y":4}

e1.eval(env)
e2.eval(env)
```