teleren/devto huggingface dataset:
How to continuously drag an element in React with javascript
Tags: react
Published: 2019-11-14 11:09:27

In this post, I will show you an implementation for moving around an element with the mouse with the aid of javascript. The implementation is simple.

Here it is:
```javascript
import React from 'react'
import styled from 'styled-components'

export const Ball=
()=>
{
  let offsetX,offsetY
  const move=e=>
  {
    const el=e.target
    el.style.left = `${e.pageX-offsetX}px`
    el.style.top = `${e.pageY-offsetY}px`
  }
  const add=e=>
  {
    const el=e.target
    offsetX=e.clientX-el.getBoundingClientRect().left
    offsetY=e.clientY-el.getBoundingClientRect().top
    el.addEventListener('mousemove',move)
  }
  const remove=e=>{
    const el=e.target
    el.removeEventListener('mousemove',move)
  }
  const Wrapper=styled.div`
  width: 50px;
  height: 50px;
  border-radius: 29px;
  box-shadow: 0 0 6px;
  position: absolute;
  top: 40px;
  left: 227px;
  background-color: rgb(0,0,0,0.5);
  cursor:pointer;
  `
  return (
    <Wrapper onMouseDown={add} onMouseUp={remove}/>
  )
}
```
Let's comment on what happens here. 
We define three event handlers: `move`, `add`, and `remove`. 
The first one, `move`, is for moving around the element. It uses `offsetX` and `offsetY` to calculate the position to move. `offsetX` is the distance from where the mouse is positioned to the border (left) of the element. `offsetY` is the same with the `Y` coordinate. These two values are calculated on the `add` event handler (or function).
In the `add` function what we do is to attach the `move` function to the on `mousemove` event (with the element itself as a listener). And also we calculate the `offsetX` and `offsetY` values to be used later in the `move` function as we already commented about it.
Finally, what we do in the `remove` function is simply removing the previous attached event handler, that is, the `move` function to the on `mousemove` event.
If we look to the style what it is being painted here is like a ball, with `absolute` positioning.
So when we do mouse down on the ball (element) we execute the `add` function, adding the `move` function the `mousemove` event. When we release the button or do mouse up, we are removing this event handler.
This works and it's quite a simple implementation. Thank you.
As per request here it is a CodePen (without React):
{% codepen https://codepen.io/roggc/pen/eYYPrMb %}
Serverless: hidden costs, lock-in fears & security best practices
Tags: todayilearned, serverless, security
Published: 2019-11-14 11:00:17

*TL;DR style notes from articles I read today.*

### [The hidden costs of serverless](http://bit.ly/2ObB5sw)

- API Gateways tend to be a huge chunk of your serverless costs when you connect to a lot of APIs.
- The switch to serverless may not be worth it if data storage and networking are the largest chunks of your application’s costs.
- Two unknown costs of moving to serverless come in the shape of code maintenance and cold starts. 
- Assess the cost of extra code maintenance and the extra time spent switching to serverless.
- Look for the pricing advantages of serverless providers that suit you best. 
- Utilize the free tiers from vendors. Sometimes they will be enough for you to run smaller workloads.

*[Full post here](http://bit.ly/2ObB5sw), 6 mins read*

---

### [Mitigating serverless lock-in fears ](https://thght.works/2KhgHF6)

- Think lock-in cost = migration cost - opportunity gain from the migration. Maximize opportunity gain and minimize migration costs.
- To maximize opportunity gain, deploy existing tools such as serverless framework, apex, claudia.js & be as cloud-native as possible using the backend service provided by your cloud vendor.
- To minimize migration costs, choose a programming language that's supported by multiple vendors. Separate application domain from the platform and invest in a good architecture pattern. 
- Avoid integration tests heavily dependent on the cloud vendor and think of reusable abstractions instead.
- Use standardized technology such as HTTP and SQL. 


*[Full post here](https://thght.works/2KhgHF6), 6 mins read*

---

### [9 serverless security best practices](http://bit.ly/33KMW7f)

- Map your application - consider the data involved, its value and services that access it. 
- Keep using your WAF and API Gateway but apply perimeter security at the function level too.
- Secure application dependencies to prevent new vulnerable packages from being used.
- Look out for bad code that can trigger a self-inflicted denial-of-service attack from within your application.
- Add tests for service configuration to CI/CD & PROD.
- Make FaaS containers refresh to limit the lifetime of function instances.

*[Full post here](http://bit.ly/33KMW7f), 4 mins read*

---

*[Get these notes directly to your inbox every weekday by signing up for my newsletter, in.snippets(), here.](https://mailchi.mp/appsmith/insnippets?utm_source=devto&utm_medium=post08&utm_campaign=is)*
Favicon and Linq
Tags: todayilearned, csharp, linq, favicon
Published: 2019-11-14 09:01:46

I'm getting very partial to Linq. The encapsulation of logic at a declarative level is getting quite addictive.

I'll start off with the declaration of the `Favicon` object before I get to the code.
```csharp
    [Serializable()]
    public class Favicon
    {
        public string Rel { get; set; }
        public string Type { get; set; }
        public string Title { get; set; }
        public string Href { get; set; }
        public string Sizes { get; set; }
    }
```
Next the code.
```csharp
        private Favicon[] GetFavicons(HtmlNode document)
        {
            var favicons = new List<Favicon>();

            var rels = from link in 
            (from tag in document.Descendants("link") select tag) 
            where link.Attributes["rel"] != null && 
            link.Attributes["rel"].Value.Contains("icon") select link;

            foreach (var link in rels)
            {
                favicons.Add(new Favicon
                {
                    Href = link.Attributes["href"]?.Value,
                    Rel = link.Attributes["rel"]?.Value,
                    Title = link.Attributes["title"]?.Value,
                    Type = link.Attributes["type"]?.Value,
                    Sizes = link.Attributes["sizes"]?.Value
                });
            }

            return favicons.ToArray();
        }
```
The `HtmlNode` in this case is provided by [HtmlAgilityPack](https://html-agility-pack.net/). I haven't tried but I expect `XDocument` could work as it also has a `Descendants` method.

First of all we get all the `link` tags in the document. Then we pass that iterator up to another that finds all the links that are `rel` links with a value containing "icon" (so that one catches things like "icon", "shortcut icon" and "apple-touch-icon"). Then we iterate through the result set, create a new `Favicon` object and assign values to its members and then add the finished article to the List. (The `?.` notation is the null-conditional operator discussed at [Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators).)

Finally, we turn the List into an array and return. This data structure eventually ends up in a large XML file.

I could put the whole of the clause after the `rels =` into the head of the foreach, but it gets a bit hard to read at that point. In fact, I may go back to having the `from tag in document.Descendants("link") select tag` clause assigned to separate variable (as I had it earlier in the development cycle) again just for the sake of readability.
Tips to Be Successful in Life
Published: 2019-11-14 10:39:25

Success is not a milestone but a journey.

First of all, you have to set a goal according to your passion. Rest assured, when one enjoys work, then the probability of success increases dramatically. So, it is essential for you to explore your inside and find out your areas of core competence. Subsequently, pursue your passion by setting a goal and plan a course of action.

No two individuals are the same. Every person is different in character, traits, thinking, background and many more aspects. Therefore, there is no particular mantra for success. Every person has to define their path to success. However, there are some pieces of advice provided by great personalities that can help you in realizing your dreams.

Positive thinking and positive attitude are the two ends of the boat that sails you through the river full of hurdles. They not only helps you in achieving your goal but makes you a better person over and above all.
Also, it is vital never to let your professional goals ruin your personal life. Balance is must between both of them. The joy of success doubles sharing with loved ones.

Don’t let the fear of failure holds you back.  Don’t hold yourself back when you have an idea that is new to others. Always back yourself in taking calculated risks. Self-motivation is equally important to keep moving forward. Never forget to treat your spirit when you achieve something, no matter how small. Love your life, enjoy your actions and be kind to yourself.

Don’t lie on the ground when you fall, get up; it’s not about the first place always, crawl to cross the finish line.

Read More:<a href="https://happyrealization.com/how-to-become-successful-2/">HOW TO BECOME SUCCESSFUL?</a>
What future for docker?
Tags: docker, future, discuss
Published: 2019-11-14 10:13:18

After Docker enterprise part get acquired by Mirantis, Docker future is unclear. On the bright side, without enterprise bloat Docker might finally be able to concentrate on the core product and make Docker great(er) (again).

What feature do you want to see most in Docker? Or which issue  that they should work on now to get their glory back?
The reality of a developer's life
Tags: watercooler, jokes
Published: 2019-11-14 08:46:39

Today a colleague sent me a link to an awesome post called "The reality of a developer's life".

It is a really awesome collection of captions and GIFs to express common situations we all know as developers.

Have a look at it!

https://dzone.com/videos/reality-developers-life-gifs

I can relate to so many of them, but the most to **When I show my boss that I've fixed a bug**. 😅

![When I show my boss that I've fixed a bug](http://www.topito.com/wp-content/uploads/2013/01/code-07.gif)
<figcaption>When I show my boss that I've fixed a bug</figcaption>


Let me know which one you have the most!
My new site wants feedback ☕️
Tags: feedback, showdev
Published: 2019-11-14 08:45:07

<h4>Hello there, users!</h4>

Today I'd like to receive some <b>feedback</b> for my new personal site.

I'm well aware maybe you're <b>busy</b> right now, so I'll publish a few <b>screenshots</b>. However, I'd really appreciate if you can test the functionality of the site too.

My webpage: <a href="https://desiremcarmona.com/#/">Here</a>

I'm a self-taught designer&developer, so every feedback is **really** appreciated.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/kn4u81huqvlcbof23uya.png)
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ptgguv1cse3ysr7tn6n3.png)
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ofyolqmw8vsh9ad9jj75.png)

Thank you 🌹
Who explain me this Shell-Command? this.service does! ;)
Tags: linux, bash
Published: 2019-11-14 08:21:48


*This* pipes to *that*, doing *something* and leading back to *this & that*.

If you ever struggled with an huge shell-script-command and you'd whish to have somebody (or something) that explains this huge command to you... I have a hint for you:

[explainshell.com](https://explainshell.com/)

I've found this Page some minutes ago, and still love it!
As I've seen so many good hint's here on DEV.to, I'd like to share this one to you - hopefully it helps you a bit.
Binary Search - A Simple Code
Tags: beginners, javascript
Published: 2019-11-14 07:23:16

In my last post in this series, I wrote about Recursion.
 
Now, if you have just bumped into this post, it follows a series of posts I have been creating. I'm making this in adherence to the Feynman's Technique which is basically just to improve my comprehension level with an approach to teaching what I have learned.

So, I covered a brief intro on Binary Search and also touched on recursion which we will use in writing this algorithm.

We are going to write a function that takes in an array of numbers as its first argument and a key as its second. The function will search through the array using Binary Search and return true if the key exists or false if it doesn't. 

```javascript
function binarySearch(numArray, key){
   let middleIndex = Math.floor(numArray.index / 2)
   let middleElem = numArray[middleIndex]

   if(middleElm === key) return true;
   if(middleElm < key && numArray.length > 1){
      return binarySearch(numArray.splice(middleIndex, numArray.length), key)
   } else if {
      return binarySearch(numArray.splice(0, middleIndex), key)
   } else return false 
}
```

So, in this piece of code, we define two variables ``middleIndex`` to store the middle Index of the array and ``middleElem`` to store the middle element of the array. Simple?

Next, we go ahead and write out the base case which checks if the middle element is the same as our key and returns true ending our function since we have already located it.

We again write another "if" statement for our recursion which checks if the middle number is less than the key and also if the numbers array is greater than one. If the key is greater than the middle number, we splice the array and remain with the section above the middle number.

The splice function takes in two arguments, the index from the point you want to start slicing the array and the index where you want to end. it returns the sliced part.

Then we call the function recursively to repeat this process until the base case is reached hence completing our function.
Simple tricks that can speed up your development cycle
Tags: productivity, linux, todayilearned
Published: 2019-11-14 07:03:38

---
title: Simple tricks that can speed up your development cycle
published: true
description: Get development feedback quickly
tags: productivity,linux,todayilearned
---

I recently watched Bret Victor's video - Inventing on Principle. That is so inspired. The demos are awesome in their own right. He talked about his principle: **Creators need an immediate connection to what they create.**
{% youtube PUv66718DII %}

Inspired by that, I start thinking about how to speed up my development feedback. Here is a little trick that I think is useful to me.

## Introduce two core tools

[ag](https://github.com/ggreer/the_silver_searcher): The Silver Searcher. Like ack, but faster.
[entr](http://eradman.com/entrproject/): Run arbitrary commands when files change.

## Save code, See the result

### Web sample

When any html/css/js files change, the current chrome page will refresh.

```zsh
ag -l --html --css --js | entr ./reload-browser.sh chrome
```
You can download `reload-browser.sh` from [here](https://gist.github.com/daoleno/4e155bb65c433d490b3a70e5a96377c0).


![autohtml](https://thepracticaldev.s3.amazonaws.com/i/pb1w8lgt01mg2xnogi6w.gif)

### Golang sample

When any go files change, my custom run script will be executed. I can build, start, run tests on my project automatically.

```zsh
ag -l --go | entr -c -r ./run.sh
```

![autogo](https://thepracticaldev.s3.amazonaws.com/i/2xt0nldtt6c02wqsfpb6.gif)
Stream 11/13/19 - npx is pretty cool
Tags: todayilearned, journal
Published: 2019-11-14 06:52:45

### Check Out the Stream @ [https://twitch.tv/talk2megooseman](https://twitch.tv/talk2megooseman)

# Today Objective

✅ Work on a fork of {% github https://github.com/talk2MeGooseman/firestore-backup-restore %} to experiment adding `npx` support to it

# Notes

### NPX

During off stream time I was looking for a good way to export Firestore data that I have for a couple of my extension s so that I can import into any other DB service of my choice. 

Unfortunately Firebase does not offer a clean export tool, instead, you can only export to their propriety format. BUT I ended finding an NPM package that someone wrote to export data to JSON: [firestore-export-import](https://npmjs.com/package/firestore-export-import)

I was lazy and didn't want to spend time integrating this package into any project I have. So instead I got the crazy idea, "What if I made this npx compatible?" And here we are now. 

So I forked the repo and start laying the groundwork for creating `npx` compatible version of this package.

I got alot of my inspiration of how to do this from the cowsay package: 
{% github https://github.com/piuccio/cowsay %}

After completing the work and getting the MVP done for import and export, next came refactor phase. One thing that I realized needed a refactoring was the usage of [optimist](https://www.npmjs.com/package/optimist)

It has been deprecated for a long time so I wanted to look for a better alternative. Luckily ABuffSeagull came flying in and recommended [commander](https://www.npmjs.com/package/commander)

The end result is the it worked out great and I feel like the command and options structure feels a lot better.

# Shoutouts and Thanks

ABuffSeagull
- Thanks for recommending commander.js and an alternative to optimist cli package
[commander](https://www.npmjs.com/package/commander)

Kodder
- 2 month resub!

Booperinos
- Thanks for the 18 months of sub love!

# Future action items

⬜ Wrap up doing a pull request for firestore-backup-restore. But its a done MVP <3

{% github https://github.com/talk2MeGooseman/firestore-backup-restore %}
YSPKA #3: Dapr
Tags: yspka, microservices, dotnet
Published: 2019-11-14 06:25:57

[Dapr](https://dapr.io/) (Not to be confused with [Dapper](https://stackexchange.github.io/Dapper/)) is, in my humble opinion, one of the coolest thing Microsoft has released in many years. 

Dapr is something of a Lego for building micro services. There is state management, pub/sub functionality and much more that you need for building micro services. Using Dapr you can focus on your business logic. Dapr can be used in a side car architecture, i.e you run Dapr side-by-side with your application without adding any dependencies to your application. Dapr can use gRPC (that was yesterdays topic) to communicate with.

Go check out the [samples](https://github.com/dapr/samples), the Distributed Calculator is awesome!
The Classic TicTacToe Game in Python
Tags: python, showdev, tutorial, codenewbie
Published: 2019-11-14 05:52:24

So, the best and the most fun way to learn any programming language for me has always been by developing a fun project like a simple game or some project that I would use in my daily life.

So, when I started to learn Python, I started with this No Starch Press published book [“Automate The Boring Stuff With Python”](https://amzn.to/2piGghV) which is just awesome and If you are looking for a book to get started learning python, I would recommend you to go through this book. Its very beginner-friendly and it covers almost all the basic topics of python. So, while solving the exercises in this book, I came across this TicTacToe game implementation in python.

{%gist https://gist.github.com/jamesshah/269b59a9fc2e1fc9b1a83aa75c545006 %}

And Now Play Time:

![TicTacToe](https://thepracticaldev.s3.amazonaws.com/i/b07443ltj0m8eqv8jwoy.png)


Checkout the Full code explanation here.
{%medium https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874 %}
Introducing Code Review, a weekly coding challenge series!
Tags: career, challenge, codenewbie
Published: 2019-11-14 05:36:06

Hey everyone! My name is Elisabeth Gross and I have the privilege of working on the [Coderbyte](https://coderbyte.com/) platform alongside a talented and passionate team. We're working hard to enable 300,000+ developers to improve their skills and land their dream jobs. 

We're launching a brand new series of free articles and challenges exclusively for the Dev.to community. It's called **Code Review** and I'm super excited to be leading the initiative.

##Introducing: Code Review 🤓

Each week (beginning next week) we'll release one coding challenge on Dev.to that will be completely free for the community. The awesome part is that we won't just be posting the challenge – we'll also include real stats and insights from thousands of results in our database so you can see common mistakes, average scores, and average time to complete.

I'll be in the comments section each week discussing the inspiration for the challenge, key concepts, and giving out special rewards to the most clever solutions. We'll begin next week, but in the meantime, here's a bit more about me and my coding journey.

##Introducing: Me 👋

I’ve been a software developer for about 3 years. I majored in Biology in college thinking I wanted to be a doctor, but by the time graduation came around, I just wasn’t ready to sign myself up for another 4 years of school, plus a residency and a huge amount of debt. I began working with a friend, [Nis Frome](https://www.linkedin.com/in/nisfrome/), at his company, Alpha, writing content and learning about startup culture and the tech world. Very quickly, I started hanging out with the developers and fell in love with the creative problem solving they were doing in their everyday work. I began to teach myself bits and pieces and eventually attended the Grace Hopper Program at Fullstack Academy in NYC. 

I have had a couple full stack developer roles over the years and currently work as a senior software engineer for Moz, a mid-sized SaaS company based in Seattle. I love being an engineer and am passionate about teaching and mentoring to help get more talented people into this great field!

##Introducing: Our newsletter 📫
We’re going to be sending out a small, feature reveal snippet every time we release something big, so our community is the first to know when we break out something new. [Give us your email here] (https://coderbyte.typeform.com/to/fb7Yk8) and we'll add you to our "first to know" list :)