teleren/devto huggingface dataset:
Day 3 of #100DaysOfCode: JS Fractals in CodePen and Observable
Tags: fractals, javascript, canvas, 100daysofcode
Published: 2020-04-18 03:57:46

---
title: Day 3 of #100DaysOfCode: JS Fractals in CodePen and Observable
published: true
description: Drawing fractals with JS in two interactive JS coding environments.
tags: fractals, javascript, canvas, 100DaysOfCode
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/htmeaw8dfrdlnqvz4coa.png
---

Yesterday I saw @lautarolobo's tutorial on [coding fractal trees in JS](https://dev.to/lautarolobo/use-javascript-and-html5-to-code-a-fractal-tree-2n69), and I knew I had to try it. Besides, it's Fractal Friday!

I opened up CodePen and was going to use HAML, then realized that the Pug HTML processor was available. Why not try Pug while I'm at it, right? My Pug code was nice and short:

```
h1 Fractal Tree
canvas#my_canvas(width="1000", height="800")
```

I gave the canvas a nice light gray background so I could see the bounds:

```
#my_canvas { background-color: #efefef; }
```

Then I defined the recursive `draw()` function as per the first tree version in @lautarolobo's tutorial, where each execution:
* Moves to `startX`, `startY`
* Draws a line of length `len`, angle `angle`
* Calls itself to draw left and right branches until `len` < 10

{% codepen https://codepen.io/audreyr/pen/jObrOXm %}

I brought the code over to Observable and hooked it up to sliders controlling the two values that were hardcoded: the ratio of new branch length to old, and the angle at which a new branch sprouts.

* I got the slider code from [Huy Nguyen's Fractal Tree notebook](https://observablehq.com/@kuquanghuylcb/fractal-tree) which is similar to this but more configurable.
* I could have implemented this in CodePen but it would have been much more verbose than in Observable (*I think*)

![Observable Notebook with JavaScript Fractal Tree](https://dev-to-uploads.s3.amazonaws.com/i/m7by7iwcwubr0e3r6kom.png)

The above is just a screenshot because I don't think you can embed live running code on dev.to (unless I'm wrong?). Check out the interactive slider version: https://observablehq.com/@audreyr/fractal-tree-1

Finally, I experimented with different left vs. right branch ratios back in CodePen and got some pretty results. Here's left `branchPercent` 0.5, right 0.8:

![Fractal Tree, Leaning Right](https://dev-to-uploads.s3.amazonaws.com/i/j7zu4hhpfujimgxhuxr2.png)
06: Binary system 
Tags: computerscience
Published: 2020-04-18 03:35:42

#**Why '0' and '1'?**
Binary (or base-2) a numeric system that only uses two digits — 0 and 1. Computers operate in binary, meaning they store data and perform calculations using only zeros and ones.

A single binary digit can only represent True (1) or False (0) in boolean logic. However, multiple binary digits can be used to represent large numbers and perform complex functions. In fact, any integer can be represented in binary.

Below is a list of several decimal (or "base-10") numbers represented in binary. 

----

*One bit contains a single binary value — either a 0 or a 1. A byte contains eight bits, which means it can have 256 (28) different values. These values may be used to represent different characters in a text document, the RGB values of a pixel within an image file, or many other types of data.*

*Large files may contain several thousand bytes (or several megabytes) of binary data. A large application may take up thousands of megabytes of data. No matter how big a file or program is, at its most basic level, it is simply a collection of binary digits that can be read by a computer processor.*

---- 
###NOTE: 
The term "binary" may also be used to describe a compiled software program. Once a program has been compiled, it contains binary data called "machine code" that can be executed by a computer's CPU. In this case, "binary" is used in contrast to the text-based source code files that were used to build the application.
A Bit of Progress
Tags: job, javascript, progress, update
Published: 2020-04-18 02:38:33

So some of you may have seen my post a few weeks ago about having an interview with several people at a company I applied to. Good news, if you haven't gone back to that post, I got the job! 

In this weird time where people are being furloughed and laid off from their jobs I feel a bit bad about celebrating this win. Not just because I got this job. I also applied to be a Teaching Fellow with LaunchCode and got that as well! I am now one week out from training with LaunchCode and two weeks out from starting the new "real" job. I wanted to be able to post this win on Facebook and LinkedIn, but I feel it's better not to. At least I can post it here.

Enough about the psychology that's happening in my brain. For both jobs I have to learn JavaScript, Angular, PHP, and Drupal. I'm excited to dive into these, especially since I've already been seriously working my way through JavaScript on Codecademy and through LaunchCode (I'm a graduate of LC101 with LaunchCode. My cohort was the last one to do Python paired with Java. Now it's JavaScript and Java and we retain our access to all of the coursework) since about February. I'm catching on pretty well and have made it my plan to get through all the standard JavaScript by my start date with the main job. I'm doing pretty well attempting to work through something everyday. 

I'm really excited to do both of these jobs and a little nervous as both will be virtual until (let's be real) the government/my state says we can return to the office/classroom (oh my god this is getting confusing. Sorry!). I wanted to try to track my progress and even thought about making a YouTube channel for it, but when I started I was also doing rehearsals for a play that wound up getting cancelled. So maybe I'll try to do it for Angular, PHP, and Drupal.

Thank you for reading my ramblings! Hope everyone has a great weekend!
05: Digital Circuit 
Tags: computerscience
Published: 2020-04-18 03:07:36

#Definition of Digital Circuit
A digital circuit is an electric circuit where the signal is either of the two discrete levels – ON / OFF or 0 / 1 or True / False.

Transistors are used to create logic gates to perform Boolean logic.

----
*Software like Electronic Design Automation (EDA / ECDA) is used to design digital circuits. Both Paid and Free EDA Software are available online for Download*

----

##*How Digital Circuit Works?*
In digital electronic circuits, electric signals take on discrete values, which are not dependent upon time, to represent logical and numeric values. These values represent the information that is being processed.
Best Profit in Single Sale
Tags: challenge, javascript, algorithms, interview
Published: 2020-04-18 02:46:52

Step by step thinking and solution for the challenge : <a href="https://dev.to/thepracticaldev/daily-challenge-228-best-profit-in-single-sale-48pb"> Dev challenge 228 </a>

Question: You work as a hotshot day trader at Wall Street. Someone tipped you off and you got hold on the different rates at which a particular stock will sell at (highly illegal activity). 
Since you don't want to arise suspicion, you decided that you'll get into a single trade and get as much profit as possible. 
What's the max profit you can get? 

Eg: Price = [7,1,5,3,6,4], output = 5, Buy on day 2 and sell on day 5. 6 - 1 = 5.

Some rules : 
1> Once you buy a stock you can sell only on a later day, ie you can't buy stock on day 4 and sell it on day 1. 
2> You can perform only one transaction, ie if you buy on day 1 and sell on day 2, you can't buy/sell on any later day.
3> You can perform one transaction per day, ie either you can buy on that day or sell on that day. You can't buy and sell on the same day. 

With that out of our way. Let's solve this.

Brute Force: O(n^2)
Brute force approach would be to go over prices and compute all possible sale prices and find the maximum among them.

```javascript
var maxSale = function(prices){
     int maxprofit = 0;
        for (let i = 0; i < prices.length - 1; i++) {
            for (let j = i + 1; j < prices.length; j++) {
                let profit = prices[j] - prices[i];
                if (profit > maxprofit)
                    maxprofit = profit;
            }
        }
        return maxprofit;
}
```

Now let's work on optimizing it. 

Observations : 
1> We want to find the maximum profit, maximum profit occurs when our buy at the least price and sell at the maximum price. 

One pass : O(n)
Let's maintain a variable minPrice, which tracks the minimum stock price. 
We'll go through prices if at a day, the stock price is less than the minPrice till that day, reset the minPrice. If stock price is not less then check if we can get maximum profit by selling stock on that day. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zwk4iazfp1rblhvsswd7.png)

```javascript
var maxProfit = function(prices){
        
        // initially set to minimum price
        let minprice = Number.MIN_VALUE;

        // set max profit to 0
        let maxprofit = 0;
        for (let i = 0; i < prices.length; i++) { 
         
            // if Current price is less than minprice found till now, 
            // set min price to current price. 
            if (prices[i] < minprice)
                minprice = prices[i];
         
            // else check if selling stock on ith day will give us maximum profit.
            else if (prices[i] - minprice > maxprofit)
                maxprofit = prices[i] - minprice;
        }
        return maxprofit;
}
```
Now you know how to earn profits by stock trading, go spend that hard earned money on your gold digger crush 🤪. 

github : https://github.com/AKHILP96/Data-Structures-and-Algorithms/blob/master/problems/BuyAndSellStocks.js
Help! How to upload files to S3
Tags: help, aws, react
Published: 2020-04-18 02:12:22

Hey all :) I am struggling with something and wondering whether somebody could help me.

I am trying to upload files to S3. I have watched several tutorials on it and am still having trouble, specifically:

Whether to upload from server-side or client? For this project, the cost is a priority and based on this [article] I am learning toward uploading client side. Is that the correct approach?





[article]: https://levelup.gitconnected.com/upload-image-directly-from-react-app-to-amazon-s3-856280c62e45
[rant]: The way I've been thinking about software lately
Tags: javascript, webdev, career, programming
Published: 2020-04-18 02:02:35

---
title: [rant]: The way I've been thinking about software lately
published: true
description: 
tags: #javascript #webdev #career #programming
---

Baking is a whole art on its own.

You should be determined to deliver an
amazing experience at the end of the process.

Think about it for a sec.
* Select which elements will be used in the process.
* Note if any special care is to be taken given the end goal.
* Proceed with setting up the environment with everything we need before begin.
* Put together the elements in such a way that it achieves a specific goal.
* Watch carefully how everything holds an evolves together until achieving the final form.
* Finally put it on the open, ready for consumption of those who enjoy it.

Having said that I feel like I'm an App Baker for sure.
How to test Java Classes using JUnit5 and Reflection API
Tags: java, testing
Published: 2020-04-18 00:59:00

I have created a project which is intended to demonstrate the following using `Java`, `Maven` and `JUnit5`
 
- If the `Class` exists in project.  
- If the class contains a `method` with a specific name
- If a method is `public`, `private`  
- If a method contains parameters with specific types  
- If a method returns a specific type

And there could be more additions to such a list.  

This project makes use of [ReflectionUtils](https://junit.org/junit5/docs/5.0.3/api/org/junit/platform/commons/util/ReflectionUtils.html) class from `Junit5` and `Java`'s [Reflection API](https://junit.org/junit5/docs/5.0.3/api/org/junit/platform/commons/util/ReflectionUtils.html) 

The codebase and tests are available at [GitHub](https://github.com/hhimanshu/reflection-testing)
How to set a database with MongoDB Atlas
Tags: beginners, mongodb
Published: 2020-04-18 00:08:16

###What is MongoDB?
"MongoDB is a document database, which means it stores data in JSON-like documents." - [Official MongoDB Website](https://www.mongodb.com/) MongoDB is one of the most popular NoSQL databases.

###What are the advantages of NoSQL?
- Scalability: by default, non-relational databases are split (or "shared") across many systems instead of only one. This makes it easier to improve performance at a lower cost.
- Flexibility: new datasets and properties can be added to a document without the need to make a new table for that data.
- Replication: copies of the database run in parallel so if one goes down, one of the copies becomes the new primary data source.
[FreeCodeCamp](https://www.freecodecamp.org/learn/apis-and-microservices/mongodb-and-mongoose/)

###What is MongoDB Atlas?
MongoDB Atlas is a database hosted in the cloud. MongoDB Atlas handles all the complexity of deploying, managing, and healing your deployments on the cloud service provider of your choice (AWE, Azure, and GCP).

###Steps to create a cluster on MongoDB Atlas
If this is your first time using MongoDB Atlas there probably be a button in the left-hand corner where you can follow the steps. If you've used MongoDB Atlas and have forgotten the steps here they are.

1a. Create a MongoDB Atlas account
1b. Under context, there is a dropdown where you can create a new project
2. Create a new cluster
- You can keep everything as the default
3. Create a new user on the Database
- You can find this in the Database Access
4. Whitelist your IP address
- This can be find this in the Network Access
- Allow access from anywhere (0.0.0.0/0)
5. Connect to your cluster
- Go back to your cluster and press connect
- Click on Connect your application
- You will use your URI to connect to your database
- It should look like this "mongodb+srv://<user>:<password>@<cluster#-dbname>.mongodb.net/test?retryWrites=true, notice that the user and cluster#-dbname"

Thank You for reading!
If you have any questions or something that looks off to you please feel free to comment. Tell me how you like MongoDB or MongoDB Atlas, I would love to hear your experience with it.
line-height in CSS
Tags: lineheight, css
Published: 2020-04-15 12:54:56

---
title: line-height in CSS
published: true
description: In this article, the property line-height in CSS is explained.
tags: line-height, css
---

The CSS property **[line-height](https://www.w3schools.com/cssref/pr_dim_line-height.asp)** defines the amount of space used for lines, most commonly in the text. 

It is often confused with **line spacing (leading)** used in Photoshop and similar softwares.

Leading is a term that describes the distance between the baselines in the text. In the case of defining leading, space is always **added below the text**. But, when working with line-height property, space is always added **equally above and below the text**. 

Line-height uses several different types of **units**: 
* **px**,
* **em**,
* **%**,
* **unitless number**,

It’s important to mention that the **unitless value is, basically, just a percentage**. So, if the line-height has a property of **1.2**, it means it just has a value of **120%**. 

## Importance of line-height

The most important use of line-height is **making your text readable**. It is recommended to use unitless values of any other unit that **isn’t static** like the px unit. 

If there is a need to set the font size and line-height at the same time, there is a handy CSS **shorthand**:

```
html {
  font: 24px/1.5 ‘Lato’, sans-serif;
}
```

By using this shorthand you will be able to set 3 elements at the same time:
* font-size,
* line-height,
* font-family.

The line-height property applies only to elements that have their display property set to **inline or inline-block**. If the line-height is set on a block element, there might be some changes, but it is probably just the **inline child** elements that have been affected. 

If you set the line-height without a unit, the result is the **line-height value multiplied by the element’s font-size**.

```
div {
  Font-family: ‘Lato’, sans-serif;
  Font-size: 14px;
  Line-height: 2 // equals to 28px
}
```


Hope this article helped clarify the meaning and usage of the line-height property.

Thank you for reading!

*Originally published at [Kolosek blog](kolosek.com/css-line-height/).*
You can pass a predicate to RxJS’s first() operator, I was not aware!
Tags: rxjs, javascript, typescript, webdev
Published: 2020-04-18 12:22:58

---
title: You can pass a predicate to RxJS’s first() operator, I was not aware!
published: true
date: 2020-04-18 00:00:00 UTC
tags: RxJS,Javascript,typescript,webdev
cover_image: https://www.leonelngande.com/images/uploads/rxjs-first-operator-predicate-function-illustration.png
canonical_url: https://www.leonelngande.com/you-can-pass-a-callback-function-to-rxjss-first-operator-i-was-not-aware/
---

My typical use-case for RxJS first() operator is to emit only the first item of an observable stream. What if you want the first value based on a certain condition instead?

I recently found out you can pass in an optional callback function ([predicate](https://stackoverflow.com/a/1344021)) just for this.

> **[First](http://reactivex.io/documentation/operators/first.html)**  
> _emit only the first item (or the first item that meets some condition) emitted by an Observable_.

`predicate` is a function you write to evaluate an expression and return true or false. You can have a look at it’s source [here](https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/first.ts).

```typescript
export function first<T, D = T>(
  predicate: (value: T, index: number, source: Observable<T>) => boolean,
  defaultValue?: D
): OperatorFunction<T, T | D>;

```

As an example, say we setup a listener for DOM click events.

`const clicks = fromEvent(document, 'click');`

We later decide we’d like to receive only the first click event that happens on a DIV, here’s how we’ll do that:

```typescript
import { fromEvent } from 'rxjs';
import { first } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');

const result = clicks.pipe(first(ev => ev.target.tagName === 'DIV'));

result.subscribe(x => console.log(x));

```

As seen above, we make use of the first() operator passing it a callback function that receives a click event, and returns true if the tag name is DIV, false otherwise.

Hopefully, like me, you’ve learned something new from this tiny blog post 🙂.
Quickly exploring CSV files with wc and awk
Tags: bash, productivity
Published: 2020-04-19 00:53:47

---
title: Quickly exploring CSV files with wc and awk
published: true
date: 2020-04-18 00:00:00 UTC
tags: bash, productivity
canonical_url: 
---

This week I was extracting high-intensity activity episodes from the Fitbit data of 150 people. The first thing I wanted to know after processing all participants was how many people had at least 1 episode. I am using [RAPIDS](https://rapidspitt.readthedocs.io/en/latest/) to process the data, which means that the activity episodes for each participant are stored one per line in CSV files in individual folders. As I was looking for a quick and short solution, I went for Bash instead of Python or R.

Then, the problem is reduced to three steps: list all files in a subfolder with names that match a pattern, count the lines on each file, and filter those files with at least 2 lines (all files have at least the header row). For that, we can use `wc` and `awk`.

```
wc $(find . -name 'p*_fitbit_mvpa_episodes.csv') | awk '{if (($1 > 1) && ($4 ~ /^\.\/data/)) { print }}' | wc -l

```

The first part `wc $(find . -name 'p*_fitbit_mvpa_episodes.csv')` executes the `wc` command on the output of the `find` command, which retrieves all files in the current directory and any subdirectories with a name that matches the regular expression between quotes. The [default output](https://www.mkssoftware.com/docs/man1/wc.1.asp) of the `wc` command has four columns for each file: line count, word count, byte count, and its path. These are piped into `awk '{if (($1 > 1) && ($4 ~ /^\.\/data/)) { print }}'` which filters and prints those lines where the value of the first column `$1` (line count) is bigger than one and the fourth column `$4` (file path) starts with `./data`. The first part of the filter gets all the files with at least one activity episode (header + episode line), and the second part excludes the total count that `wc` appends. Finally, to obtain the _number_ of files with at least one activity episode, I piped the previous list to `wc` with the `-l` flag that counts the number of lines (files) that `awk` printed. It turns out that out of 150 participants, only 20 have high-intensity activity episodes (this lead us to discover a problem with the data I was working with that is a matter for another post).

As an extra bit of information useful for our collaborators, I wanted to know the average number of episodes across all participants. For this I followed a similar process but instead of the second `wc -l`, I piped the output to `awk` where it is possible to keep a counter and sum of the values of each line, obtaining the average for the first column (line count) as follows:

```
wc $(find . -name 'p*_fitbit_mvpa_episodes.csv') | awk '{if (($1 > 1) && ($4 ~ /^\.\/data/)) { print $1}}' | awk '{ total += $1; count++ } END { print total/count }'

```

We have an average of 17.3 episodes across 20 people.
📚 How I am Learning Go
Tags: go
Published: 2020-04-17 23:54:08

```go
fmt.Println("Hello, Go!")
```

One of my favorite things to do my senior year in college was to attend hackathons. In one of those hackathons, I needed to build a web service that can handle HTTP requests. At the end of that weekend, I learned how to use AWS Lambda.

> Random thought 💭: Man, I miss those free AWS credits from [MLH](https://mlh.io/)!

Fast forwarding almost two years, I have gotten to work with many AWS services. Through that process I have developed a passion for building tools and infrastructure. While learning about DevOps, I came cross Go and I was quickly intrigued. That now leads to this post.

After many weeks of putting it off, this week I decided to start learning Go. First, I started reading the book *[The Go Programming Language by Alan Donovan and Brian Kernighan](https://www.amazon.com/Programming-Language-Addison-Wesley-Professional-Computing/dp/0134190440)*. The first couple of chapters gave me a great introduction to the language but mid-way through chapter 3, I realized that this is not a book to get me started quickly. So instead, I turned to *[Go in Action by William Kennedy, Brian Ketelsen, and Erik St. Martin](https://www.amazon.com/Go-Action-William-Kennedy/dp/1617291781)*. This book has been a quick read and has given me a high level introduction to Go (currently reading chapter 6 on concurrency). I have enjoyed it very much!

To put into practice what I have learned so far, I am solving problems on *[Leetcode](https://leetcode.com/)*. I have found this approach has helped me get familiar with built-in types and packages. Through this, I realized that I needed to understand pointers better (a post on that coming soon). So far this have been a fun and challenging approach.

My direction going forward is to finish reading the *"Go in Action"* book and start working on projects, which I am noting down as random ideas come up.

Feel free to comment on ways that you have approached learning Go or any other programming language and project ideas you recommend!

Cover image by Maria Letta from https://github.com/MariaLetta/free-gophers-pack