teleren/devto huggingface dataset:
Linear Regression: First Step towards Machine Learning
Tags: machinelearning
Published: 2021-02-09 18:26:03

If you are wondering how to start with machine learning and write hello world program in it then Linear Regression is what you are looking for.

# What is Linear Regression?
Linear Regression is a Supervised ML Algorithm that is used to predict some values from given data. Supervised Machine Learning Algorithms need some sample data from which they learn the relationship between given data and output value and then predict when new unseen data is given.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0nc4tidx2doiuvfy809n.PNG)
Suppose we have this above dataset and we want to know what is the value of Y at X = 10.
We could say that it will be close to 45 because the value of Y increases as X increases by observing the sample data.

Now how will the machine learn this? The machine will just find a line such that all data points are closer to it.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8babtozywi5fsvxht3dw.PNG)
This Line can be represented as
Y = B0 + B1*X
where B0 and B1 are the coefficients that define this line
 
B1 = Σ [ (xi - xm)(yi - ym) ] / Σ [ (xi - xm)^2]

B0 = ym - B1* xm 

where xm and ym are mean values of X and Y values respectively.

But what if we have Dataset Like this?
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/oe7ur6bo0ibn9e8aeonl.PNG)
We can clearly see that some points are too far away from the line.

Hence, we need to find how nicely this line fits the dataset.
To find how good a line is we need to calculate the Root Mean Squared Error.

RMSE can be calculated as follows:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ueo21gsu6qdi0hwtivj8.jpg)

Where N is the total number of data points.

If RMSE is close to 0, we can say that our regression line is fitted nicely.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8fju1c966yvso9betpod.PNG)

In the above plot length of red lines is the difference between predicted and actual values.

As RMSE increases with the difference in Predicted and actual values. 

We can say that the RMSE Of fig A is less than that of RMSE of fig B
Hence, the Line in figure B is not as fit as the line in fig. A for predicting values.
MongoDB: Inserting Data - Series #08
Tags: mongodb, javascript, database, express
Published: 2021-02-09 17:43:43


## Intro

In the last article in the series I showed how to establish a connection to MongoDB.

Here I'll show how to interact with data using that connection object.


Here's a simple insert:
```js
/**
@func
insert a single doc into a coll

@param {string} dbName
@param {string} collName
@param {object} o - the doc to insert into the coll
@return {Promise<object> | null} the inserted doc, or null if exception
*/
const mgInsertOne = async (dbName, collName, o) => {
  const client = await mongoAsync();
  try {
    return await client.db(dbName).collection(collName).insertOne({ ts: getDateStandardWithSeconds(), ...o });
  } catch (err) {
    console.error(err);
    return null;
  } finally {
    if (client) {
      client.close();
    }
  }
};

export default mgInsertOne;
```


Here's an example usage:
```js
 mgInsertOne("myCompanyDB", "userColl", { firstName: "fluffy" });
```

Here's the sample output:
```js
/*
@output
{
  ts: '[2021-02-09 Tue 09:21:21]',
  firstName: 'fluffy',
  _id: 6022c491834ad44058181f5b
}
*/
```


## Notes

The "mgInsertOne" utility func will return our inserted record. This is useful for delivering feedback in the UI.

Notice the utility func closes the client connection in the "finally" block

If the DB does not exists, it gets created dynamically.

If the collection does not exists, it gets created dynamically.

If you don't supply a primary key, which is field called, "_id", then the framework autogenerates one for you.

The client code of this func is a simple one liner. Wrap it in an Express.js route, push it to a provider like Heroku, and you're live within minutes — from composing the query — to having it available for clients to use.


## What's Next?

If you have any questions let me know.

The best way to perform queries in Mongo is using their "aggregate" func. It takes an arr of objs. Each obj is a part of the query that we're composing. It's an extremely powerful command that allows to you to shape and reshape your data any way your wish.
We'll cover more real-life examples of this powerful tool.
Start reading from the beginning of this series to get an introduction to this "Aggregation Framework".
What are IIFE or Immediate Functions on JavaScript?
Tags: javascript, webdev, programming, designpatterns
Published: 2021-02-09 18:23:10

😁 IIFE or Immediately-invoked Functions Expressions is a design pattern that runs functions as soon as such functions are created on its runtime environment.

😎 In general, IIFE's are related to the desire to not pollute the global object and/or to isolate business logics.

```javascript
;(function thisIsANamedIIFE() { 
    let name = "Beto Muniz";
})();
```

😋 This pattern is used a lot for library creators. Even Rollup.js, which is a good bundler for libraries offer this output.
A beginner-friendly guide to get Tailwind CSS up and running in your first web development project
Tags: css, codenewbie, html, webdev
Published: 2021-02-09 18:13:57

I've been hearing about [how cool](https://twitter.com/dhh/status/1349722147845976065?s=20) [Tailwind CSS](https://tailwindcss.com/) is, for quite sometime now so I decided to use it in a project I wanted to work on. 

When I went to the [installation](https://tailwindcss.com/docs/installation) page on the official Tailwind website, I realized that the guide could be a little overwhelming for people who are just starting out. With this guide, I aim to make the installation process a little simpler.

Ways to get Tailwind CSS up and running in your project:

1\. [**Tailwind Play**](https://play.tailwindcss.com/) - If you want to dive straight into writing code without having to worry about integrating Tailwind on your machine, this is the best option for you. You can start tinkering with your code and see what it does simultaneously. Also, with this option you don't have to dread writing that first line of code(like I do), since it already has a sample code for you to play with.🙂

2\.  [**Using Tailwind via CDN**](https://tailwindcss.com/docs/installation#using-tailwind-via-cdn) -  This is a great option for setting up Tailwind locally in no time. You just have to write a single line of code under the `<head>` section of your *.html* file and you can start working on your project straight away. 
                      
`<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">`

This does have a few [limitations](https://tailwindcss.com/docs/installation#using-tailwind-via-cdn) to it though, and therefore the Tailwind website doesn't recommend using this method. However, this is a good option if you hate long installation processes that make you want to quit coding. 

3\. [**Installing Tailwind CSS as a PostCSS plugin**](https://tailwindcss.com/docs/installation#installing-tailwind-css-as-a-post-css-plugin) - This is the method that you should go for if you want to work on a real-world project and hope to upload the code to your Github repo. Since in this method we install Tailwind CSS using npm, the first step would be to [install *Node.js*](https://nodejs.org/en/download/) on your machine. Next, you need to follow the steps over [here](https://tailwindcss.com/docs/installation#installing-tailwind-css-as-a-post-css-plugin) to complete setting up Tailwind locally. Don't worry if you don't understand a lot of the terms used in the guide. Just follow the steps and you'll be good to go!

That's it!

Do let me know if this guide helped you or if you have some feedback.

You can follow my journey on [Twitter](https://twitter.com/paridhitweets) as I try to learn web development by building a project using Tailwind CSS.
Dan Book’s Perl 7: A Modest Proposal
Tags: programming, link, perl, work
Published: 2021-02-12 04:48:42

---
title: Dan Book’s Perl 7: A Modest Proposal
published: true
date: 2021-02-09 18:13:01 UTC
tags: Programming,link,Perl,work
canonical_url: https://phoenixtrap.com/2021/02/09/dan-books-perl-7-a-modest-proposal/
---

[This proposal from Dan Book](https://dev.to/grinnz/perl-7-a-modest-proposal-434m) seems reasonable to me. A version 7 feature bundle that renders [signatures](https://perldoc.perl.org/feature#The-'signatures'-feature) non-experimental; removes the [indirect](https://perldoc.perl.org/feature#The-'indirect'-feature), [multidimensional](https://github.com/Perl/perl5/pull/17808), and [bareword filehandle](https://github.com/Perl/perl5/pull/18073) features; enables [warnings](https://perldoc.pl/warnings) and [utf8](https://perldoc.perl.org/utf8) by default? Sure. And more importantly, incrementing the major version every time a new feature is stable.

Unfortunately we’re still on [Perl 5.16.3](https://perldoc.pl/perl5163delta) at work, and it would be a big push to make sure our codebase is compatible with a newer version, much less adopt new features. But I’m willing to bet a reasonable release of version 7 might be just the push we need.
Solution: Convert BST to Greater Tree
Tags: algorithms, javascript, leetcode
Published: 2021-02-09 18:06:10

*This is part of a series of Leetcode solution explanations ([index](https://dev.to/seanpgallivan/leetcode-solutions-index-57fl)). If you liked this solution or found it useful,* ***please like*** *this post and/or* ***upvote*** *[my solution post on Leetcode's forums](https://leetcode.com/problems/convert-bst-to-greater-tree/discuss/1057425/).*

---

####[Leetcode Problem #538 (*Medium*): Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/)####

---

***Description:***

*Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.*

*As a reminder, a binary search tree is a tree that satisfies these constraints:*
  -  *The left subtree of a node contains only nodes with keys __less than__ the node's key.*
  -  *The right subtree of a node contains only nodes with keys __greater than__ the node's key.*
  -  *Both the left and right subtrees must also be binary search trees.*

---

***Examples:***

Example 1:||
|---:|---|
*Input:*|root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
*Output:*|[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
*Visual:*|![Example 1 Visual](https://assets.leetcode.com/uploads/2019/05/02/tree.png)

Example 2:||
|---:|---|
*Input:*|root = [0,null,1]
*Output:*|[1,null,1]

Example 3:||
|---:|---|
*Input:*|root = [1,0,2]
*Output:*|[3,3,2]

Example 4:||
|---:|---|
*Input:*|root = [3,2,4,1]
*Output:*|[7,9,4,10]


---

***Constraints:***
 - The number of nodes in the tree is in the range `[0, 104]`.
 - `-10^4 <= Node.val <= 10^4`
 - All the values in the tree are unique.
 - `root` is guaranteed to be a valid binary search tree.

---

***Idea:***

The simple solution here is just to **recursively** traverse the BST in reverse order and convert each node's value to the cumulative **sum** value of all the nodes already visited.

---

***Implementation:***

A **recursive inorder BST traversal** is extremely easy. Based on the nature of a BST, if you always go left first whenever possible, then deal with the current node, then go right, you'll end up dealing with the nodes in their sorted order.

In this instance, however, we can shorten the code by just doing the reverse: right first, then current, then left.

---

***Javascript Code:***

The best result for the code below is **104ms / 37.6MB** (beats 95%).
```javascript
var convertBST = function(root) {
    let sum = 0
    const trav = node => {
        if (!node) return
        trav(node.right)
        sum += node.val, node.val = sum
        trav(node.left)
    }
    trav(root)
    return root
};
```
New Relic Hackathon Update: Doubling the Cash Prize!
Tags: hacktheplanet, challenge, meta, newrelic
Published: 2021-02-09 17:55:32

---
title: New Relic Hackathon Update: Doubling the Cash Prize!
published: true
description: If you’ve been thinking about participating in New Relic’s Hack the Planet contest, this update on our prize package might just fully convince you!
tags: hacktheplanet, challenge, meta, newrelic
series: Hack the Planet
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/fjyrb5se5d3s6l4mp8d4.png
---

Now this is an update you don’t want to miss 👀

You might have noticed a few weeks back that an exciting new hackathon is currently underway in partnership with New Relic. If you’re interested in joining the fun, you’ll need to read the full announcement with instructions and guidelines [here](https://dev.to/devteam/announcing-the-new-relic-hack-the-planet-contest-on-dev-5d), but the TL;DR is this:

> **_Hack the Planet is your chance to build an app using New Relic’s free software observability tooling that’s focused around climate change and protecting the planet with data analysis and monitoring. You’ll submit your final project on New Relic’s new Forem-powered community called [The Relicans](https://therelicans.com)._** 

Besides building fun software tools aimed at helping the planet, a major benefit to participating in Hack the Planet is the package of prizes, which include eco-friendly swag, DEV shop credits, and cash!

### <mark>**Today, we’re excited to announce that our friends at New Relic have _doubled_ the cash prizes available to Grand Prize winners and Runners-Up, for a total of $20,000! We’re now awarding:**<mark>

* <mark>~~$2,500 USD~~ **$5,000 USD or equivalent to three Grand Prize Winners**<mark>
* <mark>~~$250 USD~~ **$500 USD or equivalent to 10 Runners Up**<mark>

You have until February 28th to submit your projects and be in the running to win a piece of this expanded cash prize pool. 

Read the rest of the hackathon details and guidelines in [this post](https://dev.to/devteam/announcing-the-new-relic-hack-the-planet-contest-on-dev-5d). 

Happy coding and good luck! 

---

#### _Additional Rules_
_NO PURCHASE NECESSARY. Open only to ages 18+. Contest entry period ends February 28, 2021, 11:59 PM PST/ 8 AM UTC on March 1, 2021. Contest is void where prohibited or restricted by law or regulation. All entries must be new projects and created during the hackathon period. For Official Rules, see [Contest Announcement Page](https://dev.to/page/hack-the-planet-rules) and [General Contest Official Rules](https://dev.to/page/official-hackathon-rules)._
Learn more with Chaos Engineering Bootcamps
Tags: litmuschaos, kubernetes, testing, devops
Published: 2021-02-09 17:34:09

There is an unmistakable buzz and excitement that the [chaos carnival](https://chaoscarnival.io) is generating, and I just can’t wait for it to begin. While tons of material has been generated about chaos engineering - the what, why & how over the last few years, nothing beats the experience of hearing actual practitioners talk about their learnings. The chaos carnival has an impressive line-up of such speakers and their experiences & accounts will add to the abundant wealth of info out there. As members of the organizing team, and more importantly advocates of cloud-native chaos engineering, we felt this is also a good opportunity to ease people into chaos engineering via simple bootcamps during the break period. 

As the attendees flit through different tracks, they will also have an opportunity to take a low-level, hands-on intro to chaos use cases - that we will accomplish using LitmusChaos. Unlike most demos/intro sessions we have conducted in the past during meetups & conferences, the idea behind these bootcamps is to take an actual real-world application (like Kafka, Percona MySQL) - not a hello service :) - and inject chaos with a well-defined hypothesis around the failure. 

During the session, you will also be introduced to the observability elements in chaos engineering & how experiments both generate as well as consume observability info that helps you to validate the hypothesis. Considering these bootcamps are scheduled during breaks, they will be split into two parts: an instructor-led tutorial explaining each step followed by an optional guided lab that you can join-in to experience, where the participants will be provided access to a pre-packaged Kubernetes cluster environment that has been bootstrapped with the necessary dependencies allowing them to recreate and experience the chaos steps. 

During the tutorial, we will also discuss the KPIs on how you can measure your progress around your efforts on chaos engineering. 

To participate in the bootcamp on Days 1 & 2 of the event, please join & track the announcements in the chaos carnival slack channel. If you’d like to also perform the optional lab exercise, please do reach out via email ([Karthik.s](karthik.s@mayadata.io), [Udit Gaurav](udit.gaurav@mayadata.io) or [Shubham Chaudhary](shubham.chaudhary@mayadata.io)) or DMs on the [chaos carnival](https://chaoscarnival.slack.com/archives/C018Q4T4F2A) slack channel. There are a limited set of pre-packaged environments available - the access to which will be emailed on a first-come-first-service basis and stay active for the duration of the lab! 

We hope that these sessions are fun, pique your interest in chaos engineering, reduce your apprehension and inspire you to dig more so you take those bold steps towards application resilience. They would also serve as a nice indicator of the prerequisites needed to kickstart these efforts in your organization.
How do you think tech can better protect people from harassment? Answer for the chance to appear on the DevDiscuss podcast!
Tags: discuss, podcast
Published: 2021-02-09 17:28:16

---
title: How do you think tech can better protect people from harassment? Answer for the chance to appear on the DevDiscuss podcast!
published: true
tags: discuss, podcast
---

The [DevDiscuss Podcast](https://dev.to/devdiscuss) begins with an interview and ends with commentary from listeners — and we like to feature the actual _voices_ from our community!

To enrich an upcoming episode of the show, we'd like to know...

> ### **“How do _you_ think tech can better protect people from harassment?”** 
  
For your chance to appear on an upcoming episode, answer the question above by:

- Calling our Google Voice at +1 (929)500-1513 and leave a message 📞

- Sending a voice memo to pod@dev.to 🎙

- OR, leaving a comment here (we'll read your response aloud for you) 🗣

_Please send in your recordings by TOMORROW, Wednesday, February 10th at Midnight, ET (9 PM PT, 5 AM UTC)_

_**Voice recordings will be given priority placement**_ 😉 

---

Don't forget to check out the most recent season of DevDiscuss [here](https://dev.to/devdiscuss)
How To Encrypt Fields in Ruby on Rails with Lockbox
Tags: rails, tutorial
Published: 2021-02-09 17:27:18

{% youtube sEOLtIGkDeM %}

If you're storing any sensitive data such as API Keys, or personal data you should probably be encrypting it within your database. A fantastic gem to do this with is [lockbox](https://github.com/ankane/lockbox).

While the best defence against losing sensitive data is to not save it in the first place, you may have a scenerio where you require it later on. From this perspective, it's ideal to make sure you make it as hard for the evil people as possible.

Examples of data you might want to consider encrypting are:

- API Credentials, for example the tokens you receive from an OAuth request.
- Email & Postal Address
- Personally Identifiable Information (PII)

## The code

Start by generating a key using `Lockbox.generate_key`, store the results as the ENV `LOCKBOX_MASTER_KEY`.

```bash
# .env
LOCKBOX_MASTER_KEY="Generate with Lockbox.generate_key"
```

Create a migration for the field you'd like to encrypt. Once you've decided on the accessor, append `_ciphertext` to that name.

```ruby
class AddApiKeyCiphertextToPosts < ActiveRecord::Migration[6.1]
  def change
    add_column :posts, :api_key_ciphertext, :text
  end
end
```

Lastly, use the `encrypts` magic within your model to give you a setter & getter which stores its value in that `*_ciphertext` column as an encrypted value.

```ruby
# app/models/post.rb
class Post < ApplicationRecord
  # Stored in api_key_ciphertext but encrypted 🤯
  encrypts :api_key
end
```
How to Customize Scrollbar and Cursor Pointer
Tags: css, javascript, html, webdev
Published: 2021-02-09 17:21:00

![Alt text of image](https://blogtimenow.com/wp-content/uploads/2014/07/custom-scrollbar-wordpress.jpg)

#Customize Scrollbar

In order to customize the scrollbar, you have to use `::-webkit-scrollbar` property.
```CSS
::-webkit-scrollbar
```
You can specify the width of the scrollbar and also set the scrollbar track or path by setting the background property.
```CSS
::-webkit-scrollbar {
    width: 15px;
    background: #f7ece1;
}
```
Next, selecting the scrollbar itself by `::-webkit-scrollbar-thumb`

```CSS
::-webkit-scrollbar-thumb {
    background: #cf5c36;
    border-radius: calc(15px / 2);
}
```
Furthermore, you can also add some hover effect on `::-webkit-scrollbar-thumb`. 

#Customize cursor

The basic way to customize your cursor is by using the `cursor` property with `url()` value.

```CSS
body {
  cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/happy.png"), auto;
}
```
One thing to remember here is you have to use the `auto` as a fallback value.

However, with `cursor: url('...'), auto;`  you don't have that much control. In order to customize the cursor even more and have more control over the process, we have to use javascript.

At first, we will create a div with a class cursor.

```HTML
 <div class="cursor"></div>
```
Let's style this div.
```CSS
.cursor {
  position: absolute; /* so it is out of the flow */
  width: 20px;
  height: 20px;
  background: white;
  mix-blend-mode: difference;
  border-radius: 50%;
  transform: translate(-50%, -50%); /* so it is center with the cursor pointer */
  transition: 200ms ease-out;
}
```

Now, let's add JavaScript.

```javascript
const cursor = document.querySelector(".cursor");

document.addEventListener("mousemove", customizeCursor);

function customizeCursor(e) {
  cursor.style.top = e.pageY + "px"; 
  cursor.style.left = e.pageX + "px";
}
```

Full Code: 

{% codepen https://codepen.io/tanveersayem/pen/zYoBQvb %}



TLDR: Watch the video instead. [Customize Scrollbar and Create custom cursor with CSS and JavaScript!](https://youtu.be/eN0zu2hMPtw)

{% youtube eN0zu2hMPtw %}