teleren/devto huggingface dataset:
Navigation Component Essentials
Tags: navigationcomponent, jetpack, android, architecture
Published: 2020-01-26 15:46:59

---
title: Navigation Component Essentials
published: true
description: A few pieces of code you'll always need when using the Navigation Component from Jetpack Architecture Components.
tags: navigation component, jetpack, android, architecture
---

# Don't go back to loading from your list!

When you want to allow a navigation from one fragment to another, but want to prevent backwards navigation along that path, **`popUpTo`** the navpath on that action.

Useful when you're leaving a loading state, or an error state for the next screen.

Note: nav_paths is the xml file containing the navigation graph for my project.

```xml
<action
                android:id="@+id/action_errorDisplayFragment_to_loadingFragment"
                app:destination="@id/loadingFragment"
                app:popUpTo="@id/nav_paths" />
```

# Don't crash on a rotation!

If you use a setup where rotating the screen would result in a call to a navigate function, it's very likely you'll attempt to navigate to the same screen that you were already on.

This crashes the app with a
```
java.lang.IllegalArgumentException: navigation destination com.aniketkadam.someapp:id/action_loadingFragment_to_someListFragment is unknown to this NavController
```

To avoid that, you can use this extension function and always navigate via that. It helps if you're using NavDirections instead of typed paths to make really sure this can be a valid path at all.

All we're doing here, is making sure each node the journey to the path, is valid since nearly any of them can be null.


```kotlin
private fun NavController.safeNavigate(d: NavDirections) =
    currentDestination?.getAction(d.actionId)?.let { navigate(d) }
        ?: Timber.e("Invalid route for direction ${d} with id ${d.actionId}")
```

You can see this in use in my project here:
https://github.com/AniketSK/ArchitectureExperiments/blob/master/app/src/main/java/com/aniketkadam/temperatureapp/MainActivity.kt

I didn't need it anywhere except that screen so I went with a private extension function. If you're going to use it in multiple places, please keep it with the rest of your extension functions!
[Here's](https://proandroiddev.com/organize-kotlins-extension-functions-992e3f5cd90d) a good article about how to organize them.

---

Want to help your team get out of tricky situations? I'm available for hire as an Android Consultant. Contact me at aniket@[firstname][lastname].com
I'm Live Streaming How To Build a Mobile App for Dev.to in Flutter with REST & GraphQL
Tags: beginners, flutter, tutorial, showdev
Published: 2020-01-26 15:09:31

In this very first live stream session, I'll build yet another mobile app for the **Dev.to community**. The application will be developed using the [Flutter framework](https://flutter.dev/). I'll integrate with Dev.to's REST API followed by the integration with the GraphQL endpoint provided by [OneGraph](https://www.onegraph.com/). My goal is to have a simple article browsing by the end of it.

The live stream will start at 18:00 CET / 12:00 EST on Sunday, Jan 26th. Here's the link:

{% youtube QH0FnlparOQ %}
laravel post spam protection
Tags: laravel, help
Published: 2020-01-26 15:08:21

Hi, my project is almost finish and ready to be publish. But first, I would like to ask on how you handle excess or massive spam on post request?

I use react as my front end and laravel as my api end points.

I would like to ask on how you guys handle spam protection on massive post request specially on '/login/' POST request. Thank you
Technical Issues In Javascript | NaN.3
Tags: javascript, webdev, codenewbie, beginners
Published: 2020-01-26 14:48:30

In the session, we will be looking into the below table of content.

###TABLE OF CONTENT

6. NaN 
7. parseInt(), parseFloat(), and Number()


###6. NAN
From most of the explanations, you will hear that **NaN** means Not a Number but wait for a second... that's true, right? yes of course that's the meaning but ask yourself do you truly understand how this works?


###NaN (technically, a **string** is not a **NaN** just because its not a number)

NaN is an error that occurs when you try to perform an action which is meant for **numbers**
For Example
    let isNotNaN = 'You think this is [NAN] just because its a string?';//This is not a NaN 
  
    let str = "Javascript";
    let num = 20;
    str * num; //This is a NAN

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3ydp56at7o8hf2oe1oef.png)
*So yeah we now understand NaN right 😃*


###7. parseInt(), parseFloat(),and  Number().

####parseInt()
this function is used to convert a number-string to an integer number.
For Example

    let str = '30.8';
    parseInt(str);//30 

####parseFloat()
this function is used to convert a number-string to a floating number.
For Example

    let str = '30.8';
    parseFloat(str);//30.8

####Number
this function is a way of converting a number-string to an exact number representation.
For Example

    let str1 = '30';
    let str2 = '30.5'
    Number(str1);//30
    Number(str2);//30.5


[Previous Content](https://dev.to/emmanuelonah/continuation-of-technicalities-in-javascript-that-often-gets-a-different-meaning-explicitly2-epd)
Daily Challenge #172 - Find All in an Array
Tags: challenge
Published: 2020-01-26 14:30:13

---
title: Daily Challenge #172 - Find All in an Array
published: true
series: Daily Challenge
description: Implement a function that will find all occurrences of an integer in an array.
tags: challenge
---
###Setup 
Implement a function that will accept an array of integers and an integer `n`. Find all occurrences of `n` in the given array and return another array containing all the index positions of `n` in the array. 

If `n` is not in the given array, return an empty array `[]`. 

Assume that`n` and all values in the array will always be integers. 

###Example

find_all([6, 9, 3, 4, 3, 82, 11], 3)
\> [2, 4]

###Tests

[6, 9, 3, 4, 3, 82, 11], 3
[10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16
[20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20

***
_This [challenge](https://www.codewars.com/kata/59a9919107157a45220000e1) comes from MementoMori 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!_
Incrementation in Javascript(forward & backward incrementation ++)
Tags: javascript, webdev, codenewbie, beginners
Published: 2020-01-26 14:29:31

In this session, we will be discussing Algorithm, Forward & Backward incrementation.


*First of all, what is an algorithm?*
I could remember my first algorithm course in the university, my *java lecturer* asked the student to create a **paper plane**. Then she asked us how we **emerged** to making such **similar planes?**, then everyone started narrating in different ways. She then replied and said an algorithm mustn't be written in the same pattern but often results in the same result. 


###Algorithm:
An algorithm is a way or pattern you use in solving programmatic issues with consideration of **time and space complexity**.

**So now haven explained algorithm, what is ++(incrementation)?**

**++ simply means incrementation by 1**, it's similar to +1 but +1 is not effective and adviseable.


####1. Forward incrementation 
Forward incrementation is a simultaneous way of incrementing a value by 1. In this type of incrementation, the value immediately changes(with the addition of 1). But in the case of backward incrementation(counter++), the value gets incremented at the background but only gets it **added** when you use it **a line after the line it was incremented**.
For Example:

    let prefixIncrementer = 0;
    ++prefixIncrementer;//1


####2. Backward incrementation
Backward incrementation is a way of incrementing a value that takes effect only when you invoke it **a line after it was created**.
For Example:

    let backwardIncrementer = 0;
    backwardIncrementer++;//0
    backwardIncrementer;//1

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zl13vkqm8x0cxnl6a21n.png)
Refactoring many OR statements like a ninja 🤘
Tags: todayilearned, refactorit, javascript, codequality
Published: 2020-01-26 14:24:32

# Scenario 🙄
Let's supose we have to check which **animals are bird**, a Junior developer would made something like this:
```javascript
if (animal === '🐓' || animal === '🐦'|| animal === '🐧' || animal === '🦉') {
  console.log(`I'm bird, pew pew`);
}
```
But according with **Clean Code**, **uncle Bob** if he saw this maybe would have this reaction:
![](https://media1.giphy.com/media/jSxK33dwEMbkY/giphy.gif?cid=790b7611da18598a1724455c919874e25afb5b1aa327cec1&rid=giphy.gif)

# Refactoring 🥳

Many `||` statements are a little too verbose and in addition have poor readability, so how we can improve this situation.

We can apply a nice concept, create an array (or list) with all comparasions and test if our animal are included on this array (or list)

## Let's check some code to clarify the idea 😏

### In javascript 😎
```javascript
if (['🐓', '🐦', '🐧', '🦉'].includes(animal)) {
  console.log(`I'm bird, pew pew`);
}
```

### In C# 🐱‍💻
```c#
if (new List<string> {"🐓", "🐦", "🐧", "🦉"}.Contains(animal)) {
  System.Diagnostics.Debug.WriteLine("I'm bird, pew pew")
}
```
### In Python 🐍
```python
if animal in ["🐓", "🐦", "🐧", "🦉"]:
  print "I'm bird, pew pew"
```

### In Clojure 🤓
```clojure
(if (string/includes? ["🐓", "🐦", "🐧", "🦉"] #animal)
  (println "I'm bird, pew pew"))
```

### In Elixir 🍷
```elixir
if Enum.member?(["🐓", "🐦", "🐧", "🦉"], animal) do
  IO.puts "I'm bird, pew pew"
```

Much more elegant isn't it?
🍻
What programming language(s) do you want to learn in 2020?
Tags: discuss
Published: 2020-01-26 13:56:34

---
title: What programming language(s) do you want to learn in 2020?
published: true
description: 
tags: discuss
---

I’m not sure if this counts as a new language, but I want to learn TypeScript this year. I’ve used JavaScript my entire career and now I’m finally curious to see for myself what all the hype is about.
Best Programming Books in 2020
Tags: webdev, tutorial, career, beginners
Published: 2020-01-26 13:42:30

There are many books out there for programmers and no one can read every book out there. There are many more articles about programming books written too, but it is hard to find a good filtered list with books for programmers. In this article, I wanted to make a list that will help everyone to find particular books about programming topics that they are interested in to read. I selected this particular list of books not just to improve your coding skills and make you a better programmer, but would also help you to grow as a person in every way. 

[**Continue reading...**](https://www.codespot.org/best-books-for-programmers/)
Nucu Car: Devlog 0x01
Tags: raspberrypi, dotnet
Published: 2020-01-26 13:31:42

---
title: Nucu Car: Devlog 0x01
published: true
description: Nucu Car: Devlog 0x01
tags: raspberrypi, dotnet
series: nucucar
---

Hello everyone,

A while ago I started working on a pet project called NucuCar. It’s a platform written in .NET for the Raspberry Pi in which I’m trying to implement various utility functions to create a complete piece of software that can be used to build a remote controlled car for the Pi.

The project is open source and it can be found on GitHub: [https://github.com/dnutiu/NucuCar](https://github.com/dnutiu/NucuCar)

Since I didn’t buy a toy car and I don’t have much space in my apartment I was working only on the sensors module, which currently has support for the BME680 environment sensor and the CPU temperature sensor build in the Pi.

The idea behind this is to make a daemon that polls the sensor, publishes telemetry data and can be easily configured. This is the configuration file:

![config](https://thepracticaldev.s3.amazonaws.com/i/3zgz4ck438guq76npx9y.png)

The Telemetry block configures which telemetry publisher to use Azure or Disk (for the moment, can be extended) and the interval in which to publish the telemetry data. The other two blocks configure whether the sensors and telemetry collection is enabled or not. That’s about it.

To develop this I’ve been using Github, a free Jira instance and JetBrains’ Rider.

![JiraBoard](https://thepracticaldev.s3.amazonaws.com/i/ut9gnfjgl918k2hfmcsi.png)

## Running on the Pi

I’ve build the project and uploaded it on the Pi, running it will all the options enabled yields the following htop result:

![htop](https://thepracticaldev.s3.amazonaws.com/i/e6o59la65p4u7bbaxnwq.png)

We have lots of processes which are in interruptible sleep, about 7.8% CPU time which went to 0.7% after a while and around 5.5MB or ram usage. That’s not bad, considering that we’re running C#. Oh, and I forgot to mention, the BME680 sensor is exposed via a gRPC server. 🙂

## Telemetry Data

While running the program, the telemetry data from the sensor was collected and saved to the disk. Here’s how an entry looks like:

```lang=js
{
   "source":"NucuCar.Sensors",
   "timestamp":"2019-12-01T23:26:13.5537227+02:00",
   "data":[
      {
         "sensor_state":2,
         "temperature":32.65558333857916,
         "humidity":100.0,
         "pressure":62228.49565168124,
         "voc":0.0,
         "_id":"Bme680-Sensor"
      },
      {
         "sensor_state":2,
         "cpu_temperature":48.849998474121094,
         "_id":"CpuTemperature"
      }
   ]
}
```

Then I wrote a Python script to plot the available data, skipping the first 10 results.

![data](https://thepracticaldev.s3.amazonaws.com/i/m69w6p836xmqgb8glhl3.png)
Why you should use semicolons in spite of ASI
Tags: javascript
Published: 2020-01-26 13:05:24

What side of the road do you drive on?

In England we say it's the right side which is of course left. This is enforced by the police, if I decided to try a different strategy, middle or the right hand side, I would either die, or be detained, but before that, I could in fact drive for miles if nobody was on the road.

I will see some commenters saying follow the lint rules of your project (the police program of your codebase), end of. But I am going to look at it from the poor parsers perspective.

``` js
foo: {

}

// Vs

{
    foo: {
    }
}
```

The grammer highlighter above is having a hard time with this. JavaScripts grammer is ambiguous as it is.

I could argue that it's polite to help the parser out with semicolons but I don't think that's enough, what I will say is when you don't uses semicolons you are relying on ASI automatic semicolon insertion to fill in the semicolons because you didn't bother, I get that, why write optional code? You got me yeah, write less sure, but what about context switching, you want to learn another language, I don't know, say Java, C++, C, Rust, PHP among others, these languages do not have ASI and you will need to add semis. So why not just get into the habit now?

I used to be the opposite, I have for a long time omitted semicolons, and in that time I learned the cases that I would need to use them. But why remember this at all, it's far simpler to train your muscle memory to just add semicolons.

Did you know that CSS has optional semi colons? But you didn't know that (probably) because it's under a very special circumstance, it's easier to just add them everywhere to make this parae and get on with your life, I have never seen anyone actually do it irl, not the case with JavaScript.

The last case, I have worked in 2 large companies, both use semi's as lint rules that say use them, so regardless of your preference, you are going to be using them. I feel there is a stronger case to enforce them to prevent errors during authoring and if a company told me otherwise I would fight hard to explain the cognitive load of remembering when and where to add semicolons in order for the parser to not mistake a () as a function call.

Tell me what your thoughts are down in the comments.
Daily Developer Jokes - Sunday, Jan 26, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-01-26 13:00:09

---
title: "Daily Developer Jokes - Sunday, Jan 26, 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=Sunday%2C%20Jan%2026%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/5e1258922d1b9.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:
I’ve been hearing news about this big boolean.

Huge if true.
 -->
Automated Sourcemap SourceContent Extraction by URL
Tags: webpack, typescript, sourcemaps, angular
Published: 2020-01-26 12:56:14

Today I wrote a nodeJs script called "pack-scraper".

What it does is walking through all script tags within the HTML body fetched from a provided url by the parameter "page" to check if there is any sourceMapUrl provided within any of the loaded Javascript files.

If pack-scraper finds any sourceMapUrls within the javascript files it will clone them to a local folder described by the parameter "outDir" and afterwards extracts the source files from this sourcemap files if available.

so, i.e we could serve a local angular app and execute:
"npm run cli outDir=example page=http://localhost:4200" to basically get the same sourcecode like the project contains if sourcemaps are enabled and the "sourceContent" array isn't empty.

Please note that this is a tool developed for analyzing.

You may wondering what happens with lazy loaded javascript files in Angular applications for example?

Those files are currently not automatically added to extraction, so if you wanna unpack them also you need to click through all routes in a i.e Angular page and finally provide the obtained script list to "additionalScripts" parameter seperated by a comma.

Since this scraper should basically be focused on Angular applications I am anyway planing on implementing a Class to analyze the mainbundle and finally its subbundles so it can extract paths and automate this process.

To get a list of available commands execute "npm run cli help" after cloning and running "npm i"
The sourcecode can be found here: https://github.com/xsip/pack-scraper

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/z1cyhdk115ntpokxqwhs.png)
JS - 💡 Merging multiple objects into one
Tags: javascript, beginners, webdev, tutorial
Published: 2020-01-26 12:45:22

Want to get better at Web Development 🚀🚀🚀? Subscribe to my weekly newsletter at **[https://codesnacks.net/subscribe/](https://codesnacks.net/subscribe/)**

---

Let's say you have multiple objects that you want to merge. How can we accomplish this? Without using any libraries there are two ways to do this in JavaScript:

* `Object.assign`
* `...` - the object spread operator

Now let's see `Object.assign` in action:

```js
const a = { x: "x", y: "y" }
const b = { z: "z" }

// create a new object and assign a & b
const c = Object.assign({}, a, b)
console.log(c) // {x: "x", y: "y", z: "z"}
```

The same works also with the object spread operator:

```js
const a = { x: "x", y: "y" }
const b = { z: "z" }

// create a new object and spread a & b
const c = { ...a, ...b }
console.log(c) // {x: "x", y: "y", z: "z"}
```

Cool, so we can now merge multiple objects into one. You can of course also merge more than two.

But what happens when there are properties, that are named the same in both objects?

Let's see:

```js
const a = { x: "x", y: "y", who: "I'm a" }
const b = { z: "z", who: "I'm b" }

const c = { ...a, ...b }
console.log(c) // {x: "x", y: "y", z: "z", who: "I'm b"}
```

So if two objects contain properties that are named the same, like the `who` property, the object that is used last will overwrite the properties of the former object. In our case `who` of `a` will be overwritten by `who` of `b`. 

That because first, all the properties and values of `a` are put into the new object. Then the properties and values of `b` are put into the object, overwriting properties, that are already there.

---

Want to get better at Web Development?
[🚀🚀🚀subscribe to the Tutorial Tuesday ✉️newsletter](https://codesnacks.net/subscribe/)
A plea for blogging about SQL
Tags: sql, data, blogging
Published: 2020-01-26 12:43:53

---
title: A plea for blogging about SQL
published: true
description: A small open plea to people writing posts about SQL
tags: sql, data, blogging 
---

## Two suggestions:

1 - If your intent is to write a piece about SQL that you feel may be relevant across dialects, then you are quite right to **not** include any specific dialect in the headline.

2 - However, if you're only going to use examples from your knowledge of just one dialect, then please, **do** clearly state that somewhere in the opening paragraph.

## About those suggestions

Re the first of those: alas when most of us scan articles to read, we are likely to skip past ones that mention a dialect that we don't know or use. However that would be a poor reason for us to be skipping a piece that possibly has wider applications. So  this is a reason to _not_ mention the dialect in the headline.

Re the second: conversely, if we start reading an article apparently about "SQL" and encounter something that simply isn't true for the SQL dialect that we know and use, then we're likely to be annoyed and maybe stop reading(*).

## The SQL readership

The reality is that there are so many SQL dialects, and they vary so much, that we can't expect to avoid these effects. Few of us are likely to know more than a handful of dialects well, but many of us will probably know specific ones disturbingly well.

Data can be an unforgiving area in which to work with dialect misundertandings being equally terrible when they cause rows of data to either:
- multiply noticeably on the scale of millions; 
- become rare exceptions that go unnoticed.

My hope is that if you are open about your context - and also invite cross-dialect supplementary comments - then we can all benefit from shared insights.

## Why do I care?

For what it's worth, my reality is that I have to do this in reverse. In working life I only use the products supplied to me by my employer. However I am interested in the variations and possibilities of others - other people, other products, other platforms. That requires me to have to push through the psychology and annoyances that I've mentioned above to keep broadening my knowledge - but it would be nice if that took less conscious effort.

I hope you found this post useful and apologise if you did not.  

Notes:
- (*) Actually, there's a subtlety there: as almost no SQL product uses "the standard" in full, we all get misled about what is normal for SQL. The harsh truth is that there is no normal at all. If I put my programmer hat on then I can't think of any other language in which the variations from the standard seem to outweigh the conformity to it.