teleren/devto huggingface dataset:
Conditionally assign a CSS class to a React component
Tags: react, javascript
Published: 2019-11-05 16:04:50

---
title: Conditionally assign a CSS class to a React component
published: true
description: How to assign a CSS class based on an object property
tags: reactjs, javascript
cover_image: https://ferrariwebdevelopment.s3.us-east-2.amazonaws.com/assets/20190925-conditional-css-class-name.jpeg
---

## How to assign a CSS class based on an object property

Let's say we need to display some data that has this structure:

```js
const groceries = [
  {
    id: 1,
    name: "bananas",
    purchased: false
  },
  {
    id: 2,
    name: "apples",
    purchased: true
  }
]
```

One of the properties of these grocery objects is `purchased`.
`purchased` is a `boolean` property and can be `true` or `false`.
When we display these items, we want to style them differently depending on their `purchased` property.
If the item is purchased, we want to add the CSS class of `purchased` to the `className` property of the component.
If the item is not purchased (`purchased: false`) we want to display the item normally.

For this purpose, we can use a *ternary* operator to check if the item has a property of `purchased` set to `true`. If it does, we add the class `purchased` to the element.
We can then style the `purchased` class differently, for example adding a line-through style.

```js
<div className={props.item.purchased ? 'purchased' : ''}>
```

The example above assumes we don't already have any other class on the div.
What if we already have a class name and need to add an *additional* `purchased` class?

In this case we can take advantage of the Javascript string interpolation syntax that uses a dollar sign and braces inside back-ticks to interpolate Javascript in a string, like this:

```js
<div className={`item${props.item.purchased ? ' purchased' : ''}`} >
```

This example is a little tricky to understand, let's look at it in detail.
We first add the `item` CSS class in the backticks. We then start the interpolation syntax with the dollar sign and inside the brackets we place a ternary operator that checks the value of the purchased property of the item.

If the property is `true` we then add a string that starts with a *space* (to separate it from the existing class) and then the `purchased` string.
The result will be an `html` element that looks like this:

```js
// when purchased is false:
<div class="item">

// when purchased is true:
<div class="item purchased">
```

That's how we use ternary operators to conditionally specify `CSS` classes on React components.
Divide pizzas with a Greedy approach & Python
Tags: computerscience, python, algorithms, greedy
Published: 2019-11-05 15:59:07

Consider that you are having 10 friends over and have ordered 7 pizzas. How can you divide those pizzas fairly? One way is for everyone to get half a pizza and a fifth of a pizza. (for example, by splitting 2 pizzas in fifths and the other 5 in halves).

If we were to represent our problem as fractions:

![fraction1](https://i.imgur.com/BRDn2Gm.png)

This way of writing a fraction as a sum of distinct unit fractions (fractions that have a numerator equal to 1 and the denominator a positive integer) was used as a serious notation for the rational numbers by ancient Egyptians and is called an Egyptian fraction.

We can use the computer to find the Egyptian notation for any fraction using a fairly simple greedy approach: in short, for any given fraction M/N, find the least integer greater than or equal to N/M, let it be x, and then recur for M/N - 1/x until the result is 0.

Alright, let's code a solution! Firstly, we have to read our M and N. Let's make the user give it as M/N:

```python
M, N = [int(x) for x in input("M/N = ").split('/')]
```

Now, let's write a function that prints the sum:

```python
def egyptian_fraction(m, n):
    while m > 0: # we recur until m is 0
        x = n // m
        if n % m != 0: # if n is not divisible by m, we have to add 1 in order to respect the 'greater than or equal' part.
            x += 1
        m = m * x - n # when calculating, M/N - 1/x = (M*x - N) / N
        n *= x
        print("1/{0}".format(x), " + " if m != 0 else "", sep = "") # print the numbers like: 1/2 + 1/5
``` 

In the end, our program could look like this:

```python
def egyptian_fraction(m, n):
    while m > 0:
        x = n // m
        if n % m != 0:
            x += 1
        m = m * x - n
        n *= x
        print("1/{0}".format(x), " + " if m != 0 else "", sep = "")

M, N = [int(x) for x in input("M/N = ").split('/')]
egyptian_fraction(M, N)
```

So, in the end, we have a program capable of dividing pizzas equally among our guests! As a matter of fact, this approach can be used to divide any object in equal shares. 
Do you have any thoughts about this approach or code? Let me know in the comments!
RxJS Schedulers [Video]
Tags: angular, rxjs, webdev
Published: 2019-11-05 15:47:25

---
title: RxJS Schedulers [Video]
published: true
description: You already know that Observables produce values over time. And the moment when exactly value will be emitted is controlled by special entity - scheduler.
tags: angular,rxjs,webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/4akig4p9j9os03tsm2yh.jpg
---

You may already know that in RxJS Observables produce values over time. And the moment when exactly value will be emitted is controlled by a special entity - scheduler.

Knowing how schedulers work is extremely important in understanding how to unit test your async code.

Want to learn what are schedulers? Watch this video:

{% youtube XizAnk1KItU %}

This video is a part of my free video-course "RxJS unit testing in Angular application. The whole picture.". You can get it by [this link](https://mailchi.mp/9c8299ec62c2/rxjsunittesting)
Webcam Suggestions Anyone?
Tags: hardware, discuss
Published: 2019-11-05 16:08:12

---
title: Webcam Suggestions Anyone?
published: true
date: 2019-11-05 15:35:52 UTC
tags: hardware, discuss 
canonical_url: https://www.iamdeveloper.com/posts/webcam-suggestions-anyone-125h/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/5l6xundreqtk25dgj83u.JPG
series: home office setup
---

I'm looking to buy a webcam for my home office. The one on my laptop works quite well, it's just when I'm in a video call, my laptop is to the left or right of me as my external monitor is in front of me, so you always see my side profile.

I'm looking for a webcam I can mount on my screen or sit on my desk so I'm looking directly at the webcam. Some Googling produced some decent results, e.g. [https://www.techradar.com/news/computing-components/peripherals/what-webcam-5-reviewed-and-rated-1027972](https://www.techradar.com/news/computing-components/peripherals/what-webcam-5-reviewed-and-rated-1027972), but I'm wondering what recommendations people may have here.

I'm not looking to break the bank on this, so probably max 100$ CAD.

Thanks in advance for any suggestions!
How to make HTTP requests with Node
Tags: javascript, node, http, devjournal
Published: 2019-11-05 15:27:24

If your experience is any similar to mine, the first time you had to fetch data from a JSON API on your Node server you probably wrote something like this and were disappointed it didn't work.

```javascript
fetch(API_URL).then(doStuff)
```

It is unfortunate, but `fetch` doesn't work in node. Luckily, there are several other ways to make HTTP requests. There is a library called [axios](https://github.com/axios/axios) that is based on promises and ends up doing something similar to `fetch`. Today, however, I'm going to talk about the module http.

## What is http?

http is Node's standard module to perform HTTP requests. The coolest part about it is that you don't need to install any dependencies to use it, just require it and you're ready to go.

```javascript
const http = require('http')
```

There is one catch, though. http only works for HTTP, so if you're sending a request via HTTPS, then you'll need to use the module https instead.

## Making a GET request

```javascript
const http = require('http')

http.get(API_URL, res => {
   let data = ''
   res.on('data', chunk => data += chunk)
   res.on('end' () => console.log(JSON.parse(data))
}).on('error', err => console.error(err.message))
```
This executes an HTTP GET request to API_URL and gathers the data into the variable `data` as it receives it. Once it's finished receiving data, it parses it and logs it on the console.

If we want to make the code reusable with promises, we only need to make a function that returns a promise:

```javascript
const request = url => new Promise((resolve, reject) => {
   let data = ''
   const req = http.get(url, res => {
      res.on('data', chunk => data += chunk)
      res.on('end', () => resolve({ ...res, body: JSON.parse(data))
   }).on('error', reject)
})
   .then(({ res, body }) => doStuff())
```

A good thing about the method `.get` is that it calls `.end` automatically, so we don't need to add it.

## Making other kinds of requests

http also has the method `request`, which can be used to make any sort of HTTP request. Besides (or instead of) the url, it takes an object with the request's options as its first argument.

```javascript
const options = {
   hostname: API_HOST,
   path: API_PATH,
   method: 'POST',
   headers: { ... }
}

const request = options => new Promise((resolve, reject) => {
   let data = ''
   const req = http.request(options, res => {
      res.on('data', chunk => data += chunk)
      res.on('end', () => resolve({ ...res, body: JSON.parse(data))
   })
   req.on('error', reject)
   req.end()
})
   .then(({ res, body }) => doStuff())
```

Obviously, the module http(s) can be used without promises. But I like working with promises.
Day 3 of⚡️ #30DaysOfWebPerf ⚡️: Network profile
Tags: webperf, devtools, webdev, perfmatters
Published: 2019-11-05 13:52:51

{% twitter 1191713883209314304 %}
{% twitter 1191713886694711301 %}
{% twitter 1191713887504216064 %}
{% twitter 1191713888250793985 %}
Kubernetes Deployment Strategy - Recreate
Tags: kubernetes, devops, docker
Published: 2019-11-05 15:07:20

Recreate is the simplest deployment strategy. A recreate deployment would go something like this. Version 1 of the app is deployed. Deployment starts, all pods running version 1 of the app are deleted. Immediately followed by version 2 of the application being deployed. The biggest draw back with recreate deployments is the small window of downtime. 

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

## Manual Recreate Deployment

The self healing nature of Kubernetes makes a manual recreate deployment very easy. Because the ReplicationController or ReplicaSet managing the pods of your application will replace terminated pods you can simply modify the template of them prior to deleting the pods and it will deploy newer pods for you using the updated image specified in the template. 

{% gist https://gist.github.com/Duffney/a2b5dc2f1047a4a3dcd619e073ecbbc5 %} 

## Recreate Deploys with Kubernetes Deployment Resource

The Kubernetes Deployment resource provides declarative updates to your applications. In the previous example you had to think through the update process. You had to figure out what commands to run and in which order to run them. With the Deployment resource you define the strategy you want to use and set the behaviors you want to see and Kubernetes figures out the rest. Converting our update to use the Deployment resource vs. using kubectl looks like this. 


{% gist https://gist.github.com/Duffney/f74245494f88b3504b8dfb44b3c04790 %} 


The Deployment resource can be thought of as a wrapper around your replication controller or replicaset. By default the Deployment resources strategy is to perform a rolling update. You can change that by defining `.spec.strategy.type` as Recreate. Reference line 13 in the above manifest.

{% gist https://gist.github.com/Duffney/42b5ac8ecb46ae34dac64fa49e36e36b %}

### What Happened?

When using a Recreate deployment strategy in Kubernetes, the following actions occur. 

1. The Deployment resource created a ReplicaSet that was using v1 of the container image. 
2. The ReplicaSet created 3 pods using v1 image.
3. The image in the deployment was changed to v2.
4. The Kubernetes noticed this change and created a new ReplicaSet that uses v2 of the image.
5. Kubernetes set the ReplicaSet using v1 replica count to 0.
6. The v1 ReplicaSet deleted all of its pods.
7. Kubernetes changed the replica count on the v2 ReplicaSet to 3.
8. The v2 ReplicaSet created 3 new pods all using v2 of the image.
9. Update complete!


### When to Use

1. Your application can withstand a short amount downtime.
2. When your application does not support having new and old versions of your application code running at the same time.

### Labs & Code Samples

All the manifests and cost samples can be found in this repo or in the gits linked in the post.

{% github https://github.com/Duffney/Kubernetes-Update-Apps-The-Hard-Way no-readme %}
Facial recognition, why worried?
Published: 2019-11-05 15:05:41

Facial recognition technology is spreading rapidly.  Already widespread in China, software that identifies people by comparing images of their face to an archive database is being adopted in much of the world.  It is common among police forces, but has also been used in airports, railway stations and shopping centers.
      The rapid growth of this technology has triggered an indispensable debate.  Activists, politicians, academics and even police express serious concerns about the impact that facial recognition could have on a rights-based and democratic political culture.
Read more.. https://dailytechmonde.blogspot.com/2019/11/reconnaissance-faciale.html
The OpenID Connect Handbook
Tags: authentication, programming
Published: 2019-11-05 15:03:34

---
title: The OpenID Connect Handbook
published: true
description: A preview of our new ebook about OIDC, the de facto standard for handling authentication in the modern world.
tags: #authentication #programming 
canonical_url: https://auth0.com/blog/the-openid-connect-handbook/
---
TL;DR: In August 2019, Auth0 published an ebook called The OpenID Connect Handbook to help developers leverage this modern identity layer to provide an easy and secure authentication mechanism to their users. This ebook covers all the main concepts that you must know to integrate your app with OpenID Connect providers. If you are in a hurry and would like to dive right into the content of the ebook, follow this link to get your free copy. The rest of this article will summarize the content of the ebook so you can take a glimpse of what you will learn about on the ebook.

[Keep reading 🚀] (https://auth0.com/blog/the-openid-connect-handbook/?utm_source=dev&utm_medium=sc&utm_campaign=oidchb_blog)

![The OpenID Connect Handbook](https://cdn.auth0.com/blog/illustrations/open-id-connect.png)
Podcasts for Engineers and Programmers of All Levels
Tags: podcast
Published: 2019-11-05 14:55:26

---
title: Podcasts for Engineers and Programmers of All Levels
published: true
description: engineering podcasts for all levels
tags: podcasts
cover_image: https://thepracticaldev.s3.amazonaws.com/i/xf3jjacl8txeq9q9wzc7.jpg
---


Lately I have been on a big podcast kick and I found a ton of great engineering related ones.  I saw some recent articles like this so I decided to make my own list. These are in no particular order of importance.


## 1 . Software Engineering Daily

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

This is one of my favorite podcasts out there.  There are so many episodes available that range from Flutter, to scaling engineering at Facebook, Slack Messaging Architecture and so on.  These are real world examples of technologies in use at various companies.  Its an excellent resource to learn about new tech and how companies handle innovation.

It can be found here: https://softwareengineeringdaily.com/

## 2. The RayWenderlich.com Podcast
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/pzwoc8i0yjbqde3dp4dn.png)

This is also one of my go to's.  I have learned so much from this site in turns of iOS and Swift development.  The podcast has a broad range of topics from iOS, Android and Unity and beyond.  They are quick listens that are great for a morning commute.

It can be found here: https://www.raywenderlich.com/


## 3. Go Time
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/29yjzholl4o2oojrrymq.png)

An excellent Go focused podcast.  "A diverse panel and special guests discuss cloud infrastructure, distributed systems, microservices, Kubernetes, Docker…oh and also Go!"

## 4. The Python Podcast.__ init __

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

Their words say it best:  "The podcast about Python and the people who make it great".  A python focused podcast that talks all things from Machine Learning to Web API's to, well anything.  And thats Python for ya.  Check it out https://www.pythonpodcast.com/

## 5. Engineering Culture by InfoQ

Engineering goes beyond just building things.  Its about the how as much as the who.  This is a great listen to learn and familairize yourself with the otherside of the software world.  Excellent for learning about engineering management.  If you are like me and are transitioning from a full time coder to coder/leader then this is a great listen.

Get it: https://www.infoq.com/engineering-culture-podcast/

## 6. The Bike Shed
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/xo4sup71t867pqcqhdvo.png)

One of my newly favorite podcasts.  They range from Ruby to React to SQL and just life in the software world as a whole.  I have this at 6, but numbers are made up and ranks dont matter.  


Here: https://bikeshed.fm/




ALAS, if you have any other suggestions post them!  Im always looking for new listens and learning never stops.
Daily Challenge #108 - Find the Counterfeit Coin
Tags: challenge
Published: 2019-11-05 14:48:18

---
title: Daily Challenge #108 - Find the Counterfeit Coin
published: true
series: Daily Challenge
description: How many weightings will it take to find the coin? 
tags: challenge
---
Imagine you have 8 coins of equal weight, except for one. The odd one weighs less than the others because it is not made of pure gold. How many iterations are needed to find this counterfeit coin using a two plate scale? 

Write a function that represents this logic puzzle and returns the minimum number of weightings it will take to measure *n* coins, without relying on luck at all. It can help to think recursively.

Good luck, have fun!
***
_This challenge comes from GiacomoSorbi on CodeWars. Thank you to [CodeWars](<https://codewars.com/>), who has licensed redistribution of this challenge under the [2-Clause BSD License](<https://opensource.org/licenses/BSD-2-Clause>)!_

_Want to propose a challenge idea for a future post?  Email **yo+challenge@dev.to** with your suggestions!_
Who wants to do open source together?
Tags: opensource, javascript, pwa, web
Published: 2019-11-05 14:29:59

---
 title: Who wants to do open source together?
 published: true
 tags: opensource, javascript, pwa, web
---

Is there any new open source project that needs contributions or PRs? If there's none, I wanna propose one. 
It's a service registry/discovery agent, kinda like Spring Cloud's consul. Each service would be registered as a name and have a node apportioned to it and a configuration object would be associated with each service. This object's keys would be used to configure the registering service. This would aid in the development of microservices.

Each service could be referenced using it's node name or hash. Only one service per node.

For the platform's UI, I was thinking of using Angular (React is fine as well).
We'd be sticking to a microservice architecture for the APIs. The Auth service (User's service) would be built using NodeJs and the Node service would be built using Spring Boot. We'd also be leveraging on Websockets for pings to the registered services to check for health status.

We'd also create a NodeJs library for interacting with the API (We'd talk about the name in a workspace) and another for creating custom endpoints to ping.

Who's in?
Matt's Tidbits #41 - Converting a BehaviorRelay into a PublishRelay
Tags: mattstidbits, android, kotlin, rxjava
Published: 2019-11-05 14:29:06

[Last week I explained the way errors don’t propagate outside of a `doOnSubscribe()` block.](https://medium.com/@matthew.b.groves/matts-tidbits-40-rxjava-doonsubscribe-behavior-explained-1b197c7df9ba) This time, I wanted to share an exciting discovery — how to convert a `BehaviorRelay` to a `PublishRelay` (and why you would want to).

On the project I’ve been working on recently, I was presented with an interesting challenge — I have a `BehaviorRelay` and need it to behave like a `PublishRelay`.

What’s the difference you ask? They’re both a type of RxJava `Observable` that does not allow for errors to be emitted. However, there is one fundamental difference — a `BehaviorRelay` will emit the most recent item when someone subscribes to it, while a `PublishRelay` will not.

Given that RxJava has nearly as many operators as [emacs](https://xkcd.com/378/), you’d think there would be a built-in easy way to convert from a `BehaviorRelay` to a `PublishRelay`. Unfortunately, this is not the case. But, we can do a pretty good job of building one on our own!

Here’s what I came up with:
{% gist https://gist.github.com/mpeng3/a25ae51a75838d120c28cb2cd6374e43
%}

The most obviously important part is the `hasValue()` check and corresponding `skip(1)` statement. This allows us to check if the `BehaviorRelay` has a value that it would emit upon subscription.

However, that’s not all of it — the `Observable.defer()` is also _very_ important — this guarantees that we’re not checking if the `BehaviorRelay` has a value until the client subscribes to the `Observable` we’re returning. This means we reduce the window of time during which our call to `hasValue()` might change.

Unfortunately, this does not completely eliminate the possibility of things getting messed up — it’s possible, especially in a multi-threaded environment, that when we call `behaviorRelay.hasValue()` it returns `false`, but by the time we get ready to return the `behaviorRelay` itself a value will have been emitted, which we may have been intending to skip.

I’m not crazy about there still being a chance for things to go wrong, but this is the best I could come up with. Do you have an idea for how to improve this further? If so, please let me know in the comments! And, please follow me on Medium if you’re interested in being notified of future tidbits.

Interested in joining the awesome team here at Intrepid? [We’re hiring!](https://www.intrepid.io/careers)

*This tidbit was discovered on October 24, 2019.*