teleren/devto huggingface dataset:
Creating Firefox browser extensions-24
Tags: javascript, showdev, webdev, beginners
Published: 2020-05-15 16:41:50

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

Welcome to part-24 of the series. In this part we will create a new addon called **Read Mode**. This addon allows the user to change, the currently opened tab to reader mode if available.

So, go ahead and create a folder **ReadMode** and inside it another folder **icons**. Inside that folder place three icons. You can get them from the github link at the end of this post.

![ReadMode](https://cdn-images-1.medium.com/max/2880/1*rr_piIkR2jTfRB4yNziQDQ.png)*ReadMode*

Now, create a file **manifest.json** inside the folder **ReadMode** and put the below content in it.

It is using the permissions for **notifications** and **tabs** which we are going to use soon.

![manifest.json](https://cdn-images-1.medium.com/max/2880/1*xhxqSN-LBdXb2e7x8c-A4Q.png)*manifest.json*

We only have another file ie **background.js** in this addon. So, go ahead and create it in the same folder and put the below content in it.

Now, our program starts from Line 10 where we have an event listener for [browserAction.onClicked()](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction/onClicked). This event will fire when the browser icon is clicked.

Inside the listener, we are passing the tab to [tabs.toggleReaderMode()](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/toggleReaderMode), which toggles reader mode for the current tab.

Now, some of the web-pages don’t have reader mode and the promise will fire the catch block. For such tabs, we are calling a function **failureCallback**(). The function shows an browser notification that the reader mode is not available.

![background.js](https://cdn-images-1.medium.com/max/2880/1*MSD7mXV3SPfEkjNp7TVHRA.png)*background.js*

So, our code is complete. I had checked it by testing the temporary addon and it works perfectly.

![Gif](https://cdn-images-1.medium.com/max/2000/1*BCBsSZ1sYEUaMYiHfCXkuw.gif)*Gif*

So, it’s time to publish it in the mozilla addon store. I will follow the procedure from another of my blog in the series. The link is [here](https://dev.to/nabendu82/creating-firefox-browser-extensions-2-3gpn).

Since, the name **Read Mode** was not available, i had to change the name of the addon to **My Read Mode**.

![My Read Mode](https://cdn-images-1.medium.com/max/2880/1*NzmyOxVykOOj5yKZvRkFXw.png)*My Read Mode*

This complete part-24 of the series. You can install the addon to your firefox from [here](https://addons.mozilla.org/en-US/firefox/addon/my-read-mode/)

You can find the code for the same in my github account [here](https://github.com/nabendu82/Addons).
TIL about shell parameter expansion in Bash
Tags: bash, quicktip, todayilearned
Published: 2020-05-15 16:39:41

---
title: TIL about shell parameter expansion in Bash
published: true
description: There is an easy way to optionally pass parameters to Bash commands.
tags: bash,quicktip,todayilearned
cover_image: https://firebasestorage.googleapis.com/v0/b/blog.rousseau.dev/o/images%2fbackgrounds%2fexpand.jpg?alt=media
canonical_url: https://blog.rousseau.dev/posts/til-about-shell-parameter-expansion
---

## The problem <a name="the-problem"></a>

I am working on a new Octopus step template for Firebase deployments. I want to make the template shareable, so it should support all of the deploy command parameters.

I do not write Bash scripts very often. When I do, I do not usually plan to share them, so I write them to suit only my use case. I quickly ran into a problem I did not have a solution to.

Take the `message` parameter of the Firebase deploy command.

```bash
firebase deploy -m "A helpful comment about this deployment"
```

`Message` is optional. I only want to pass it to the command if a user of the template has provided it.

## The solution <a name="the-solution"></a>

The solution is [shell parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html).

```
${parameter:+word}
    If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
```

Perfect! What does that look like in practice?

```bash
message=$(get_octopusvariable "FirebaseDeploy.Message")

firebase deploy ${message:+ -m "$message"}
```

I will be writing more Bash scripts, so it is good to have learned this feature early on.

What is your favorite Bash tip or trick?

_This post was originally published at [blog.rousseau.dev](https://blog.rousseau.dev/posts/til-about-shell-parameter-expansion). Cover photo by [NASA](https://unsplash.com/@nasa) on [Unsplash](https://unsplash.com/)._
BUILDING REACT FROM SCRATCH in 30 minutes (video)
Tags: react, webdev, techtalks, tutorial
Published: 2020-05-15 16:37:12

> This video is a talk from [*Byteconf React 2020*](https://www.bytesized.xyz/react-2020), a free, live-streamed React conference that aired on May 1st-2nd, 2020. Join our newsletter at the [conference website](https://www.bytesized.xyz/react-2020) to stay in the know about future conferences, videos, and more!

In this talk, we’ll create an effective mental model of Concurrent React by building a tiny clone of React! We will start with a blank js file and learn about how React renders components, schedules Time-Slicing updates with a Work Loop, add Hooks, and end off with a mini-clone of Suspense!

Thanks to [Shawn Wang](https://twitter.com/swyx) who presented this talk at [Byteconf React 2020](https://www.bytesized.xyz/react-2020)!

{% youtube fKlt5GFQnVc %}

If you enjoyed the video, give it a thumbs-up, and [subscribe to our channel](https://www.youtube.com/channel/UC046lFvJZhiwSRWsoH8SFjg?sub_confirmation=1) for more web dev content every week. We also have a newsletter where we send out what's new and cool in the web development world, every Tuesday – [join here](https://www.bytesized.xyz/newsletter)!
What do you hate most about being a developer?
Tags: discuss, career
Published: 2020-05-15 16:19:03

---
title: What do you hate most about being a developer?
published: true
description: We all hate something about being a software developer. Is it something about your job? Maybe it is the tech stack you know. Are the tools you use just not good enough or out of date? I want to know!
tags: discuss, career
---
Happy Friday!

Sometimes software development SUCKS...
![ARRRRGGGGG](https://media.giphy.com/media/2HWWvU3wXwZna/source.gif)

Sometimes it is AWESOME...
![w0000000t](https://media.giphy.com/media/4xpB3eE00FfBm/source.gif)

Vent your frustrations here!
Exclaim your joys here!

Go nuts!
I'll start 👇
Free Open-source portfolio template for developers
Tags: html, css, javascript, opensource
Published: 2020-05-15 16:15:04

A beautiful, minimal and accessible portfolio template for Developers  ✨ which is completely free and Open Source. Anyone can use this as a template for making their own portfolio and can customize it the way they want.

Give it a star 🌟 on Github if you find it useful.

<blockquote>
    <div>
        GitHub <a href="https://github.com/nisarhassan12/portfolio-template" target="_blank">Repo Link →</a>
    </div>
    <br/>
    <div>
        Check out the <a href="https://portfolio-template.surge.sh" target="_blank">live demo here →</a>
    </div>
</blockquote>

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

<img alt="Portfolio Gif" src="https://dev-to-uploads.s3.amazonaws.com/i/wgeq8ew849vx75h81ht3.gif">

You can find the documentation on how to make your own portfolio [here](https://github.com/nisarhassan12/portfolio-template/#getting-started-).

Contributions are warmly welcomed ❤️.

## Features

- Clean, Simple and Modern UI Design.
- Uses No CSS or JavaScript Frameworks or libraries as dependencies.
- Built with only HTML, CSS and a bit of JavaScript 🔨.
- Well Organized Documentation.
- Keyboard support.
- Fully Responsive.
- Loads fast ⚡.


#### Lighthouse Report

![Lighthouse Report](https://dev-to-uploads.s3.amazonaws.com/i/jzfk00tjoedsrwtqaoki.png)
Django.(How to dynamically hide fields in an inline).
Published: 2020-05-15 16:13:34

Imagine that you want to hide a model field within an inline in the Django admin, but this field must be visible if you want to add a new record, next I will show you an easy and elegant way to do this.

This technique is just the beginning, I can do many things from this simple implementation. let's start.

1- As you already know, when defining a field in django you can put several attributes, as if this is required, the label, etc., in addition to these, you can put a widget and define its behavior.![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/grxoq81pexw5gg4zniuv.png)

In this case, the widget will be manipulated using our DocumentsPopulatedText class.

2- Remember before importing what is necessary.
from django import forms.

In DocumentsPopulatedText for this case the field that I want to hide or show is a Select, that's why forms.Select, then the render method is overridden, this method is the one that changes the field aspect, now, as you want to hide the power to select when the instance is created and show only when you want to add a new one, "__prefix__" inside name comes whenever the instance is created, so whenever __prefix__ comes, we call forms.HiddenInput () to hide the field and return an empty string , here you can return any text you need.![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4pbqcrg30krfvvllcgjt.png)

As a result.(in this image the widget is not forms.Select but forms.FileInput, but the base itself.

As you can see, all the instances that are saved cannot add a file, however the last one yes, this last one was added by means of the action of "add additional bank account" that is shown in the lower left part.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ydz8gw8dbw1hcn29q1j2.gif)

I hope it can serve as a base to do much more advanced things.
the difference between RSpec eq and be
Tags: testing, ruby, rails, beginners
Published: 2020-05-15 16:03:45

![ruby](https://miro.medium.com/max/800/1*Pr8GffnQMojxKwRqCRsGZw.gif)

RSpec has two equality matchers: `eq` and `be`. Depending on the circumstances, `eq` works *most of the time*. The difference between the two is subtle. The result of understanding the difference will yield clearer and more reliable specs.

Take this contrived example which expects a user name to **be** "Jon".

```ruby
RSpec.describe User, "#name", type: :model do
  let(:user) { Fabricate(:user, name: "Jon") }
  
  scenario "User's name is Jon" do
    expect(user.name).to be("Jon")
  end
end
```

Running this test we get a failure.

```
Failures:

  1) User's name is Jon
     Failure/Error: expect(user.name).to be "Jon"

       expected #<String:70298288643660> => "Jon"
            got #<String:70298288643700> => "Jon"
...
...
```

It's failing and rightfully so! RSpec's `be` matcher expects both entities to **be the same object**. In other words, `user.name` and the string `"Jon"` are expected to have the same **object_id**.

##### irb
```ruby
irb(main):001:0> jon = "Jon"
=> "Jon" 
irb(main):002:0> "Jon"
=> "Jon" 
irb(main):003:0> jon == "Jon"
=> true
irb(main):004:0> jon.equal?("Jon")
=> false
irb(main):005:0> jon.object_id
=> 70185646150880
irb(main):005:0> "Jon".object_id
=> 70185646097920
```

Notice the object ids are different. Under the hood, RSpec is calling `Object#equal?` which is a check at the object level. 

RSpec's `eq`, is what you expect the string **value to be matched against**. Going back to our earlier example:

```ruby
RSpec.describe User, "#name", type: :model do
  let(:user) { Fabricate(:user, name: "Jon") }
  
  scenario "User's name is Jon" do
    expect(user.name).to eq("Jon")
  end
end
```

After you run your spec, you're passing!

```
Finished in 1.12 seconds (files took 13.85 seconds to load)
1 example, 0 failures

Randomized with seed 4227
...
...
```

The user's name value is "jon". That's the same as the value of the string "Jon". Peaking under the hood again.. RSpec `eq` invokes `===` on the two objects which checks the return value. 

#### TLDR

`eq` checks if the object values are the same

`be` checks if the objects are the same

[Read more, here.](https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers)
Make Laravel do type safe validation
Tags: laravel, validation, type, typesafety
Published: 2020-05-15 14:28:31

Laravel has a nice validation framework, but a big catch is that it doesn't make sure your result has the right types. 

here an example:

```php
$data = ['isOk' => '1'];
$result = $this->validate($data, ['isOk' => 'boolean');

$isOkString = $result['isOk'];
$isOkBoolean = (boo;)  $result['isOk'];
if($isOkString === true){
    // wont fall here.
}
if($isOkBoolean === true){
    // but will go here.
}
```

wouldn't be wonderful to make sure you have no side affects.

Todo this we must create a nice interface to be able to make Rules allow to transform the result. You must subclass the Laravel `Validator` and extend the method: `validateUsingCustomRule`


```php
interface RuleTransformsResult
{
    public function transformResult($attribute, $value);
}


class MyTypeSafeValidator extends \Illuminate\Validation\Validator {
    protected function validateUsingCustomRule($attribute, $value, $rule)
    {
        // below is just copy pasted laravel code of method
        if (!$rule->passes($attribute, $value)) {
            $this->failedRules[$attribute][get_class($rule)] = [];

            $messages = (array) $rule->message();

            foreach ($messages as $message) {
                $this->messages->add($attribute, $this->makeReplacements(
                    $message, $attribute, get_class($rule), []
                ));
            }

        // here is where we do our magic
        } elseif ($rule instanceof RuleTransformsResult) {
            $newValue = $rule->transformResult($attribute, $value, $result);
            if($newValue !== $value) {
                Arr::set($this->data, $attribute, $result);
            }
        }
    }
}
```

Now we can write our own Boolean validator:

```php
class ValidBoolean implements Rule, RuleTransformsResult
{
    public static $validValuesMap = [
        '0' => false,
        '1' => true,
        'false' => false,
        'true' => true,
        'yes' => true,
        'no' => false,
    ];

    public function passes($attribute, $value)
    {
        if (is_bool($value)) {
            return true;
        }

        return array_key_exists((string) $value, self::$validValuesMap);
    }

    public function message()
    {
        return __('validation.boolean');
    }

    public function transformResult($attribute, $value)
    {
        return (bool) $value;
    }
}
```

Now we can always have a boolean as result:

```php
$data = ['isOk' => '1'];
$result = $this->validate($data, ['isOk' => [new ValidBoolean()]);

if($result['isOk'] === true){
   // yeah we will make it here.
}
```
Short Circuiting JavaScript
Tags: javascript, webdev, development, frontend
Published: 2020-05-15 15:43:10

---
title: Short Circuiting JavaScript
published: true
description: A while back, I came across a pattern that became very useful. It allowed me to cleanly determine if a diagnostic mode was on and log information to the console.
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/aued80i75dpr8uyca12f.png
tags: JavaScript, WebDev, Development, Front-End
---

A while back, I came across a pattern that became very useful. It allowed me to cleanly determine if a diagnostic mode was on and log information to the console.

It's a pretty pattern ... and logical. It also causes me some grief at times.

## The Pattern

Here's the code.

```javascript
// isDebug state will allow the console.log fire, if true
let isDebug = false;

// here is the conditional
(isDebug) && console.log('debugging this code', { isDebug });
```

This seems pretty cool, and I think it is.

Basically, if `isDebug` is ...

* `true`, the `&&` (and) forces the code on the right to execute ... `console.log`.
* `false`, the `&&` (and) logic in JavaScript does not attempt to execute the code on the right ... no `console.log`.

## And More

Then, this was suggested to me ... a similar pattern.

```javascript
let counts = {};

data.forEach(i => {
  // more code here
  (i.name in counts) || (counts[i.name] = 0);
  counts[i.name]++;
  });
```

Basically, this code is using similar logic to the `isDebug` logic above.

* If the name is in the object `counts`, then move to the next line and add one.
* If the name is NOT in the object `counts`, then add the key with an initial value of zero which then gets incremented by one on the next line.

With [jshint.com](), we get "Expected an assignment or function call and instead saw an expression." on the two lines in question here.

Looking for more detail, I found [this documentation on why this issue is raised](http://linterrors.com/js/expected-an-assignment-or-function-call) ... reading this, the issue is raised for the left-hand portion of the code in question, totally ignoring the potential of the code on the right-hand side.

Going even further, I found [this documentation](https://eslint.org/docs/2.0.0/rules/no-unused-expressions) that showed this pattern as a "Short Circuit" and, if needed, `allowShortCircuit` is an option for the linter.

## Conclusion

This is an interesting, terse pattern that seems to have gained some traction: Using an expression to determine which branch to follow in (or **short circuit out of) the code.

I will say, that on a personal level, I like the first pattern for conditional diagnostic information while the second pattern felt awkward, but readable.
Is the DEV yaml frontmatter broken or changed?
Tags: meta
Published: 2020-05-15 15:39:44

I often opt for using the yaml frontmatter of dev rather than the UI as it is easier to replicate from other posts in a similar series.  Today I copied one, hit `write a post` and it did not pick up my frontmatter and told me I couldn't save without a title.

``` markdown
---
title: What Did You Learn This Week --May 15?
tags: todayilearned, discuss
cover_image: https://res.cloudinary.com/practicaldev/image/fetch/s--TpOOUw4B--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/i/67bb72156h4y13zl5cio.png
series: this-week-i-learned
---
```

Is this a bug?  Am I doing something wrong?  Was there a change to how you use yaml frontmatter, it clearly still works on my old posts?


## Update

_This is what I see when I post how I used to._

![Unable to make post with yaml frontmatter](https://dev-to-uploads.s3.amazonaws.com/i/mfbb08vjl05lzztqzd7g.png)
Top 10 Trending Technologies
Tags: technology, trending, top10
Published: 2020-05-15 15:23:02

This applies to your professional life as well. Up-grading yourself is a need nowadays, the reason is pretty simple, technologies are evolving very quickly.

So I have listed the <a href="https://onlinetutorials.tech/top-10-trending-technologies/" target="_blank">top 10 trending technologies</a>, which are expected to acquire a huge market.

Artificial Intelligence
Blockchain
Augmented Reality and Virtual Reality
Cognitive Cloud Computing
Angular and React
DevOps
Internet of Things (IoT)
Intelligent Apps (I – Apps)
Big Data
RPA (Robotic Process Automations

Learn more about above technology by visiting <a href="https://onlinetutorials.tech/top-10-trending-technologies/" target="_blank">onlinetutorials.tech</a>
100daysofcode Flutter
Tags: 100daysofcode, flutter
Published: 2020-05-15 15:19:52

day 67/100 of #100daysofcode #Flutter
Learning Flutter , courses Udemy from
@maxedapps

 Today learn about shared preference, setString, pref.clear, remove, set as Map , clear about auth section
https://github.com/triyono777/100-days-of-code/blob/master/log.md
Bubble Sort in Java with Example
Tags: java, bubblesort, algorithms, sorting
Published: 2020-05-15 15:14:00

We will create Java program which will sort <a href="https://onlinetutorials.tech/category/java-tutorials-online-tutorials/" target="_blank">Java</a> array, <a href="https://onlinetutorials.tech/bubble-sort-in-java-with-example" target="_blank">Bubble sort</a> is one of the simplest algorithm.
Basically In bubble sort we travel through all the elements starting from 0th (zeroth) index to n-1(last) index. while traversing through these elements we also perform comparison (compared with adjacent element) and perform swapping (if current element is greater).
<a href="https://onlinetutorials.tech/bubble-sort-in-java-with-example" target="_blank">Let’s see the complexity of Bubble sort algorithm and it’s example in detail.</a>
Simple Fetch API wrapper that addresses its annoyances and makes it enjoyable to use 
Tags: javascript, github, npm, fetch
Published: 2020-05-15 14:58:16

`Fetch API` is an improvement in many ways from xhr (though it is missing upload progress), but it's extremely inconsistent at times and isn't the most enjoyable to use.

`FarFetch` was created to address these issues. Check it out here: https://github.com/WebsiteBeaver/far-fetch. Here's a simple example to show how much more consistent passing in data to the request is in `FarFetch`, compared to vanilla JS `Fetch API`.

**Fetch API**

```js
// GET
async getPerson() {
  const data = { name: 'Jessica', gender: 'f', age: 25 };

  const queryString = `?${new URLSearchParams(Object.entries(data))}`;

  const response = await fetch(`https://example.com/people${queryString}`, {
    method: 'GET',
  });

  if(response.status !== 200) throw new Error('Server error.');

  return response.json();
}

// POST
async addPerson() {
  const data = { name: 'Jessica', gender: 'f', age: 25 };

  const response = await fetch(`https://example.com/people`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });

  if(response.status !== 200) throw new Error('Server error.');

  return response.json();
}

// application/x-www-form-urlencoded
async addPerson() {
  const data = { name: 'Jessica', gender: 'f', age: 25 };

  const response = await fetch(`https://example.com/people`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams(Object.entries(data)),
  });

  if(!response.ok) throw new Error('Server error.');

  return response.json();
}
```

**FarFetch**

```js
// GET
async getPerson() {
  const { responseJSON } = await ff.get('https://example.com/people', {
    data: { name: 'Jessica', gender: 'f', age: 25 },
  });

  return responseJSON;
}

// POST
async addPerson() {
  const { responseJSON } = await ff.post('https://example.com/people', {
    data: { name: 'Jessica', gender: 'f', age: 25 },
  });

  return responseJSON;
}

// application/x-www-form-urlencoded
async addPerson() {
  const { responseJSON } = await ff.post('https://example.com/people', {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    data: { name: 'Jessica', gender: 'f', age: 25 },
  });

  return responseJSON;
}
```

Consistency and readable is one of many nice features of `FarFetch`, along with like simplified uploading, error handling and before/after hooks.
Alternative to backend services for a contact form in Static pages
Tags: webdev
Published: 2020-05-15 14:54:08

Nowadays, Even basic project as creating a simple portfolio may involve some problems, like receiving data from contact form.
There are many ways to read those data. You can connect your form with the database but it may be some troublesome for beginners.
 
So there are some services which can help you out
<ul>
<li><a href="https://formsubmit.co/">FormSubmit</a></li><li><a href="https://formspree.io/">Formspree</a></li>
</ul>
You can signup to any of these (free) services and configuration is damn simple, there are bunch of others services too.

I even used formspree service for my <a href="https://aletisunil.github.io/">portfolio</a> page 
Give it a try !!
Hope it's useful
A ❤️ would be Awesome 😊