teleren/devto huggingface dataset:
How to add data-* attributes to your component library and benefit from them in your E2E tests
Tags: react, javascript, styledcomponents, testing
Published: 2019-09-19 11:13:43

## Intro

When building a component library, one of the most important things is a seamless and clean documentation of the available properties of a component.

Users of your component library should not be able to write random properties on components which are not used by it. Otherwise an error like `Warning: React does not recognize the 'isVisible' prop on a DOM element. [...] If you accidentally passed it from a parent component, remove it from the DOM element.` can be thrown quickly.


## The data-* and why we sometimes need it

There are use cases in which users need to have the ability to pass some kind of random properties on the components.

For me, such a use case was adding selector attributes for End-2-End tests like `data-test-element="header"` to the libraries components in my project.
(BTW: I love to write my E2E tests with [cypress](https://www.cypress.io/).)


## Solution

A small and simple function which takes your property object and returns just valid properties that should appear in the rendered markup.

```javascript
const validateProps = (props) => {
  const newProps = {}

  Object.keys(props).forEach((key) => {
    if (key.startsWith('data-') || key === 'className') newProps[key] = props[key]
  })

  return newProps
}

```

**Usage**

In your components you can extract the properties which are used by it self. All other properties are passed through `validateProps()`.

```javascript
const Badge = ({ onToggle, isActive, children, ...props }) => (
  <Wrapper
    isActive={isActive}
    onClick={onToggle}
    {...validateProps(props)}
  >
    {children}
  </Wrapper>
)
```


*??? className ???*

Maybe you wonder why `validateProps()` keeps the `className` property? That's because I work with [styled-components](https://www.styled-components.com). If you add some custom styling from outside to a component you will have to write this property on the component (see [styled-component docs](https://www.styled-components.com/docs/advanced#existing-css))


## Prod vs. Dev

Depending on how and where you run your tests, you maybe don't want to see those `data-test-*` attributes in your markup in production.

In this case I recommend [babel-plugin-react-remove-properties](https://github.com/oliviertassinari/babel-plugin-react-remove-properties).


**Usage**

Filter all `data-test-element` properties only in production with the following config in the `.babelrc` of your project.

```json
{
  "env": {
    "production": {
      "plugins": [
        [
          "react-remove-properties", {
            "properties": [
              "data-test-element"
            ]
          }
        ]
      ]
    },
  }
}

```
Onboarding.design - Looking for beta testers
Tags: ux, design, uiweekly, help
Published: 2019-09-19 11:13:03

# __Looking for beta testers__

__Hey community__,
I created [OnboardingUiKit](onboarding.design) which has all essential UI components such as modal, tooltips, hotspots, banners which required to create onboarding flow.

The idea came from the frustration of creating onboarding flow in onboarding tour providers platform. we have to go through the process of selecting elements, installing extensions and whatnot. And I wanted UI kit with a set of components which I can use to create onBoarding flow on my Figma/Sketch design and see what it looks like before I move to code and implementation part.

Current UI components:
 1.Hotspots
 2.Tooltips
 3.Banner
 4.Alerts
 5.Launcher
 6.Checklists
 7.Feedback Forms
 8.Tour components (Paginations, cards, buttons)

I have made components for 2 onboarding providers as of now which are __intercom__ and __appcues__.

### __Looking For Beta Testers__

Currently, I am looking for beta testers to try out [onboarding.design](https://onboarding.design) and provide feedback.

If you think this service could help you or your company/organization, and you want to try out beta while I refine offerings then please head over to [onboarding.design](https://onboarding.design) and register for beta invites.


The onboarding UI kit is free and always will be :)

Please reach out to me via comment if you need more info, happy to talk.
How to Test Your Fetch API Requests with Cypress
Published: 2019-09-19 10:38:04

Cypress [is awesome](https://dev.to/noriste/front-end-productivity-boost-cypress-as-your-main-development-browser-5cdk). With Cypress you can do everything, including simulating your back end by stubbing requests, or getting freshly brewed coffee to your bed as you wake up every morning <sup>[1](#note-1)</sup>.

Unfortunately, Cypress does not currently support intercepting requests made with the more modern *[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)*, but only with the not-so-good old *XMLHttpRequest*.

From [their own docs](https://docs.cypress.io/guides/guides/network-requests.html#Testing-Strategies):

> Please be aware that Cypress only currently supports intercepting XMLHttpRequests. Requests using the Fetch API and other types of network requests like page loads and `<script>` tags will not be intercepted or visible in the Command Log. See [#95](https://github.com/cypress-io/cypress/issues/95) for more details and temporary workarounds.

Luckily there is a very simple yet very effective workaround: include a `fetch` polyfill, then delete `window.fetch` to make sure the browser falls back to *XMLHttpRequest*.

Here is the easy 3-step process:

1. Install the `fetch` polyfill package in your project, if you haven't already  
   
    ```
    $ npm install whatwg-fetch --save
    ~or~  
    $ yarn add whatwg-fetch
    ```

2. Import it in your project (you'll probably do it in your `index.js` file)

    ```js
    /* file: src/index.js */

    import 'whatwg-fetch';
    ```

3. Instruct Cypress to delete `window.fetch` before every window load

    ```js
    /* file: cypress/support/index.js */

    // Delete window.fetch on every window load
    Cypress.on('window:before:load', win => {
      delete win.fetch;
    });
    ```

That's all, happy stubbing 🚀

---

<small>NOTES  
**1** - <a name="note-1"></a> Not yet confirmed</small>
Activity ShortCut is not create in Vivo devices
Tags: android, java, shortcut, vivodevices
Published: 2019-09-19 10:02:36

I want to create the Activity shortcut at home screen , so user can open the activity screen directly .

I have used this code

if(ShortcutManagerCompat.isRequestPinShortcutSupported
    (getApplicationContext()))
    {


        ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(getApplicationContext(), id)
         .setIntent(new Intent(getApplicationContext(), 
           TranslateActivity.class).setAction(Intent.ACTION_MAIN))
         .setShortLabel(label)
         .setIcon(icon)
         .build();
         return 
  ShortcutManagerCompat.requestPinShortcut(getApplicationContext(), 
  shortcut, startHomeScreen());
}

     else
         {
        // Shortcut is not supported by your launcher

        Intent shortcutIntent = new Intent(getApplicationContext(), TranslateActivity.class);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Intent addIntent = new Intent();
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher));
        addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        getApplicationContext().sendBroadcast(addIntent);
    }
How to Save an Android Activity State Using Save Instance State?
Tags: android
Published: 2019-09-19 09:47:56


Saving and restoring an activity UI state is an important part of user experience. In such cases, the client expects the UI state to continue as before, however, the framework demolishes the action and any state present in it. You may have seen during testing that screen-rotation resets all information gathered from the client. Same is the case when a user presses the back button by mistake. Screen rotation is one of the numerous life-cycle changes in Android that can destroy and reset the Activity and cause all information to be lost. Definitely not an extraordinary user experience!
 
In order to Save and Restore UI state, I override two most common methods for this purpose:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/e53c4qng9ystfjk8jlml.gif)

<h2>onSaveInstanceState():</h2>

In order to save sates of UI, I override onSaveInstanceState(Bundle savedInstanceState) and save all the data of the UI in savedInstanceState Bundle.



<b>This method is called before onStop() in older versions of Android (till android 8.0) and can be called after onStop() for newer versions.</b>

 
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("StringKeyForBoolean", false);
  savedInstanceState.putDouble("StringKeyForDouble", 3.4);
  savedInstanceState.putInt("StringKeyForInteger", 5);
  savedInstanceState.putString("StringKey", "Folio3/blog");
  // etc.
}

The Bundle is essentially a way of storing an NVP ("Name-Value Pair") map, and it will get passed into onRestoreInstanceState() where you would then extract the values like this:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/o2lmdux3ts6c4laekwc1.gif)

<b>This method is called after onStart().</b>

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Restore UI state using savedInstanceState.
  
  Var1 = savedInstanceState.getBoolean("StringKeyForBoolean", false);
  Var2 = savedInstanceState.getDouble("StringKeyForDouble");
  Var3 = savedInstanceState.getInt("StringKeyForInteger");
  Var4 = savedInstanceState.getString("StringKey");
  
}

Using this way you can save all the states and other data variables that could be lost on screen rotation or when the current activity goes into the background. Saving and restoring states of UI is a good practice in <A href=https://www.folio3.com/mobile/android-app-development/>android app development</a>.
Note: When an activity is created for the first time there will be no data in the save instance state bundle. 

Check out <a href=https://www.folio3.com/mobile/blog/how-to-launch-an-app-the-right-way/>this guide</a> if you are planning to launch an app.
What is your story with software development? 🐱‍💻
Tags: webdev, angular
Published: 2019-09-19 09:31:02

---
title: What is your story with software development? 🐱‍💻
published: true
description: 
tags: webdev, angular
---
**What is your story with software development?
When did you start? How did you learn?**
I would love to hear about your journey 😃

When it comes to me, it all started back in early 2000 😱
My parents bought a computer and I was hooked on day 1!
I just couldn't stop my passion! I started with creating simple HTML pages before I discovered Turbo Pascal and Delphi! Then I got into "serious" programming (how serious programming maybe if you are 14 years old 🤣) You can see me on the photo below. Then after a couple of years (many years actually, I am 28 now), I went to a university to get my Master Degree in Computer Science.

After another couple of years of working in the IT industry, I had a privilege to speak at the top international conferences all over the World (like JSConf, AngularUP or NgColombia). How unexpected life could be 😉. Now, I am running Angular-Academy.com, to share knowledge even at a much higher scale, which makes me really thrilled. We have people from all continents in the Academy!

Now, it's your turn. What is your software development story? I would love to hear your voice 🤗

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/fwovm8wdyh86nluanzb7.jpg)
What do you regret?
Tags: discuss, career, watercooler
Published: 2019-09-19 09:28:44

---
title: What do you regret?
published: true
description: What do you regret now for the first year/years of starting in your career?
tags: discuss, career, beginners, watercooler
---

What do you regret now from the first year/years of starting in your career?

I truly deeply regret believing small people that wanted to make me doubt myself and not search for other options, better ones, ranging from how to learn, how important is to share knowledge with peers and strangers, how to respect myself and others and demand that in return and how to write code. Literally, it was bad but aggressively told it's how things should be done.

How about you? No names, or details, just a bit of lashing out so that other new beginners can learn from this. Thank you! You are awesome!
My solution to Code challenge #77
Tags: go, showdev, challenge
Published: 2019-09-19 08:27:20

Implemented in golang, quite easy to be fair :smile:

```go
func GetNthFib(n int) int {
	if n == 1 {
		return 0
	}
	if n == 2 {
		return 1
	}
	x, y := 0, 1
	for i := 2; i < n; i++ {
		x, y = y, x+y
	}
	return y
}
```

## Explanation

So we check for the first two value as this two are required to be able to build the rest of the sequence.

Once we know it is not 0 (x) or 1 (y), we know that the correct result comes from adding the x+y and moving the values 1 place forward.

The loop starts at 2 because otherwise the results will be offset by 2 iterations (we already check the first two statically).

For example, if the loop starts at 0 and they ask for nth 3, then our result will be 3 which is incorrect as the third position on Fibonacci's sequence is 1.

You can play around with it by using this [Golang Playground link](https://play.golang.org/p/yNUdwd07SvF)
My manager made a quite stupid mistake
Tags: watercooler
Published: 2019-09-19 07:46:46

And I'm upset about it.

Long story short: I'm a consultant and my company is looking to get me on a great mission but the client asked for a specific price limit and my manager just told me he mistakenly made them an offer that is just above that limit...

The price limit was a pretty obvious and well stated requirement and he still missed it and that could make the client refuse the offer and I'd miss a great opportunity.

I'm pretty pissed off. I've yet to see how this pans out but still...

That's all, I just needed to get that off my chest, sorry for the whining.
Will you sacrifice minimalist UI for features?
Tags: ux, discuss
Published: 2019-09-19 07:10:09

There are a lot of apps that claim to have great features _and_ minimalist UI as well. But from my past experiences, this is very difficult to achieve. Either you have to sacrifice your minimalist UI to add more features or you have to cut back the features to keep a clean UI. 

Why am I having this concern? Recently I'm using a productivity app that helps me track tasks and manage my work. I really like the app but they're adding many features to make the platform better and I worry if it might destroy the simple and clean UI. 

![Quire](https://thepracticaldev.s3.amazonaws.com/i/0c1pflufiaa6l3jrutum.png)

*Image source: [Quire](https://quire.io)*
[Git] delete the [Local | Remote] merged branch
Tags: git
Published: 2019-09-19 06:57:36

---
title: [Git] delete the [Local | Remote] merged branch
tags: git
published: true
---


## 🔗 Parent Note
{% link n350071/my-git-note-5259 %}


## Delete Local Branch
## 👍 Usual way
`git branch --merged` lists branch that is merged into the current branch.
so, this deletes merged branches.

```sh
git branch --merged | grep -v master | xargs git branch -d
```

## 🦄 Delete Squashed Merged Branch
Only 3 steps.

```sh
# show local branches
$ git branch
  * master
    branch1
    branch2
    branch3

# grep them
$ git log | grep 'branch1\|branch2\|branch3'
   Merge branch 'branch2' into 'master'

# force delete it
$ git branch -D branch2
```


## 👍 Delete Remote Branch

```sh
# delete remote branches with some conditions
git branch --remote | grep -v "upstream" | egrep -v "origin/master|origin/deployment" | xargs git branch -dr
```
8 Comprehensive Programming Languages that a Data Scientist Should Master
Tags: python, sql, database, datascientist
Published: 2019-09-19 06:15:55

The data scientist is a trending profile and the demand seems like increasing. For the development of every business, there is a requirement to assess the data you gather. Being a data science is not a piece of cake. It is important for the candidate to understand the core elements of this job profile. From knowing a number of languages to distinguish the type of Data, you need to know everything about data science. Python, R, Machine Learning, Julia, Scala, Matlab, and many more languages should be in your bucket list if you want to become a data scientist. 
read more:- http://bit.ly/2kHlAhc
#KyberDeFi Virtual Ethereum Hackathon ($42,000 in prizes)
Tags: blockchain, hacktoberfest, eventsinyourcity
Published: 2019-09-19 05:07:48

Kyber Network is running an online Ethereum blockchain hackathon with some of the best names in the space. If you're looking to develop on blockchain tech and learn about crypto, this is a good place to start!

KyberDeFi Virtual Ethereum Hackathon:
Build the future of Ethereum decentralized finance with Kyber, bZx, Chainlink, Compound, Melon, Synthetix, WBTC, & other ecosystem builders.

Over $42,000 USD in prizes to be won
Submission Period: 9 Sep-21 October

Details: https://bit.ly/2m82RvL
Register: https://kyber.devpost.com/
Join hackathon discord: https://discordapp.com/invite/nuWr2KF
Launch video: https://youtu.be/KTYjdtvD9FM/

:)
Simply Auth Social 
Tags: javascript, node, mongodb
Published: 2019-09-19 04:28:24

Part 2 of Simply Auth a plug 'n' play solution for local authentication. Done with MongoDB, Node.js, Express.js and Passport.js. 

Up and running on [here](https://simplyauthsocial.herokuapp.com/)

Bit of a headache to do since Twitter requires you to write to them and explain why you need extra permissions to obtain a user's email address. Google oauth documentation seems to be all over the place.
Do Good Daily Day 7
Tags: swift, swiftui, ios
Published: 2019-09-19 03:56:56

📅 09/18/2019
🔥 7 day streak
📱 Do Good Daily
💰 $0.99 price
🤑 0 sales
⌚️ 6 hours spent
💻 7 files changed 42 additions(+) 2 deletions(-)
🙅‍♀️ Today's goal: Get the text editor working

## SwiftUI TextField placeholder

Look, I'm not going to sit here and wax poetic about my 30 minutes of side project work today, I'll just go ahead and say, I didn't do what I set out to do. Having a full time job and a family is hard effin work.

Let's talk about textfields and placeholders, the only thing I did today:

![screenshot of a swiftUI preview that shows in vertical order, today's day and then a picture of a sun, and text saying "What good shall I do this day?"](https://thepracticaldev.s3.amazonaws.com/i/j5v5pqk7xzg005png3ri.png)

```swift
TextField("My good for today", text: self.$input)
    .font(.custom(font, size: 18))
    .padding()
```

and that's it! Oh wait, I also figured out how to format today's date:

```swift
let fmt = DateFormatter()
fmt.dateFormat = "EEEE, MMMM dd"
self.date = fmt.string(from: Date())
```

and THAT's it!
request.files['file'] is returning string instead of filestorage obj
Published: 2019-09-19 03:42:12

**request.files['file'] is returning filestorage object when run locally but when deployed on AWS using serverless it returns a string of the contents inside the .txt file. Which is resulting in the error "String object does not have attribute save" or "String obj as no attribute filename" when I'm trying to do f.save(f.filename). Please help.**

**PS : ignore the indentation in the below code. I copy pasted it in parts.**


def create_aws_event(flask_request: request, path_data: Dict, resource: str) -> Dict:
    # build our path data
    path_parameters = {}
    for p in path_data:
        path_parameters[p] = path_data[p]
    # build our query strings for the event
    query_string_parameters = {}
    # noinspection PyUnresolvedReferences
    for q in flask_request.args:
        # noinspection PyUnresolvedReferences
        query_string_parameters[q] = flask_request.args.get(q)

return {
        "resource": resource,
        "path": flask_request.path,
        "httpMethod": flask_request.method,
        "headers": {},
        "multiValueHeaders": {},
        "queryStringParameters": query_string_parameters,
        "multiValueQueryStringParameters": {},
        "pathParameters": path_parameters,
        "stageVariables": {},
        "requestContext": {},
        "body": flask_request.files,
        "isBase64Encoded": False
    }

@app.route('/uploader', methods=['GET', 'POST'])
def upload_file():
    event = create_aws_event(flask_request=request, path_data={}, resource='/uploader')
    print('EVENT:', event)
    print(event['body'])
    result = aws_doc_upload.lambda_handler(event=event, context=Context)
    return Response(result['body'], status=result['statusCode'], content_type='application/json')



**In lambda_handler :**

    elif resource == '/uploader' and method == 'POST':
        
        test = event['body']
        print("FILE: ", test)
        test.save(test.filename)
Exemplary real world application built with react-mobx-cli (Mobx 5)
Tags: react, mobx
Published: 2019-09-19 02:24:23

# How to build your app with Mobx and React quickly ?

If you are in the React world there are some pretty high chances you may have heard about Mobx. Mobx is a lightweight and easy to learn state management library.

Besides mobx we will also add mobx-react that we will use to glue together mobx and react.


## Installing react-mobx-cli

```sh
git clone https://github.com/tuantvk/react-mobx-cli.git

cd react-mobx-cli

npm install

npm start
```

Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser.

View [repo Github](https://github.com/tuantvk/react-mobx-cli.git)
⏳ Is Future Proofing just Overengineering? 🤹
Tags: discuss
Published: 2019-09-18 22:07:30

In the UK there is a TV show called 'Bits and Bob', it's a show teaching children about engineering through story telling. In one particular episode Bits and her friends attempt to find a rare flower in the desert 🏜️. They enlisted a Jeep to get from A - B, simple premise so far right?

During this episode the gang decide to pimp this ride with a slide, a set of wings and some fluffy dice. Despite the amazing looking contraption, the slide and wings fall off, not because a slide or wings aren't useful, but out of context well every mod goes down the proverbial, in the end they get there with the original Jeep.

Talking to my junior self would have been frustrating, because like the story, I had a insatiable desire to pimp my code, that has bit me in the past. So I'd say, "it's future proofing". My code does more than it's supposed to "because I go the extra mile... ". At home on my own projects, I will still go wild, but today I went through an old unfished project and just started deleting stuff, and lo and behold nobody would stop me adding that back in in the future, when it's needed, I think that's the line, future proofing is not a thing, develop for the now.

What do you think, can you relate?

Ps, I write everything on my phone so grammer should be forgiven and forgotten, I blame my thumbs.
Rust Programming for IOT (Internet of Things)
Tags: rust, tutorial, beginners
Published: 2019-09-19 01:53:31

Is Rust ready for the embedded world yet? If your IOT project is on ARM or MSP430, it already has native support in the Rust compiler, and AVR and RISC-V have compiler forks available. But architecture support is only the first challenge: If you're used to writing Rust for hosts that run an operating system, the paradigm shift of having to do everything yourself in the embedded world can be jarring. This talk will introduce the basic techniques for writing Rust to run Microcontrollers, and survey outstanding embedded rust projects already available in the ecosystem. 

{% youtube ro-G5gu5fMk %}