teleren/devto huggingface dataset:
Test for 'element exists?'- React testing library
Tags: react, testing, unittest
Published: 2020-02-19 14:50:56

Problem: 

A react component is to being unit tested. The presence of an element after render is to be checked. In the following example, button with premium features is rendered conditionally.

Example:

```
const UserProfile: React.FC = user => {
  return (
    <div>
      <span>Hello {user.name}</span>
      {user.isPremiumUser && <button data-testid="premiumFeatures">Show premium features</button>}
    </div>
  );
};

```
 

###Test cases:

###1. Check for presence

```
import { render } from '@testing-library/react';

const { getByTestId } = render(
         <UserProfile user={{ name: 'Sheldon', isPremiumUser: false }} />
      );

expect(getByTestId('premiumFeatures')).toBeTruthy(); //passes

```

###2. Check for absence 

When we use `getByTestId` to find an element and if it doesn't exist, `getByTestId` yells out an error which cannot be used to assert the absence.

```
import { render } from '@testing-library/react';

const { getByTestId } = render(
         <UserProfile user={{ name: 'Sheldon', isPremiumUser:false }} />
      );

expect(getByTestId('premiumFeatures')).toBeFalsy(); //fails with unable find element with testid msg

```

So, what can be used here is `queryByTestId`.

```
import { render } from '@testing-library/react';

const { queryByTestId } = render(
         <UserProfile user={{ name: 'Sheldon', isPremiumUser: false }} />
      );

expect(queryByTestId('premiumFeatures')).toBeFalsy(); //passes

```
Select an Element with document.querySelector
Tags: javascript, dom, tutorial, browser
Published: 2020-02-19 14:27:16

---
title: Select an Element with document.querySelector
published: true
description: querySelector is a flexible tool to query the DOM.
tags: javascript, dom, tutorial, browser
series: Get Started with JavaScript in the DOM
---

If you would prefer to watch this post, you can do so with this [community resource lesson on egghead.io](https://egghead.io/lessons/javascript-select-an-html-element-with-document-queryselector?pl=introduction-to-client-side-web-apis-72d0&af=ay44db).

You may not always want to select the first child of an element. document.querySelector will match elements based on a pattern you give it. Say we have a page that looks like this:

```html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Select an Element with document.querySelector</title>
  </head>
  <body>
    <ul>
      <li>Peanut Butter Falcon</li>
      <li>Knives Out</li>
    </ul>
  </body>
</html>
```

Instead of accessing the first `li` element with `firstElementChild` you can use `document.querySelector('li')`.

If you guessed `<li>Peanut Butter Falcon</li>` you were right. Don't feel bad if you got it wrong though, you weren't supposed to know the answer!

How do we get the element with the inner text of 'Knives out' with `document.querySelector` though?

Right now we can't. We need to assign id's to the elements like this:

```html
<ul>
  <li id="movie-1">Peanut Butter Falcon</li>
  <li id="movie-2">Knives Out</li>
</ul>
```

Now we can call `document.querySelector('#movie-2')` to get our `<li id="movie-2">Knives Out</li>` element. The `#` is how we tell `querySelector` we are looking for an id on an element.

Note that this id should be unique in this DOM tree. You never want to give two elements the same id. This will cause some frustrating bugs!

What are some ways you've used `querySelector`?
5 reasons why I built a CSS framework (and what I've learned)
Tags: css, sass, html, design
Published: 2020-02-19 14:08:45

Bootstrap, Foundation, Bulma, Tailwind, PureCSS, Materialize, and so forth: the idea of **building your own CSS framework** might sound like pure madness with so many ready-made CSS libraries out there.


But there might be some valid reasons that lead to taking up such a challenge. In this article, I will try to list the ones that convinced me to build a custom CSS framework for our [**Cruip templates**](https://cruip.com/).

##1. I wanted a tailor-made suit

First and very debatable point! *Productivity* is what all of us should always keep the focus on, and that means *to make things work with less time and effort*. So why should I want to waste time just to reinvent the wheel? 

Well, I think it depends on what you are working on. If you need to go fast, building a custom framework it's not a good move. In our case we wanted a solid, scalable and easy to maintain scaffold, and here's why we thought that doing everything from scratch was a more appropriate choice.

##2. I needed a custom but reusable structure

During the prototyping stage of Cruip, [we](https://cruip.com/about-us/) defined some fundamental principles:
- We didn't want fluid, percent-based layouts
- We didn't need grids yet
- We wanted to define the white-space in multiples of 4
- We wanted to adopt pixel only as measure unit
- I needed a settings file to store custom variables for our sections and components
- I needed Sass mixins and functions from my Swiss Army knife 

Way too many needs for adopting a CSS framework. That's why we decided to build our own system.

##3. I didn't want to end up with plethoric code

Generally speaking, **I don't like to have things that I don't need around me**. That applies to both life and job.

Every CSS library provides you much more than you need, and I prefer to spend my time writing new code rather than wasting time to remove unused code.

##4. I wanted to save time in the long run

I've just said that building a CSS framework is time-consuming, but it's a **one-time job**.

I spent almost 3 months writing, testing, and fixing the base CSS for Cruip. What we get now is a solid skeleton that we can re-use anytime we need to build a landing page. Also, I can re-cycle my work for any of my future projects, aside from improving or extending it accordingly with the needs of the moment.

Not of secondary importance: it's *my creature*, and I can feel much more comfortable with it rather than with code written, maintained and updated by anyone else.


##5. I wanted to challenge myself

Coding a CSS framework from scratch can be an exciting experience. You will test your skills at 360 degrees and it will force you to view things from a larger perspective. Definitely an experience that I would recommend!
[No Code] How To Create Personalized Content for Logged In Members with Webflow and Memberstack
Tags: showdev, nocode, visualdevelopment
Published: 2020-02-19 13:05:34

Just finished creating a 30 minute step-by-step screencast walking through how to setup a Webflow site, with MemberStack allowing logged in members to personalize their dashboards content.

1. Visitor signs up and becomes a member
1. New member selects some screening options
1. Based on selections member is shown relevant, personalized articles


* Full control of your sites design in Webflow.
* Using the Webflow CMS to store your member accounts.
* Using MemberStack to provide members only access.
* Personalized content through member settings.

To accomplish this I use:

* Zapier
* Webflow
* MemberStack

Here's the video:

{% youtube JXJg_d7BuI4 %}

If you prefer, there is a downloadable 255 page PDF Guide with 495 screenshots to walk through this setup at your own pace at:

https://nocodequest.com/personalization-with-unique-member-dashboards/
Daily Developer Jokes - Wednesday, Feb 19, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-02-19 13:00:05

---
title: "Daily Developer Jokes - Wednesday, Feb 19, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Wednesday%2C%20Feb%2019%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e12597d4e1c1.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ What accommodations did the JavaScript developer request at the hotel?

___A:___ A room with a Vue.
 -->
Dicts are now ordered
Tags: python, beginners
Published: 2020-02-19 12:58:35

In <a href="https://python.org">Python</a>, a <a href="https://pythonbasics.org/dictionary/">dictionary</a> is Pythons version of a map (associative array or hash table). It lets you map keys to values. This makes it easy to request a value given a key.

A hash table contains both keys and values, but they are in a pseudo random order. This is different from a list (array), that only contains elements.

![array vs map](https://dev-to-uploads.s3.amazonaws.com/i/ape4n1prp6eyore5bgia.png)

*the good news: a dict in Python is now in insertion order*

## Dicts are ordered (for newest Python version)

In the newest version of Python, a dictionary is now in insertion order. That has not always been the case.

```python
➜  ~ python3.7
Python 3.7.5 (default, Nov 20 2019, 09:21:52) 
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> d = {'one': True, 'two': True, 'three': True, 'four': True, 'five': True}
>>> d['two']
True
>>> d['four']
True
>>> d
{'one': True, 'two': True, 'three': True, 'four': True, 'five': True}
>>> 
```

If you used an older version of Python, there was no guarantee that the dictionary is in order.

For example, in the older version of Python (2.x)

```python
~ python2
Python 2.7.17 (default, Nov  7 2019, 10:07:09) 
[GCC 9.2.1 20191008] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'one': True, 'two': True, 'three': True, 'four': True, 'five': True}
>>> d
{'four': True, 'three': True, 'five': True, 'two': True, 'one': True}
>>>
```

Quoting the docs referenced above:

    Changed in version 3.7: Dictionary order is guaranteed to be insertion 
    order. This behavior was an implementation detail of CPython from 3.6.

**Related links:**
* <a href="https://pythonprogramminglanguage.com/dictionary/">Dictionaries in Python</a>
* <a href="https://gumroad.com/l/dcsp">Python programming course</a>
Don’t waste your time learning everything
Tags: learning, beginners
Published: 2020-02-19 12:43:14

---
title: Don’t waste your time learning everything
published: true
tags: 
canonical_url: https://waylonwalker.com/blog/don-t-waste-your-time-learning-everything/
tags: learning, beginners, discuss
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/nawhyju15yykg9pnc34r.png
---

> # "Don’t waste your time learning everything."

![](https://waylonwalker.com/dont-waste-your-time-learning-everythign-post.png)

> Inspired by this [linkedIn post](https://www.linkedin.com/posts/activity-6633818327070326784--Ksl)

I felt that this comment was very powerful. Here are my 2 cents.

## Be Productive

Stick to what you know, and learn a little bit of something new every day. If what you know is how to use Excel like a boss, don't fee ashamed that you are missing something. Be proud and use what you know.

## Don't Stagnate

Take small steps enhance what you know now with something new that you get you closer to where you want to be. If you need something that sci-py offers learn how to load in data and use that part. If your sick of waiting for IT to pull data out of the database so you can use it, learn that.

## Dont Overwhelm Yourself

If you try to drop everything you know now and jump whole hog into these new flashy things its not going to work. Learn what you need to know. New things crop up very often. They will come and go. Some things will get traction, some will never get much traction past an impressive hello world example.

## Keep your finger on new tech

Its important to keep your finger on the state of technology, but dont Overwhelm yourself learning every new thing that comes out. Make silly hello world examples in these new things and walk away. When its time to implement something new into a real project you will be ready and understand how to do it. If that thing dies its good that you didn't waste a lot of time on it, but chances are it inspired the thing that actually takes off. Then you will have some understanding of what the next thing is doing ahead of everyone else who missed out on the original.

## I'll leave you with this inspirational video by Kitze

[![](https://waylonwalker.com/2020-02-16%2009-57-03_Microsoft%20Text%20Input%20Application.png)](https://www.youtube.com/watch?v=_kVxXV0TQ7M)

[Navigating the hype-driven frontend development world without going insane - KITZE](https://www.youtube.com/watch?v=_kVxXV0TQ7M)
This project is designed to help victims of the coronavirus. Need your feedback!
Tags: blockchain, testing, devops, help
Published: 2020-02-19 12:40:23

Hello, all!

A few friends and I created this in hopes of being able to send financial help directly to coronavirus victims and those who are launching relief efforts during this crisis. Would greatly appreciate it if some of you can test it out and send feedback so we can refine and start launching æid efforts to help out.

https://addons.mozilla.org/en-US/firefox/addon/corona-wallet-extension/

You could find a guide here: https://medium.com/@coronanewsorg/corona-wallet-beginners-guide-a46e2f845832

I would be grateful for feedback!
Create a slice with make
Tags: go, beginners
Published: 2020-02-19 12:29:07

In the <a href="https://golang.org">Go</a> programming language you can create <a href="https://golangr.com/arrays/">arrays</a>: collections.

You can create slices with the built-in **make()** function; you can create dynamically-sized arrays this way.

Remember that the usual array has a fixed size, that you would define in one of these two ways:

```go
var a [10]int
var a = []int64{ 1,2,3,4 }
```

What if you want an array that contains zeroes?

## Make() in Go

The make function allocates a zeroed array and returns a slice that refers to that array. The syntax of the make() function is:

    your_array := make([]type, length)

So if you'd have a program like this:

```go
package main

import "fmt"

func main() {
	a := make([]int, 5)
	printSlice("a", a)

}

func printSlice(s string, x []int) {
	fmt.Printf("%s len=%d cap=%d %v\n",
		s, len(x), cap(x), x)
}
```

It would output the array (contains a lot of zeros, the make() function does this):

    a len=5 cap=5 [0 0 0 0 0]

To change its size, change the second parameter

```go
a := make([]int, 50)
```
Adding patterns and designs to your pages without using Scalable Vector Graphics. 
Tags: css, cssdoodle, html
Published: 2020-02-19 12:11:58

---
title:Adding patterns and designs to your pages without using Scalable Vector Graphics. 
published: true
description: 
tags: CSS,CSS-doodle,HTML
---
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fodlfunbwermoymqaq4i.png)

As Front-end web developers, pixels can be both our friends and worst enemies. Making everything to look nice and sharp for anyone who uses any of the websites we work on, but we need to keep file sizes down for performance. There is pretty way to go about handling patterns and designs on web pages — <code>Css-doodle</code>. 
CSS-doodle is a library of tools that create art using CSS. CSS-doodle is a web component, just like any other HTML tag <code>css-doodle</code>. The component will generate a grid of divs by the CSS rules inside it. You can easily manipulate those cells using CSS to come up with a graphic pattern or an animated graph on your web pages. CSS-doodle can be use to create some awesome repeated patterns.

How to use CSS-doodle:

First, you need to download the latest version or include it directly from a CDN src="https://unpkg.com/css-doodle@0.7.7/css-doodle.min.js">. Alternatively, you can also install CSS-doodle from npm and import the module in JavaScript npm install css-doodle.
Secondly, We don’t actually need to write any JavaScript, or any CSS for that matter, everything we do will take place in the HTML. In the body section of your HTML you add the syntax <code>css-doodle</code>. This element is targeted by the library and the contents we add will determine the pattern generated which can also be wrap within a <div> element. 
The syntax of <code>css-doodle</code> is based on CSS and provided several extra utility functions and shorthand properties for:

1. Grid
2. Selectors
3. Properties
4. Functions
5. JS API. 

Using the CSS Grid layout, the number of rows and columns in the grid is defined by the grid attribute on the element, ranged from 1 to 32. It's default to be 1x1 when no value or 0 is given.
The CSS-doodle component accepts any valid CSS rules. There are special selectors, properties and functions that that you can use to create pretty much any pattern imaginable. 
To get started with CSS Doodle head over to https://css-doodle.com There you’ll find code examples and inspiring demos of things you can create with it. 

Have fun playing with Css-doodle.
Format dictionary as table
Tags: python, beginners
Published: 2020-02-19 12:06:00

In <a href="https://python.org">Python</a> you can use formatted strings to output variables easily.  
Formatted string literals (f-strings) let you include variables inside a string by prefixing the string with f or F and writing expressions as {expression}.

If you have an f-string, you can use the `:10` to make sure it's 10 character wide. This let you create a nice table like this:

If you are new to Python, you should first <a href="https://pythonbasics.org">learn the basics</a>.

## Format dictionary as table with f-strings

If you have a newer version of Python (>3.5) you can use f-strings. These let you format strings nicely.

First we define a <a href="https://pythonbasics.org/dictionary/">dictionary</a>, then iterate over it with a for loop and format it with f-strings.

```python
>>> table = { "Alice": 12, "Jim": 15, "Tim": 19 }
>>> for name, id in table.items():
...     print(f'{name:10} => {id:10d}')
... 
Alice      =>         12
Jim        =>         15
Tim        =>         19
>>> 
```

If you want to add a header, just call the print function before. We removed  the decoration, making it easier to read.

```python
d = { "Alice": 128, "Bob": 256, "Tim": 512, "Jim": 1024 }
print(f"Key{' ':14} Value{' ':15}")
for k, v in d.items():
    print(f"{k:8}{v:15}")

```

This returns

```python
Key               Value               
Alice               128
Bob                 256
Tim                 512
Jim                1024
```

## Existing functions

You can also use an existing function, like this one I found on the web. Personally I prefer formatting with f-strings, but this may be what you are looking for.

```python
def printTable(myDict, colList=None):
    if not colList: 
        colList = list(myDict[0].keys() if myDict else [])
    myList = [colList] # 1st row = header
    for item in myDict: 
        myList.append([str(item[col] or '') for col in colList])
    #maximun size of the col for each element
    colSize = [max(map(len,col)) for col in zip(*myList)]
    #insert seperating line before every line, and extra one for ending. 
    for i in  range(0, len(myList)+1)[::-1]:
         myList.insert(i, ['-' * i for i in colSize])
    #two format for each content line and each seperating line
    formatStr = ' | '.join(["{{:<{}}}".format(i) for i in colSize])
    formatSep = '-+-'.join(["{{:<{}}}".format(i) for i in colSize])
    for item in myList: 
        if item[0][0] == '-':
            print(formatSep.format(*item))
        else:
            print(formatStr.format(*item))

d = { "Alice": 128, "Bob": 256, "Tim": 512, "Jim": 1024 }
printTable([d])
```

This outputs:


```
------+-----+-----+-----
Alice | Bob | Tim | Jim 
------+-----+-----+-----
128   | 256 | 512 | 1024
------+-----+-----+-----
```

**Related links:**
* <a href="https://gumroad.com/l/dcsp">Python programming course</a>
* <a href="https://www.python.org/dev/peps/pep-0498/">Python formatted strings, f-strings</a>
FYI, github secret gist is not private, use gitlab snippet instead
Published: 2020-02-19 11:47:33

---
title: FYI, github secret gist is not private, use gitlab snippet instead
published: true
description: for private purpose make sure that you doing a real private
tags: 
---

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

If you need a private snippet, use GitLab snippet instead of GitHub gist because secret gist is not private. 
Omg, Really? Yes according to GitHub documentation 
"Secret gists aren't private. If you send the URL of a secret gist to a friend, they'll be able to see it. However, if someone you don't know discovers the URL, they'll also be able to see your gist."

I created this secret gist just to show you an example, try to access https://gist.github.com/pvgomes/43e3c575ab401f27937b4426d1e3e815
and this gitlab private snippet https://gitlab.com/snippets/1942790

I really like the way that gist works, but with gitlab we can create a good description of our snippet, this helps also to avoid a lot of comments inside the snippet. It does not mean that gist is bad, it just means that depends of your purpose make sure that you're using a real private snippet.

that's it.
pass statements
Tags: python, beginners
Published: 2020-02-19 11:37:16

In some programming languages there are is a statement that does nothing. In assembly there's `nop` (no operation). How about Python?

In Python you can use the `pass` statement. The `pass` statement does nothing.

## Why pass?

Python has the syntactical requirement that code blocks (for, if, except, def, class etc.) are not empty. 

Empty code blocks are useful in different contexts, such as when you don't have time to implement right now. 

```python
def complexFunction():
    pass
```

Other purposes are deriving an exception class that does not add new behaviour

```python
class CustomException(Exception):
    pass
```

if you want to ignore a type of Exception

```python
try:
    self.version = "Expat %d.%d.%d" % expat.version_info
except:
    pass # unknown
```

Below are some more pass examples

## Pass examples

If nothing is supposed to happen in a code block, a pass is needed for such a block to not produce an IndentationError


You can use this for all kinds of purposes. Inside a while loop:

```python
>>> while True:
...     pass 
```

This will wait for a keyboard interrupt (Ctrl+C)

In a <a href="https://pythonbasics.org/class/">class</a> that you need to implement, but will implement later:


```python
>>> class Example:
...     pass
...
```

But beware, if a class is not implemented you can still create objects:

```python
>>> obj = Example()
>>> 
```

In a function that you implement later:

```python
>>> def hello():
...     pass   # Implement this later
```

**Related links:**
* <a href="https://pythonbasics.org">Learn Python Programming</a>
* <a href="https://medium.com/better-programming/how-to-use-pass-break-and-continue-in-python-6e0201fc032a">How to use pass, break and continue</a>