teleren/devto huggingface dataset:
Façade Design Pattern in Go
Tags: go, design, programming, productivity
Published: 2020-12-04 23:24:46

Hey there!

This is a late post in the week, but let's get into it. 

Let's assume you are trying to build a new API for a CLI. In this case, we are going to build a limited size console.

On our console, we are going to have a buffer of runes which we are going to be able to add, remove, or consult at any time. 

So for example, let's see how it'd be built:

```golang
type Buffer struct {
	width, height int
	buffer        []rune
}

func NewBuffer(width int, height int) *Buffer {
	return &Buffer{width, height, make([]rune, width*height)}
}

func (b *Buffer) At(index int) rune {
	return b.buffer[index]
}
```

In order to keep the example short, we are only going to add define the At method which will consult the character (or rune) at the 'index' index.

So, we now have a Buffer for our console and a constructor. And this would work for everyone, however, we want to give the user a not so complex interface in order to use our console. They'll be able to handle the Buffers if they want to do so, but we are going to handle them with an interface that configures the structures for them.

So then, let's give them a viewport to handle that buffer

```golang
type Viewport struct {
	buffer *Buffer
	offset int
}

func NewViewport(buffer *Buffer) *Viewport {
	return &Viewport{buffer: buffer}
}

func (v *Viewport) GetCharaterAt(index int) rune {
	return v.buffer.At(v.offset + index)
}
```

Right now, the user can interact with a portion of the buffer without the need of getting it in it's totality since some buffers can get really big to handle. 

Again, we are letting the user interact with the viewport if they please by using it's constructor and methods.

Finally, we can add the so-called Façade for our program:

```golang
type Console struct {
	buffers   []*Buffer
	viewports []*Viewport
	offset    int
}

func NewConsole() *Console {
	b := NewBuffer(200, 150)
	v := NewViewport(b)
	return &Console{[]*Buffer{b}, []*Viewport{v}, 0}
}

func (c *Console) GetCharaterAt(index int) rune {
	return c.viewports[0].GetCharaterAt(index)
}
```

On our console, we can have as many buffers and viewports as we want. Most systems will be initialized with just one of each, but that could easily be handled with another constructor in which we can specify how many of which we want or we can just add them to our buffers and viewports variables inside our Console instance.

```golang
func main() {
	c := NewConsole()

	u := c.GetCharaterAt(1)

	fmt.Println(u)

}
```

The user only has to initialize a console with it's constructor without having to think about the complexity behind the program and thus the façade works as intended.
Don't miss this Data for Good panel at MS Create: Data
Tags: sql, firstpost, azure, mscreate
Published: 2020-12-04 23:08:07

Join three inspiring and accomplished leaders (women specifically!!) in the data space for this data for good panel. Come get candid perspectives about what good data is and how it relates to actually doing good. I'll also seek to understand from the panelists how data tools can help us in keeping our data healthy.

You aren't going to want to miss this or the rest of the event. Register today at https://aka.ms/createdata
Stacking Elements to Solve Transition Issues
Tags: html, css
Published: 2020-12-04 23:05:56

I recently stumbled into a problem while attempting to create a transition for an anchor tag which used a linear gradient background. Unfortunately, the gradient background will not transition smoothly from a regular one; here's a neat solution to the problem.

{% codepen https://codepen.io/brandonmweaver/pen/VwKeoBg %}

Here, I used a container to act as the true position of the elements using `position: relative`, and placed the 'top' div over the 'base' div using `position: absolute; top: 0; left: 0;`. From there, I simply set the opacity of the 'top' div to zero percent, and one hundred percent when the hover state is triggered; creating the illusion of a transition from a gradient background to regular, and vice versa.
Advent of Code 2020: Day 02
Tags: adventofcode, algorithms, tutorial
Published: 2020-12-04 21:53:25

**[Originally Published on my blog](https://www.mahmoudashraf.dev/blog/adevnt-of-code-2020/)**

## Day 02

### part 01 ⭐

We have a list of passwords with validation rules, 
So we should validate each password and submit the 
total number of valid passwords.

```
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
```

First, let's create an parser to extract information from each line.

```javascript
const getPasswordsList = () =>
  readFileSync(path.resolve(__dirname, 'input.txt'), 'utf8')
    .split('\n')
    .filter(Boolean)
    .map((i) => i.split(/[-,:,\s]+/));
```

We read the `input.txt` file and convert it into an array by split each line using 
`.split(\n)` then we will use regex to extract min, max, target, and password 
on each line by using multi separator: `-`, `:`, and `\s` for space.

If you interred to learn more about split with regex I highly recommend to watch
[Regular Expressions: split() - Programming with Text](https://www.youtube.com/watch?v=fdyqutmcI2Q) video.

Now we are ready to write the validator function:

```javascript
function getValidPasswordsP1(passwords) {
  return passwords.reduce((ans, [min, max, letter, password]) => {
    const count = password.match(new RegExp(letter, 'g'))?.length;
    return count >= +min && count <= +max ? ++ans : ans;
  }, 0);
}
```

### part 02 ⭐

Actually the part two is a lot easier than the part one it assume the first two numbers
are the positions for the target letter to only occurs in one of them.

```javascript
function getValidPasswordsP2(passwords) {
  return passwords.reduce((ans, [pos1, pos2, letter, password]) => {
    return (password.charAt(+pos1 - 1) === letter) ^
      (password.charAt(+pos2 - 1) === letter)
      ? ++ans
      : ans;
  }, 0);
}
```

Use the bitwise `XOR` to make sure it only occurs in only exact one position.

You can check the MDN [reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR).
Can you help us building a local dev community?
Published: 2020-12-04 22:40:49

 Hi, we are a group of a few ppl from Spain, and we are studying web development. Our curriculum is outdated, it always has been a "problem" but now with corona I feel like me and my mates won't learn everything we could... I am luckily enough to be working already and I learnt some things by myself but I want to motivate them and wake them up, they can achieve a happy life coding (which I think is the happier way of life).

##What do we need?

So at the end of every idea in my head I thought that it would be super nice to build a community, to kind of "force" them to move, do some research etc... Why? Because I want them to gather information about different topics like state of web dev, or multiplatform dev, become producers of content not just spectators, idk, it's a long topic and I don't want to bore you, for real.

##How?

I want to focus the community more in motivation around coding, technology etc, instead of just "tutorials" or how tos. There is a lot of really good people making this. I want experienced coders to share with them ideas about life, more in the softskills part of ourselves. I think it's most than a half of a good developer.

![philosopher sharing](https://dev-to-uploads.s3.amazonaws.com/i/f96c0j0hxjl36wjvc2z9.jpeg)
 

We already planed the first online meeting to decide platforms, tools and work methodologies.

I already planned some content and work to keep them engaged, I even talked with companies to interact with the community. Also I focused everything for the job hunt improvement. It's a long story but a job would make them significantly happier.

> Can we get your help, please? 🥺

So yeah, of course, I am asking in one of my most beloved dev community. What are your tips to build communities? Have you ever build a local work group?

Any help is super welcomed!
EasyGrid - Responsive Grid
Tags: javascript, opensource
Published: 2020-12-04 22:38:04

Hey,

Did any of you feel the difficulty in making a grid of items?

Sometimes it is a little difficult to get it right, depending on the template and the space you have to use it.

I made a Javascript Plugin that makes it really easy and straightforward, It's called: EasyGrid.

Basically, it creates items dynamically, organize them and distribute them by columns automatically generated according to the width of the monitor (or container). 

It doesn't need any kind of CSS or CSS Framework and it was built with pure javascript, no dependencies.

Feel free to try it:
https://github.com/BMSVieira/EasyGrid

Thank you :D
Day 270: Application
Tags: hiphop, code, coding, lifelongdev
Published: 2020-12-04 22:35:09

_liner notes_:
- Professional : Had a couple of meetings. Got to show a new demo application I made this week. Rest of the day, basically trying to figure out how to get React Native to run properly on my work laptop. Ran a command on their website, looks like it almost went through, but got a weird error. Said something about cocopods dependencies and to run a command. Got an even more cryptic error message. Looked it up, kind of got a solution. Didn't work. Figured I would install XCode and see what happens. Went to the Mac App store to download it, would just cancel before even trying. Great. Went to download the beta version from the developer's portal. Why is the file 11GB!!!!! That took a while to download. Was told not to install the beta great. They said maybe I needed to update. Fine, did that. Still the app would not try to download from the store. Tried turning off my work's VPN. Then it started to download, awesome. Now I got a new error. It's says I need at least MacOs version 10.15. I was on 10.14. The newest version is 11, but that doesn't play nice with the software we have on the work computer. I could not find where I could get version 10.15.0 I would download updates for 10.15.7 and others, it would say I needed 10.15. Cool. Went to the Apple support page, clicked on the link for 10.15, it went to version 11. Wonderful. I had to watch a video on YouTube about upgrading to 10.15 and copy the URL from the browser the person was using into my own browser. haha. That opened the link to the version 10.15 in the MacOS App Store. Finally! I started the download. Again. It. Took. Forever! With that installed, I was able to install XCode. Ran the command line for a React Native project again.... got a new error this time. WooHoo! Looked it up. Apparently there is a command I need to run to get the Command Line Tools. Ran that, took forever to download. Of course. Got another error. Looked it up. Had to run another command that I think set the path to something. After that, finally got no errors! I was basically done for the day. haha

- Personal : Last night, worked on the demo application I got to show today. Then it got pretty dark and chilly. My brain pretty much shut down and I went to sleep. haha.

![The clouds above Above Žalý, Czechia at sunset.](https://dev-to-uploads.s3.amazonaws.com/i/bdf0ozuc9uoeo7oyuvf9.jpg)

Going to spend the night working on the radio show for tomorrow. After that, I'm going to watch more "Legion". Want to finish the series as soon as possible.

Have a great night and weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 9_3li9ruEVM %}
Is functional programming in JS really worth it?
Tags: javascript, webdev, typescript, discuss
Published: 2020-12-04 21:55:12

I admit that I am still at the beginning of my FP journey, but it's examples like these that make me sceptical about the whole FP hype which is consuming the JS world.

Imperative isOdd:

```js
const isOdd = n => n%2 === 1;
```

Imperative isEven:

```js
const isEven = n => n%2 === 0;
```

Declarative / FP isOdd:

```js
// utilities
const mod = y => x => x % y;
const eq = y => x => x === y;

const mod2 = mod(2);
const eq1 = eq(1);

const compose = (fn2, fn1) => v => fn2(fn1(v));

// end result
const fpIsOdd = compose(eq1, mod2);
```

Declarative / FP isEven:

```js
// utilities
const not = fn => x => !fn(x);

// end result
const fpIsEven = not(fpIsOdd);
```

The FP style may be more readable (or is it?), but I needed to write 5-6 utility functions to achieve the same end result, so what are the real benefits here?

**I wouldn't even know how I could justify writing code like this to my team members.** 

I am already used to writing FP code in moderation (in my JS/TS projects), like
 
- using .map, .reduce, .filter
- constructing pure functions
- using redux for global state management (store, pure reducers, actions) 
- doing shallow/deep copying of function params when needed (to minimise mutating reference variables outside of the function's lexical scope) 

And implementing these concepts doesn't require so much overhead in code. To be fair, redux does add a layer of indirection but it's totally manageable and justified.

But the more I learn about advanced FP concepts like pointfree style, composition and piping, the more absurd it seems to use it in my projects.

## So for me the jury is still out on this one

Maybe I just can't see the grand and majestic FP forest because of all the composition/piping trees that I'm currently surrounded with. 

What do you think about FP? Do you have any experience in using the more advanced techniques in some serious JS/TS projects?
Thinking of Contracting? Questions to ask yourself first.
Tags: career, contracting, freelance
Published: 2020-12-04 21:51:03

In the past, I've talked about the structural aspects of contracting.  Since then I've seen a few people questioning if contracting (specifically contract-employee) is a good option for them. 

Contracting isn't for everyone.  While I know some people who have been contracting their whole careers, some hate it.  However, if you look around, you'll find quite a lot of people making good money with contracting so that's why I wanted to share this information. 

Here's some questions to ask yourself:
1. How much do you value company perks and benefits.
2. How important is company provided health care. Can you get health coverage from a spouse/partner?
3. Do you work significant overtime? Are you paid for OT?
4. Do you enjoy settling in at a company or do you like to move around?
5. Would you consider giving up some company perks and befits for a higher take home pay?
6. What is your main motivation for even considering contracting?  


My friends and I created a couple videos on contracting.
{% youtube 78cD3kVpN9s %}
{% youtube -hGtBJN__r8 %}

Though I've been a contracting for a while now, it doesn't mean I'll stay one forever.  I'm curious to know how many people on DEV are contractors? What pushed you into contracting?  Or if you are not a contractor, are you considering it a option?

Oh, if you have any feedback on the videos, I've love to hear that too...it's our first ever videos.
Photo Credit: [unsplash](https://unsplash.com/@jontyson)
Advent of Code 2020: Day 01
Tags: adventofcode, algorithms, tutorial
Published: 2020-12-04 21:48:10

**[Originally Published on my blog](https://www.mahmoudashraf.dev/blog/adevnt-of-code-2020/)**

## Day 01

### part 01 ⭐

The first part of day one is a two-sum problem needs to get the 
multiply of two entries that sum to `2020`

The naive solution you can do two loops and make a condition whenever 
the two numbers sum to `2020` break the loop and return the value.

```javascript
function p1(input) {
  for (let i = 0; i < input.length; i++)
    for (let j = 0; j < input.length; j++)
      if (input[i] + input[j] === 2020) 
        return input[i] * input[j];
}
```

This solution will take `O(n^2)` time complexity for each element.

We can enhance our solution by using `Map` data structure and only one loop

```javascript
function p1(input) {
  const map = new Map();
  for (let i = 0; i < input.length; i++) {
    const complement = 2020 - input[i];
    if (map.has(complement))
      return input[map.get(complement)] * input[i]

    map.set(input[i], i);
  }
}
```

this solution will take `O(n)` time complexity by traverse the list containing 
`n` element only once.

### part 02 ⭐

The difference in the part two that we need to get the multiply for 
`three` numbers that sum to `2020`

We can use the same naive solution by using brute force with three loops.

```javascript
function p2(input) {
  for (let i = 0; i < input.length; i++)
    for (let j = 0; j < input.length; j++)
      for (let k = 0; k < input.length; k++)
        if (input[i] + input[j] + input[k] === 2020)
          return input[i] * input[j] * input[k];
}
```
Posting YouTube-only articles is hurting the quality in Dev.to
Tags: discuss
Published: 2020-12-04 21:45:17

I recently saw several authors here post what I call Youtube-only or "ghost" articles. Where they leverage the SEO of dev.to and the community to promote their Youtube (or other external links).

I think that it could be nice if they had to write a textual version in dev to also, and not just link it. It seems like it will add (I dare to say) spammy noise if not tackled.

---

Ideas I had, I didn't think them though, they are just starting points:
- Have a voting system to remove content-less articles.
- Allow posting Youtube only after a certain amount of rep.
- Force a minimum amount of text if you link YouTube.

--- 

Maybe this is only my thoughts, but I wanted to share before this becomes the next medium.com
My #100DOC - Day 100
Tags: 100daysofcode, challenge
Published: 2020-12-04 21:41:24

### Day 100: December 04, 2020
#### **Today's Progress**: 
1. **[DI exercises](https://github.com/pablohs1986/dam_di2021)** (1h 30min):<br>I keep working on the exercises. Focusing on creating my own components.
2. **Well, today I finished this challenge. It has been a great experience that has helped me to get regular coding.**
    
#### **What I learned**:
* Create own components on Java Swing. 

#### **Total time**:
1h 30min.
My #100DOC - Day 99
Tags: 100daysofcode, challenge
Published: 2020-12-04 21:41:07

### Day 99: December 03, 2020

#### **Today's Progress**: 
2. **[JAXB](https://github.com/pablohs1986/dam_ad2021)** (2h):<br>Studying JAXB with some exercises.
    
#### **What I learned**: 
* Marshalize, unmarshalize, query, insert and delete data.

#### **Total time**:
2h.
My #100DOC - Day 98
Tags: 100daysofcode, challenge
Published: 2020-12-04 21:40:46

### Day 98: December 02, 2020

#### **Today's Progress**: 
1. **[PSP, studying Threads](https://github.com/pablohs1986/dam_psp2021)** (2h):<br>I did several exercises to learn how to handle synchronization, monitors and semaphores.
    
#### **What I learned**: 
* Synchronization, monitors and semaphores;

#### **Total time**:
2h.
My #100DOC - Day 97
Tags: 100daysofcode, challenge
Published: 2020-12-04 21:40:22

### Day 97: December 01, 2020

#### **Today's Progress**: 
1. **[Review for SGE exam](https://github.com/pablohs1986/dam_sge2021)** (1h 30min):<br>I reviewed for the SGE exam.
    
#### **What I learned**: 
* Basics of ERP & CRM.
  
#### **Total time**:
1h 30min.
My #100DOC - Day 96
Tags: 100daysofcode, challenge
Published: 2020-12-04 21:39:58

### Day 96: November 30, 2020

#### **Today's Progress**: 
1. **[Review for SGE exam](https://github.com/pablohs1986/dam_sge2021)** (1h 30min):<br>Studying for SGE.
2. **[File Java Class](https://github.com/pablohs1986/dam_ad2021)** (1h 30min):<br>I went over how to use StringTokenizer, Iterator and complex structures in Java with a few exercises.
    
#### **What I learned**: 
* Basics of ERP & CRM.
* Review of StringTokenizer, Iterator and complex structures in Java.

#### **Total time**:
1h 30min.
Advent of Code 2020-04 with R
Tags: rstats, adventofcode
Published: 2020-12-15 20:35:11

---
title: Advent of Code 2020-04 with R
published: true
date: 2020-12-04 00:00:00 UTC
tags: rstats, adventofcode
canonical_url: https://colinfay.me/aoc-2020-04/
---

Solving Advent of Code 2020-04 with R.

[Disclaimer] Obviously, this post contains a big spoiler about Advent of Code.

## Instructions

### Step 1

- Inputs are of the form of

```
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm

iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929

hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm

hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in
```

Where each “passport” is separated by a new line.

To be considered valid, a passport has to have all of`c("byr","iyr","eyr", "hgt", "hcl", "ecl", "pid")`.

### Step 2

To be considered valid, a passport has to have all of`c("byr","iyr","eyr", "hgt", "hcl", "ecl", "pid")`, plus, each entry has to validate a series of rules.

Find the complete instructions at:[https://adventofcode.com/2020/day/4](https://adventofcode.com/2020/day/4).

## R solution

### Part one

```r
library(magrittr)
# Read the data
ipt <- readLines("2020-04-aoc.txt" ) %>% 
  # pasting everything into one big character string
  paste(collapse = "\n") %>% 
  # splitting where there are two \n\n (new lines)
  strsplit("\n\n") %>% 
  .[[1]] %>%
  # Removing the new lines
  gsub("\n", " ", .)

library(purrr, warn.conflicts = FALSE)

is_north_pole_valid <- function(
  x, 
  patt = c("byr","iyr","eyr", "hgt", "hcl", "ecl", "pid")
){
  map_lgl(
    patt, 
    ~ grepl(.x, x)
  ) %>% all()
}

map_dbl(
  ipt, ~{
    if (is_north_pole_valid(.x)) return(1)
    return(0)
  }
) %>% sum()

## [1] 204
```

### Part two

```r
ipt %>%
  # Remove the unvalid passport
  discard(~ !is_north_pole_valid(.x)) %>%
  # Split stuff
  strsplit(" ") %>%
  map_dbl(~{
    # Now, the heavy lifting
    # we have a string of key:value pairs, 
    # split it
    vals <- map_chr(.x, ~ gsub("([^:]*):(.*)", "\\2", .x)) 
    names(vals) <- map_chr(.x, ~ gsub("([^:]*):(.*)", "\\1", .x)) 
    
    # checking that values are inside range
    if (! dplyr::between(vals["byr"], 1920, 2002) ) return(0)
    if (! dplyr::between(vals["iyr"], 2010, 2020) ) return(0)
    if (! dplyr::between(vals["eyr"], 2020, 2030) ) return(0)
    # If height is in inch, check the range
    if ( grepl("in", vals["hgt"]) ) {
      if (! dplyr::between(gsub("in", "", vals["hgt"]), 59, 76)) return(0)
    } else if (grepl("cm", vals["hgt"])) {
      if (! dplyr::between(gsub("cm", "", vals["hgt"]), 150, 193)) return(0)
    } else {
      # No unit provided
      return(0)
    }
    if (! grepl("^#[a-f0-9]{6}$", vals["hcl"])) return(0)
    if (! vals["ecl"] %in% c("amb","blu", "brn", "gry", "grn","hzl", "oth")) return(0)
    if (! grepl("^[0-9]{9}$", vals["pid"])) return(0)
    return(1)
  }
) %>% sum()

## [1] 179
```
My #100DOC - Day 95
Tags: 100daysofcode, challenge
Published: 2020-12-04 21:39:34

### Day 95: November 29, 2020

#### **Today's Progress**: 
1. **[File Java Class](https://github.com/pablohs1986/dam_ad2021)** (1h 30min):<br>I went over how to use StringTokenizer, Iterator and complex structures in Java with a few exercises.
    
#### **What I learned**: 
* Review of StringTokenizer, Iterator and complex structures in Java.

#### **Total time**:
1h 30min.
My #100DOC - Day 94
Tags: 100daysofcode, challenge
Published: 2020-12-04 21:39:09

### Day 94: November 28, 2020

#### **Today's Progress**: 
1. **[DI exercises](https://github.com/pablohs1986/dam_di2021)** (1h 30min):<br>I keep working on the exercises. Focusing on Look&Feel.
    
#### **What I learned**: 
* Handle Look&Feel.

#### **Total time**:
1h 30min.
My #100DOC - Day 93
Tags: 100daysofcode, challenge
Published: 2020-12-04 21:38:43

### Day 93: November 27, 2020

#### **Today's Progress**: 
1. **[DI exercises](https://github.com/pablohs1986/dam_di2021)** (1h 30min):<br>I keep working on the exercises. Focusing on handling the TableModel.
    
#### **What I learned**: 
* Handle TableModel.

#### **Total time**:
1h 30min.