teleren/devto huggingface dataset:
Membuat Objek Bersarang Dengan Memanfaatkan Composite Class
Tags: javascript, beginners, programming
Published: 2022-05-02 22:36:32

Hai teman-teman 👋

Kali ini saya akan membagikan tentang cara membuat objek bersarang dengan memanfaatkan composite class. Sebagai contoh saya akan membuat class Category seperti berikut:

```javascript
class Category {
    constructor(name) {
        this.name = name;
    }
}
```

Pada contoh di atas, objek yang dihasilkan dari instansiasi class Category tidak mampu untuk menampung sub kategori. Oleh karena itu, kita perlu untuk membuat composite classnya yang diturunkan dari class Category seperti berikut:

```javascript
class CompositeCategory extends Category {
    constructor(name, categories) {
        super(name);
        this.categories = categories;
    }

    getCategories() {
        return this.categories;
    }
}
```

Pada class CompositeCategory menerima dua inputan. Yang pertama nama kategorinya dan yang kedua array untuk menampung sub kategorinya. Berikut contoh penggunaannya:

```javascript
const categories = [
    new Category('Buah dan Sayur'),
    new CompositeCategory('Fashion', [
        new Category('Fashion Pria'),
        new Category('Fashion Wanita')
    ]),
    new CompositeCategory('Elektronik', [
        new Category('Sound System'),
        new CompositeCategory('Handphone', [
            new Category('Android'),
            new Category('iOS')
        ])
    ])
];
```
Pada contoh di atas, saya membuat variabel categories yang menampung beberapa kategori. Setiap kategori di dalamnya ada yang memiliki sub kategori ada yang tidak. Kedalaman sub kategori juga berbeda-beda sesuai preferensi.

Demikian yang dapat saya bagikan, apabila ada yang perlu dikoreksi silahkan share di kolom komentar. 😁
What's the longest build time you've experienced?
Tags: discuss, productivity, devops
Published: 2022-05-02 22:30:33

The most successful engineering teams typically keep their workflow durations between five to ten minutes on average, according to CircleCI's [2022 State of Software Delivery](https://circleci.com/resources/2022-state-of-software-delivery/). The median is 3.7 minutes. 

Looking at our team's slowest GitHub Actions using our [GitHub App](https://bit.ly/software-github), our longest workflow is just under 13 minutes. This excludes local builds and workflows. 

![Software.com GitHub Actions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ucfmtp80xdophht5st6.png)

But it's not unusual to see build times measured in hours, depending on the stack you're using.

LinkedIn's engineering org previously wrote about the steps they took to decrease build times from [60 minutes to 15 minutes](https://engineering.linkedin.com/blog/2018/07/how-we-improved-build-time-by-400-percent) for their largest microservice, improving productivity and team happiness.

What's the longest build or workflow time you've ever encountered? What tools were you using / could you fix it?
SUPER KEYWORD IN SOLIDITY
Tags: smartcontract, dapp, web3, solidity
Published: 2022-05-02 22:02:45

Solidity, like other programming language, is a statically typed language for creating smart contracts with complex algorithmic programs. This higher language is afterwards compiled into opcodes that virtual machines understand. Despite the speciality of the language, it borrows ideas iimmensely from other existing programming languages. This article hopes to help you understand the **super** keyword in Solidity.

The Solidity language is designed with the attributes of inheritance and it supports polymorphism. While inheritance is simplying the sharing in the same functions as the inheritor contract, polymorphism is the ability to make internal or external calls to functions of the same name and the same type of parameters. Due to the possibilities of having a long hierarchy of inheritance, the super keyword was therefore introduced to enable easy accessibility.

The super keyword are mentioned often in contracts with a lot of inheritance possessing the some functions with the same parameter types. When this code is called, **super.funcName()**, it calls the last base contract before the contract that makes the call. 

For instance, there are three contracts: A, B, C. If C inherits B and B inherits A, and they all have the same functions. If the super and the method function in the contract C, the last implementation of the function in B is what will be called. If A is the parent root contract, it won't be possible to use because it has no inheritance.

Here are practical examples:
```
pragma solidity 0.8.7;

contract A {
   function doSomething() external returns(bool) {}
}

contract B is A {
   function doSomething() external override returns(bool) {
     //super.doSomething();
}
}

contract C is B {
   function doSomething() external override returns(bool) {
   super.doSomething();
}
}
```

The code block above indicates clearly what the super keyword do and how it is relevance in the tree of inheritance in solidity.
Releasing at warp speed with EaaS
Tags: productivity, devops, kubernetes, terraform
Published: 2022-05-02 21:51:59

[Join](https://hubs.ly/Q019l2Vr0) our webinar which will take place on Thursday, May 12, starting at 4PM CEST | 6AM PST.

## Overview

"**It worked in my local environment**". Sounds familiar? If rollbacks, refactoring and bottlenecks in your staging and pre-production are some of the reasons your release cycle gets blocked and you can't forecast your sprint properly - This session is for you!

[Join us](https://hubs.ly/Q019l2Vr0) for a lively discussion on Thursday May 12, 2022 at 4pm CEST / 6am PST including a hands-on demo of how Bunnyshell's EaaS “smooths” your release process with Roxana Ciobanu Bunnyshell Founder and CTO.


You'll learn:

- What are the main reasons for the slow release process and fire-drills pre-release?

- What is code drift and how to avoid it?

- What is this EaaS fuss all about? How does it fit your development pipeline?

- Bunnyshell demo including Terraform support

- How can your team start with EaaS

Register now: https://hubs.ly/Q019l2Vr0

## About Bunnyshell

[Bunnyshell](https://www.bunnyshell.com/) is a multi-cloud Environments-as-a-Service platform that creates, manages and maintains production replicas, no matter how complex the architecture and what services are used. It automatically spins up new environments with every pull request or as part of the software release cycle, for development, testing, demo or deployment purposes. Bunnyshell brings predictability into sprints, enables frequent releases and helps developers ship more code.
Ng-News: Episode 22/17
Tags: angular, javascript, webdev, programming
Published: 2022-05-02 21:48:48

This is a weekly posting, covering the latest updates from the Angular community.


{% embed https://youtu.be/AwH-Imv9x-c %}


## Cypress 9.6

Cypress, the most used E2E testing framework in Angular, released version 9.6. It comes with a significant improvement, if not even a game-changer.

Until now, if you had a test where you had to go to another domain, e.g. authentication, you had to find workarounds. And sometimes, this was reason enough not to use Cypress.

That's a thing of the past. From now on, you can switch domains within a test as often as you want.

{% embed https://youtu.be/Fohrq5GZSD8 %}

## Jest 28

Jest had a new major release with version 28. It contains a lot of breaking changes but also quite some new additions.

For example sharding: You can distribute your tests to multiple machines. CI instances are a good use case.

Jest added new features to `fakeTimers` as well. It allows you to control time and therefore also asynchronity.

Support for ECMAScript modules hasn't been so good. Unfortunately, there were no improvements in that area.

[Jest 28 Release Notes](https://jestjs.io/blog/2022/04/25/jest-28)

## Miscellaneous

### New Angular team member

Pawel Kozlowski, known for his Angular contributions, especially for Standalone Components, is now an official member of the Angular team.

{% embed https://twitter.com/pkozlowski_os/status/1519746420898676739 %}

### nx Conf Lite

We also had nx conf lite, a conference about the Angular CLI extension nx. The recording is available on YouTube. 

Speaking of nx, respectively mono repositories: Lerna, the tool for mono repositories in the JavaScript space, is more or less deprecated. So if you are using it, maybe nx might be a suitable replacement.

{% embed https://youtu.be/iIZOfV0GFmU %}

### Testing & Asynchronity

Stephen Cooper wrote an article on testing in Angular and focuses especially on how to deal with asynchronity.

{% embed https://dev.to/angular/understanding-async-tests-in-angular-f8n %}
Best Decision I Ever Made Since I Started Coding?
Tags: javascript, beginners, react, webdev
Published: 2022-05-02 21:41:43

So it's been 2 days since I posted this [Rookie Mistake?](https://dev.to/soclarence/rookie-mistake-24m9) and honestly, I am wondering why I didn't take this journey from the beginning when I started learning to code. So far, I have faced the "biggest challenges" in css and javascript only to find out that it wasn't that big of a challenge in the first place.

So far, I have learned about fluid typography, basically how to use clamp() in css for responsiveness, I don't fully understand it but I know how to use it (or I now know something like that exists). After trying to centre a div here and there, I no longer have to rack my head to know where to use flex.

My biggest challenge was with responsiveness. I wrote the codes on my 24" monitor and was viewing the live version on my 15" laptop, I had the thought to switch between monitors and I realised I had mobile covered, I had tablets covered and basically my laptop screen. What happens to the 24" monitors and above? at first I tried using media query to find a middle ground but when I zoom out to assume the screen of a wider display, everything got really messy really fast. As I have learned from a lot of developers around, I took a walk and decided to browse through google till I found the fluid layout and fixed layout solution. of course I went with the fixed layout. It supported what I wanted to achieve at the time and also it was easier.

Well, there you have it. The journey so far.

I need a way to connect this series of posts. Anyway, I will be sharing more on the product as I share my progress with you'll thanks for coming.

_Please drop your thoughts and advice, it's not been easy. I'd really appreciate that. Thanks_
Day 24: Hello Redux 2
Published: 2022-05-02 21:30:29

Hi!
Remember the `Hello redux 1` post at day 19? probably not, but on day 19 wanted to start learning about Redux because was needed in the React app that I'm working. I had to name it 1 because at that time I Redux was like gibberish to me so I knew that I will have to go back to it again and here we are `Hello Redux 2`
So I didn't want to work on my paper so I dodged it by coding and that's when I tried researching about Redux again and I stumbled to some really great resources but the one that changed my Redux understanding was this article/minibook titled [The world's easiest guide to beginning Redux](https://www.freecodecamp.org/news/understanding-redux-the-worlds-easiest-guide-to-beginning-redux-c695f45546f6/) and as the name implies I think is the easiest article I have read about a complex topic. I read the first second and third chapters of this minibook and I now have a basic understanding of Redux `reducers`, `payload`, `action`, `store`... I was also able to work with `yarn` which is a very good (a faster one) alternative to `npm`
Overall I think the day was a productive one even if I didn't do much until the evening
Tomorrow the last the of this long weekend I will try to continue about Redux, get ready for the upcoming week and work on my paper I have to now
I'm excited!!!
Signing off for now...
Como estructurar aplicaciones en Angular
Published: 2022-05-02 21:29:20

Cuando se trata de estructurar aplicaciones, podemos pensar que no es necesario tener un orden definido, pero a medida el desarrollo crece, el equipo cambia y nuevos requerimientos son añadidos, se hace mas necesario tener consistencia en nuestro trabajo para facilitar la integración de nuevos miembros, nuevos requerimientos y para la mantenibilidad del proyecto.

Angular tiene una estructura bien definida de como deberían ordenarse los archivos y carpetas y hoy me gustaría profundizar en ello.

## Patrón LIFT
LIFT es el patrón principal creado por el equipo de Angular para ayudarte a definir bien la estructura de tus proyectos, significa lo siguiente:

Locate = Localizar
Identify = Identificar
Flat = Plano
T-DRY = Intentar no repetirse.

Ahora, veamos mas a detalle lo que cada uno significa.

## Locate
Debemos hacer que el localizar código en nuestra aplicación sea algo fácil e intuitivo, que ya sea que tengamos mucho o poco tiempo en un proyecto siempre sepamos a donde ir para encontrar cada cosa. 

Para cumplir con este paso, podemos guardar archivos en sub carpetas con nombres descriptivos y que tengan relación, por ejemplo, una carpeta para componentes (components), una carpeta para directivas, servicios, interfaces y pipes. De esta manera, sabremos que cada modulo que trabajemos tendrá este grupo de carpetas y sabremos a donde dirigirnos.

## Identify
Para cumplir con este paso, lo que debemos hacer es nombrar nuestros archivos de manera que identificarlos sea fácil, es decir, si estamos creando un componente, podemos colocar el nombre y la terminación `.component.ext`, si estamos trabajando con servicios sería `.service.ts` y así sucesivamente.

Para este paso, lo que debemos evitar es que un archivo contenga más de un componente, así podremos saber que el nombre del archivo hace relación explícitamente a su contenido y no usar nombres más generales. Siempre debemos preferir nombres descriptivos (aunque largos) a tener nombres cortos pero confusos.

## Flat
La estructura de nuestras aplicaciones debe ser lo mas plana posible, a nadie le gusta navegar a cinco niveles de profundidad en carpetas para encontrar el componente que andamos buscando.

Una recomendación importante es que cuando una carpeta tenga más de diez archivos dentro de ella, deberíamos considerar crear sub-carpetas, porque si bien es cierto no queremos que se llene de anidaciones, tampoco es lo correcto dejar todo dentro de una sola carpeta.

## T-DRY
T-DRY significa `Try Don't Repeat Yourself` y lo que significa es que, en la medida de lo posible intentemos no repetirnos, pero si es inevitable, o si haremos sacrificios en nuestro código para no repetirnos, que elijamos legibilidad sobre el DRY.

Como ejemplo, debemos evitar nombrar con cosas obvias nuestros componentes, como agregar `login-view.component.html` cuando la extensión ya nos esta indicando que es una vista, o nombrar `sign-up-style.component.scss` cuando la extensión claramente nos dice que es un archivo de estilos.
VS Code Tip of the Week: TypeScript Error Translator Extension
Tags: vscode, typescript, vscodetips, vscodeextension
Published: 2022-05-02 20:48:48

This week's VS Code Tip of the Week is a newly released extension, [TypeScript Error Translator](https://marketplace.visualstudio.com/items?itemName=mattpocock.ts-error-translator), that came out today!

This is super fresh/brand new, but it looks like it could be a super helpful extension for TypeScript devs. When you get a TypeScript error that you really don't understand, this might be the extension for you.

Thanks to Matt Pocock for creating the extension! If you're a fan of TypeScript and aren't already following him on Twitter, I suggest you do! 😎

{%embed https://twitter.com/mpocock1/status/1521145755007922176 %}

Thanks Matt and happy VS Coding!

P.S.: If you're looking for a community that’s all about VS Code, come on over and say hi at [vscodetips.com](https://vscodetips.com)!
Time Series Decomposition - Spotting Seasonality
Tags: programming, datascience, patterns
Published: 2022-05-02 20:39:55

The results fascinated me -- seasonal patterns when none were visible in the raw data.

I had looked at trends in this visualization of the median price of homes by zip code: ![median price of homes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kcqia3xoztukbsy36pxl.png)

And, mainly noticed the upward and downward trend in the median price.

However, when I performed and plotted a seasonal decomposition with statsmodels.tsa.seasonal:

```
# Import and apply seasonal_decompose()
from statsmodels.tsa.seasonal import seasonal_decompose
decomposition = seasonal_decompose(np.log(percent1))

# Gather the trend, seasonality, and residuals 
trend = decomposition.trend
seasonal = decomposition.seasonal
residual = decomposition.resid

# Plot gathered statistics
plt.figure(figsize=(12,8))
plt.subplot(411)
plt.plot(np.log(m1), label='Original', color='blue')
plt.legend(loc='best')
plt.subplot(412)
plt.plot(trend, label='Trend', color='blue')
plt.legend(loc='best')
plt.subplot(413)
plt.plot(seasonal,label='Seasonality', color='blue')
plt.legend(loc='best')
plt.subplot(414)
plt.plot(residual, label='Residuals', color='blue')
plt.legend(loc='best')
plt.tight_layout()
```
I noticed something surprising in the seasonality output - seasonality! 

![seasonality! :)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mm54anw4oo7hn948t0qt.png)

I enjoyed seeing the seasonal pattern.  I had always heard that prices were slightly higher in the spring/summer months, but it is confirming to see it in the decomposition.

I am now wondering about the magnitude of the trend.  I know the magnitude can't be too large, but I'm not sure how large.  

I am curious about how I would figure this out.

So far I have tried reversing the log transformation that was part of the process of decomposing the original data, but then I am left with a result of 1, as the magnitude of the seasonal trend oscillates between -0.001 and 0.0005.  I'm guessing the seasonal difference is greater than $1 in the real estate market with median prices varying in the data for this zip code between $120,000 and $700,000.

If anyone reads this and has answers, please message me or comment - Jim.Petoskey.146@gmail.com.
(React)ion news : Easy As Pie
Tags: react, javascript, webdev, beginners
Published: 2022-05-02 20:35:17

So I've been busy.
I've learned the basics of react, created a tutorial app, and re-did one of my past applications in react.

Its actually really easy. I LOVE react hooks.
From the outset, it seemed really confusing. 
But once you realize how they work, you won't be able to stop using it.

Here is the component from my redone application.
```
import {useState} from "react";
import './quotes.css';
function Quote() {
	let [quoteText, setQuote] = useState("");
	function getText()
		{try{
			fetch('https://ron-swanson-quotes.herokuapp.com/v2/quotes')
			.then(response => response.json())
				.then((data) => setQuote(data));
			}
			catch(err){
				console.log(err);
			}
		}
	return (
		<div className="MainDiv">
			<header className="quote-header">
			<h1>Random Swanson Quotes</h1>
				<div className="row">
					<div className="col">
<button onClick={() =>getText(quoteText)}>Sage Wisdom</button>
					< hr/>
						</div>	
					</div>
				<div class="row" id="mainrow">
				<div class="col-sm-12" id="quote">
			<p id="quoteBlock">{quoteText}</p>
		</div>
		</div>
		</header>
    </div>
	);}
export default Quote
```
From this, I've discovered that my biggest issue is getting ahead of myself.
Especially when learning new tech, I put the cart before the horse and then wonder why I haven't moved.

But now, I create micro apps to become adjusted with the language, and grow with the language from there.

I highly recommend React to any beginners. Once you learn it, its a very helpful tool.
Controlando a quebra de linha
Tags: html, css, braziliandevs, ptbr
Published: 2022-05-02 20:17:39

---
title: Controlando a quebra de linha
published: true
description: Como um caracter especial pode salvar a quebra de linha e alguns minutos da sua vida!
tags: html, css, braziliandevs, ptbr
cover_image: https://giovanisleite.dev/static/58a02d43788e945371cb3d9fa0c68fe6/a7c53/banner.webp
canonical_url: https://giovanisleite.dev/controlando-quebra-de-linha
---

Seja para criar um efeito estético ou evitar algum problema, tipo uma palavra viúva, aquela que sobra para outra linha no final de um parágrafo, é legal ter umas cartas na manga para dar aquela ajeita nos textos e nas quebras de linha. Ainda mais quando tratamos de partes chave do projeto, como a primeira coisa que vão ver no site que você está desenvolvendo, como é o caso da _Hero Section_[^1].

Por exemplo, estamos criando um site que o texto da nossa _Hero Section_ é "Vamos Jogar um Basquete". Os designers do nosso time pediram que a frase ocupe apenas uma linha em telas grandes o bastante, mas nas demais, o desejado é que ao quebrar, nunca a palavra "Basquete" fique sozinha na segunda linha.

Obviamente, podemos dar uma olhada como a frase fica disposta em vários tamanhos de tela e forçarmos a quebra de linha entre as palavras "jogar" e "um" com uma tag `<br>` e, para os tamanhos de tela, que cabem a frase toda, podemos usar media-queries[^2] para esconder a quebra de linha.

```html
<section class="hero">
  <h1> Vamos Jogar<br>um Basquete</h1>
  <button>Jogar</div>
</section>
```

Mas tem um jeito muito mais fácil e escrevendo muito menos! **É utilizando o caracter especial _Non-breaking space_[^3], no HTML ele é invocado assim: `&nbsp;`.** Esse caractere funciona como um espaço, mas, no momento da quebra da linha, ele não vai ser considerado. É como se "Um Basquete" fosse uma palavra só sob a regra padrão de quebra de linha, na qual uma palavra é indivisível.

Codando nosso exemplo:

{% codepen https://codepen.io/giovanileite/pen/XWZJKaK %}

[^1]: Geralmente, a primeira dobra (o que aparece no seu navegador assim que abre o site) da página inicial dos sites é chamada de _Hero Section_. A versão mais comum é uma imagem de fundo, um texto grande com o nome do produto e/ou um slogan e um botão convidando a se cadastrar, comprar o produto ou algo que seja do interesse do site em questão.
[^2]: https://developer.mozilla.org/pt-BR/docs/Web/CSS/Media_Queries/Using_media_queries
[^3]: https://en.wikipedia.org/wiki/Non-breaking_space
golang multithreading
Tags: go, concurrency, parallelism
Published: 2022-05-02 20:07:57

In my workplace, client had reported a performance bottle-neck and as a resolution, I was assigned to identify the bottleneck and make necessary changes to make it more efficient. After some time investing the logs, I had found the root cause and it was due to the repetitive occurrence of some time-consuming activity, which ultimately impacted on the response time.

After some workaround, I decided to execute the time consuming operations asynchronously and wait for the execution of asynchronous work and aggregate the final results. Here I found 3 ways to do this.

go-routines are light weight wrappers for threads, they will do the work using a pool of threads internally. 

### The Bad way 
TLDR: Execute jobs synchronously.
{% embed https://gist.github.com/lakshanwd/c2ccd1e8e3725f002bdf9567eaa16393.js %}
This is a bad way of doing asynchronous work since it blocks main thread and execute jobs synchronously.  

### The Normal way 
TLDR: Execute jobs asynchronously, but number of parallel jobs are uncontrolled
{% embed https://gist.github.com/lakshanwd/9990dcd7db01de22d4bceb07b0aaf834.js %}
In here, `sync.WaitGroup` is controlling the execution of background thread and it waits till the atomic counter of waitGroup is reduced to zero, which indicates all the routines have been executed. The problem with this approach is, if we get a large number of jobs in job array, there will be that number of go-routines which consumes resources.  

### The Better Way 
TLDR: Execute jobs asynchronously and number of parallel jobs are **controlled**
{% embed https://gist.github.com/lakshanwd/2f328a626e471e93d7cd908e5b94b791.js %}
This approach will do the work in a controlled parallel manner. So at any given time, it will use `max` number of go-routines to execute the jobs parallelly and will consumes less resources.