teleren/devto huggingface dataset:
It's never easy knowing when to use exception handling. In this post I explain a simple rule
Tags: article, exceptions, tips
Published: 2021-04-07 07:18:18

---
title: "It's never easy knowing when to use exception handling. In this post I explain a simple rule"
tags: Article, Exceptions, Tips
description: "If the record should have been in the database, then an exception can be raised. This is because something unexpected happened - a record that your program expected to find in the database was not found."
cover_image: https://faruknasir.com/images/blog/2021/refactor_using_exception.png
published: true
---

It is good practice to check for every possible errors - especially, the unexpected ones. This can push us to write code that is hard to read. The logic of your program can end up being totally obscured by error handling, particularly, if you subscribe to, <code>"a function must have a single return statement"</code> school of thought.

Let's examine the code snippet below:

<img class="blogimage" alt="If else nesting" src="https://faruknasir.com/images/blog/2021/if_else_nesting.png" />

Personally, I am not aware of any limitation to *if-else* nesting but, deep *nestings* could be an indication of terrible design. They could negatively impact readability which will make the job of the future maintainer a little bit more difficult.

With most modern programming languages, we can, easily, refactor the above code snippet using **exception** handling to increase readability:

<img class="blogimage" alt="refactor using exception" src="https://faruknasir.com/images/blog/2021/refactor_using_exception.png" />

The code is clearer with the main logic on one side and all the error handling moved to a single place. <code>But, my personal dilemma is the deciding factor of when wrapping a piece of code around a try and catch block is the right approach and when it isn't.</code>

### What is Exceptional?

<div class="blognote">
"Exceptions should rarely be used as part of a program's normal flow; exceptions should be reserved for unexpected events".
</div>

If your code tries to load a record from the database for some operations, and that record does not exist, should an exception be raised?

That depends on the expected behaviour. 

Always assume that an uncaught exception will terminate your program and then ask yourself, "Will the code still run if I removed the exception handler?". If "no", then, maybe, exceptions are being used in non-exceptional circumstances.

If the record should have been in the database, then an exception can be raised. This is because something unexpected happened - a record that your program expected to find in the database was not found.

On the other hand, if you are unsure whether the record should exist or not, then not finding it in the database is not exceptional - not an unexpected behaviour, and an error return is appropriate.

<blockquote>
This post first appeared on <a href="https://faruknasir.com">
https://faruknasir.com</a>
</blockquote>
How To Add Dark Mode To Your WordPress Website
Tags: wordpress, webdev
Published: 2021-04-07 06:54:12

We start with the Dark Mode plugin for WordPress, which allows you to activate the night mode on the WordPress Dashboard and Frontend. It’s easy to use and free.

The first thing you need to do is install and activate the [Droit Dark Mode plugin](https://wordpress.org/plugins/droit-dark-mode/). Upon activation, you need to visit the Settings > Droit Dark Mode Setting page and check the box “Enable Frontend Darkmode”, “Enable default Dark Mode” & “Enable backend Dark Mode” option.

![Dark Mode Dashboar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3ml6zbum4ooid766s9o.png)Don’t forget to click on the save changes button to store your settings. Your WordPress admin area and frontend will now switch to the night mode.

For instance, you just need to click the Display Settings tab to change the style of the floating switch:

![Dark Mode Dashboar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/50v94kxbtqpql5ggd0km.png)
You can also customize the dark mode colors using the Style in Preset Design tab:
![Dark Mode Dashboar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/phybh4jf4rii0vz5xst1.png)
Now, you can comfortably write and work on your website at night without straining your eyes.

Credit: [DroitThemes](https://droitthemes.com/droit-dark-mode/)
Best Way to take Backup of Gmail Emails
Tags: sotwsurvey, tooling
Published: 2021-04-07 06:51:56

We know that our Gmail Account contains all the important Business-related information and personal details.

Suppose, your emails are lost or hacked because we are listening that everything is going on digitally and faced CyberAttacks on Gmail Account, Social Media Accounts, Bank Account, etc.

To protect email data lost or hacked by the help of Gmail Email Backup Tool to take backup of Gmail emails in the form of different file formats such as MBOX, OST, PST, HTML, etc in the hard drive and also for further offline use.
You can easily download it from here to evaluate the performance of the tool you can use a free demo version for 50 emails for backup.
(https://www.arysontechnologies.com/gmail-backup/)
WWC MENTORSHIP -WEEK 1
Tags: computerscience, womenintech
Published: 2021-04-07 06:49:13

WWC aims at bridging the gender gap in the field of technology . They have started this mentorship series for the same reason , through this program they give women who are unacquanited but passionate about computer science , a chance to get mentored by some insane mentors who have done extremely well in the field of CS.

This year i had the chance to be a part of this mentorship program as a mentee . We were grouped in a team of 3, headed by a mentor. My mentor was Urvi Goel.

Urvi Goel is a pre-final year Computer Science student at IGDTUW. She was a 2020 summer intern at Microsoft IDC and has a returning offer from the same for 2021 summers.

Before the actual program began we were given a brief about the program and how it works.

Week 1 :
At the beginning of the week we had an intro session , we introduced ourselves , shared about our goals and interests. Since my aim was to get a summer internship i was given a task to gather all the upcoming internship opportunities .

In the middle of the week we had another session “chai session“, it was a very casual meet, we discussed about our doubts , future plans and opportunities.

At the end of the week we had to submit our task , following which we had a week concluding session .

The list of opportunities that i had gathered during my task :

1)Google codejam (feb) : Coding competition conducted by google .
2)Google codejam io for women(feb) : Coding competition conducted by google for women.
3)Adobe codiva (march): Prefinal and final year female students are eligible , there are 2 rounds for this hiring event .
4)Servicenow codediva ( march): Prefinal and final year female students are eligible , the first round is conducted on hackerearth following which a hackathon will be conducted.
5)Google kickstart ( registration starts in feb ): Coding competition conducted by google , it has 8 rounds.
6)Wintathon(nov): Hackathon for all female students in final and prefinal year.
7)Google step internship: For sophomores .
8)Women tech makers program: For freshmen year female students.
9)Microsoft Codess: For female sophomores of selected colleges.
10)Amazewow (april): Any female students are eligible .
11)Adobe she codes: For sophomores and juniors.
12)Goldmansach global mentoring program: For sophomores and juniors of selected universities .

Thanks for reading , will be back next week with another article on week-2 of women who code mentorship series :)
Easy way to create API documentation in Laravel
Tags: laravel, php, api
Published: 2021-04-07 06:41:44

For today's article, I want to illustrate how easy it is to create API documentation in Laravel.
We just created our first API, and know the importance of having good documentation.

The goal for today is to have a primary documentation endpoint, we won't add all the details, but I'll show you how to get started with it.

## Installing Scribe for Laravel

First of all, we need to install Scribe, the documentation generator we will use for Laravel 8.

```bash
composer require --dev knuckleswtf/scribe
```

Next up, we need to publish the vendor.

```bash
php artisan vendor:publish --provider="Knuckles\Scribe\ScribeServiceProvider" --tag=scribe-config
```

This will create a config file for Scribe that we can potentially use.

Next up is basically the step to generate our initial documentation.

```bash
php artisan scribe:generate
```

We should now be able to visit our documentation on:

```bash
localhost:port/docs/
```

You should see something similar to this.

![Laravel generated API doc](https://cdn.hashnode.com/res/hashnode/image/upload/v1617452610859/65FAMrbf0.png)

## Making our documentation better

For now, we didn't add much information. We can use the PHP Doc annotation to add information for each file.

Let's open up the `AuthenticationController.php` and check how we can make it better.

First of all, above our class annotation, we can add a general piece of information.

```php
/**
 * @group Authentication
 *
 * API endpoints for managing authentication
 */
class AuthController extends Controller
{
	// Functions
}
```

This will group all functions inside this file, as well as add a short description about it.

Now for the login function, we can add the following doc.

```php
/**
 * Log in the user.
 *
 * @bodyParam   email    string  required    The email of the  user.      Example: testuser@example.com
 * @bodyParam   password    string  required    The password of the  user.   Example: secret
 *
 * @response {
 *  "access_token": "eyJ0eXA...",
 *  "token_type": "Bearer",
 * }
 */
public function login(Request $request)
{
	// Code here
}
```

That's quite the piece. First, we name the function and state what parameters it's expecting and what the return looks like.

If we now generate our API doc, we should see the following.

![PHP doc in action](https://cdn.hashnode.com/res/hashnode/image/upload/v1617452887501/rcHDjWGr-.png)

Cool right! It shows exactly what's needed and what response a user can expect.

If you are interested in making your documentation optimal, check out Scribe's documentation on PHP doc.

[Read the scribe documentation](https://scribe.readthedocs.io/en/latest/documenting/index.html)

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
What Is React Native, Building With React Native
Tags: hashnodebootcamp, reactnative
Published: 2023-04-23 11:23:55

---
title: What Is React Native, Building With React Native
published: true
date: 2021-04-07 06:05:18 UTC
tags: hashnodebootcamp,ReactNative
canonical_url: https://chrisdevcode.hashnode.dev/what-is-react-native-building-with-react-native
---

## TL;DR

React Native - Simply an Open Source framework (React) used to create applications that run on multiple devices (Android, Web, iOS ...) using JavaScript.

[React Native Docs](https://reactnative.dev/)

To get started with React Native, it is advisable to have basic knowledge of javascript (es2015) and React components and props, just the basics of all these will set you ready.

Native Components: Components that can be used in iOS and Android devices.

Core Components: Ready to use React Native Components -

[native and core components](https://reactnative.dev/docs/intro-react-native-components)

[List of core components](https://reactnative.dev/docs/components-and-apis)

## React Native Developer Environment

[Docs](https://reactnative.dev/docs/environment-setup)
Introducing .iex.local.exs
Tags: elixir
Published: 2021-04-07 05:42:02

I love command-line interfaces! And, I like to customize my CLI experience as well. Either it being one-character-long aliases, utility functions, or just preloading some data into helper variables, my shell is always customized to some extend.

When I'm working with Elixir, I use IEx, which in turn allows you to customize itself through `.iex.exs` files. I truly love it! However, if I'm working on a team with other developers and they do like to do the same, we'll be in trouble. If this `.iex.exs` file is being controlled by Git, we'll both have the exact same customizations (and it won't be customizations anymore).

This week I wrote a solution that's so simple I decided to share.

## Behold `.iex.local.exs`!

OK, I'm being a bit extravagant here. 😂 The idea behind this `.iex.local.exs` file is: any team-wide IEx customization goes on `.iex.exs` directly (e.g.: customizations that you as a team agreed to use), and anything too personal to be team-wide goes on `.iex.local.exs`. Then, your `.iex.exs` file will end with the command below:

```rb
# Local dot-iex file (user/environment-specific, Git-ignored)
import_file_if_available(".iex.local.exs")
```

The file `.iex.local.exs` should be Git-ignored, so it will be entirely user/environment-specific. There you can create your own aliases, preload/prepopulate utility variables, provide utility functions, etc. You name it!

How about you? What have you been doing/using to be more productive in your work?
TIL Xbox UWP Basic Fixes
Tags: todayilearned, gamedev, unity3d, uwp
Published: 2021-04-07 05:31:11

2021-04-06

There are two basic issues when you output a Unity game to Xbox as a UWP application. The first one is the visible white edges (tv overscan) and the second one is the mouse pointer.

Most of the [official docs](https://docs.microsoft.com/en-us/windows/uwp/xbox-apps/tailoring-for-xbox) describes solutions for C# XAML but Unity only supports IL2CPP for UWP builds. 

To address this change, you need to edit `app.xaml.cpp` instead. 

```cpp
App::App()
{
    InitializeComponent();
    Application::Current->RequiresPointerMode = ApplicationRequiresPointerMode::WhenRequested; // mouse mode off
// 
void App::InitializeUnity(String^ args)
{
    ApplicationView::GetForCurrentView()->SuppressSystemOverlays = true;
    ApplicationView::GetForCurrentView()->SetDesiredBoundsMode(ApplicationViewBoundsMode::UseCoreWindow); // overscan fix
```
Introduction to Java 8 in Layman's terms - Functional Interface - Consumer Interface
Tags: java, webdev, functional, consumer
Published: 2021-04-07 05:10:30

Hi All !!!!

Want to learn about Java's Consumer functional interface then check the link below .....

https://praveen075.blogspot.com/2021/04/introduction-to-java-8-in-laymans-terms_6.html
Setting up Blazor with Tailwindcss
Tags: blazor, tailwindcss, dotnet
Published: 2021-04-07 05:05:58

So, you decided that you want to try Blazor... Then you decided that you want to try Blazor with Tailwind. This mix of tech is what I like to call WindBlazor.

One of the first things you need to do is get all this junk setup. It's not that hard, I was able to do it in about an hour the first time.

Then I created a repo with the resulting files and made a Github Template out of them. So yes, it took an hour but that was just the one time. Each time I start a new project from now on all I have to do is clone my repo:

- https://github.com/denvercoder/windblazor.git

Now Chris Sainty already wrote a really good post on how to integrate Tailwind into Blazor. You can find it here:

- https://chrissainty.com/integrating-tailwind-css-with-blazor-using-gulp-part-1/

Chris' article is great but in my opinion he left out a few steps to **really** get you squared away.

First of all he doesn't talk about getting a watch to work.

You can run `dotnet watch run` from the **server** project but that only watches server files. If you want it to watch frontend files you have to add a few things.

You'll want to look in your `Server.csproj` file and create an new `ItemGroup` like so:

```
  <ItemGroup>
    <Watch Include="..\Client\**\*.razor" />
  </ItemGroup>
```

I got the above tidbit from Patrick God.

Now what that will do is the server project will now watch Server files but it will also watch any razor files. When you add:

`class="text-red-500 p6"`

and then save the file, `dotnet watch run` will recompile the app and then refresh your browser so you can see the result.

Thanks for reading and that's all y'all.
JavaScript some and every method
Tags: javascript, arrays, tips, snippets
Published: 2021-04-07 04:11:31

Both some and every method is used to test whether or not elements are present in the array. <br>
In this article, we are going to look at the differences between **some** and **every** method

## some()

```javascript
  const words = ["cat","be","danger", "dog","log","bag","wag"]; 

  words.some(word => word.length ===3); //true
```
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a **Boolean value**.
<br>
In the above example, the word array contains certain words. Each word has a length greater than or equal to two. In the above some() method we are checking if any word has length three or not. It returns the Boolean value **true** if any of the lengths of the words is three, otherwise, it returns **false**.

---

## every()

```javascript
   const words = ["dog", "dig","log","bag","wag"];
   words.every(word => word.length ===3); //true
```
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
<br>
In the above example, the word array contains certain words. Each word has a length greater than or equal to two. In the above every() method we are checking if any word has length three or not. It returns the Boolean value **true** if any of the lengths of the words is three, otherwise, it returns **false**.

**Then what is the difference between some() and every()**

```javascript
  const words = ["dog", "dig","log","ba","wag"];
  words.every(word => word.length ===3); //false
```
In the above example, In the above every() method we are checking if any word has length three or not. It returned false because every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. so it returned **false**

**Thank you for reading the article**
Tip for making good reusable components - React TS
Tags: react, typescript, webdev
Published: 2021-04-07 03:51:31

When we are coding an app, most of the time we have a button or an input component in our components directory to reuse across the entire application. And what makes them reusable are their props.

One thing that I found really useful is to add at the end of destructuring the props an spread. With that I could pass different attributes for the specific html tag (button, input, etc).

```javascript
const Button = ({x, y, …restProps}) => {
	return <button {…restProps}>btn</button>
}
```

And good news are that there is someway of doing with types.

JSX.IntrinsicElements[] accepts an array of strings with the tag elements and we get the typed attributes.

```typescript
type DefaultInputProps = JSX.IntrinsicElements['input'];
```

Nice. And we could extend them with the props types from our component.

And in the case that we want to replace the default types of certain properties because we are going to apply ours, we just omit them with the utility type Omit.

```typescript
import { ChangeEvent, RefObject } from 'react';

type DefaultInputProps = Omit<JSX.IntrinsicElements['input'],
	'name' | 'label' | 'value' | 'placeHolder'
>;

export interface InputProps extends DefaultInputProps {
	name?: string;
	label?: string;
	handleChange: (e: ChangeEvent<HTMLInputElement>) => void;
	value?: string;
	placeHolder?: string;
	ref?: ((instance: HTMLInputElement) => void) | RefObject<HTMLInputElement>
}
```

Since the idea of this components is that they don’t handle their logic and state, they mostly will receive as props these properties.
Youtube Clone
Tags: react, redux, javascript, stripe
Published: 2021-04-07 03:39:13

This is the youtube clone which I did from the sonny sanga tutorials in youtube, The tutorial was good ,I have learnt many things also it includes Redux for the state management with stripe.

 I have added my own touch to build by adding the youtube trailer link for the movies & the stripe button with node server for stripe payments.

Please find below how I have added stripe & trailer feature for netflix clone

link to the project- https://netfllicclonne.herokuapp.com/

##How I added stripe button 

1. Install react-stripe-checkout from npm
2. In client code add following code
<code>
   ` import React from 'react';
    import StripeCheckout from 'react-stripe-checkout';
    import axios from 'axios';

    const StripeCheckoutButton = ({ price }) => {
    const priceForStripe = price * 100;
    const publishableKey =****;

    const onToken = token => { 
     axios({
       url: 'payment',
       method: 'post',
       data: {
        amount: priceForStripe,
        token: token
       }
      })
      .then(response => {
        alert('succesful payment');
      })
      .catch(error => {
        console.log('Payment Error: ', error);
        alert(
          'There was an issue with your payment! Please make sure 
     you use the provided credit card.'
        );
      });
    };

  return (
    <StripeCheckout
      label='subscribe'
      name='Netflix-clone'
      billingAddress
      shippingAddress
      
image='https://assets.stickpng.com/images/580b57fcd9996e24bc43c529.png'
      description={`Your total is $${price}`}
      amount={priceForStripe}
      panelLabel='Pay Now'
      token={onToken}
      stripeKey={publishableKey}
    />
  );
};

export default StripeCheckoutButton `

</code>

3.Add an node server to run/open the stripe popup when hit /payment route

<code>

` app.post("/payment", (req, res) => {
  console.log("inpayment");
  const body = {
    source: req.body.token.id,
    amount: req.body.amount,
    description: "test description",
    currency: "INR",
  };

  stripe.charges.create(body, (stripeErr, stripeRes) => {
    if (stripeErr) {
      console.log("abc", stripeErr);
      res.status(500).send({ error: stripeErr });
    } else {
      console.log("abc2");

      res.status(200).send({ success: stripeRes });
     }
     }) `

</code>


4.Voila!! your stripe payment is ready 

### How To integrate Tmdb api with youtube-trailer 

1.install movie-trailer & react-youtube from npm

2.Then fetch trailers id from the below link replace **movie.id** by id of the movie,that  trailer to be fetched https://api.themoviedb.org/3/movie/${movie.id}/videos?api_key=9d2bff12ed955c7f1f74b83187f188ae

3.store the key value from the results fetched from before ,& send it as trailer prop
<code>
   `<Youtube videoId={trailer} opts={
    height : "390",
    width : "100%",
    playerVars : {
        autoplay:1,
    }}/>`

</code>

4.Now you have working trailer popup for the movies



please do share your feedback on this blog
Thanks for your time :)
How I created biased dice.
Tags: html, algorithms, javascript, webdev
Published: 2021-04-07 03:27:36

---
title: How I created biased dice.
published: true
description: MakeMyTrip Interview Question to created a biased dice where the probability of getting an even number is more.
tags: HTML, Algorithm, javascript, webDevelopment
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0hl5w7vmj1udkyfzfix.png
---
Can you create biased dice where the probability of getting an even number is more?

The question was asked in MakeMyTrip interview.

A dice has 6 states : {1, 2, 3, 4, 5, 6} and the problem is P{2, 4, 6} > P{1, 3, 5}.

Can you **create a mathematical function** to solve this problem without hampering the dice randomness?

Follow up the below video lineups to find the solution or comment down your approach how you will solve it

```
int function DiceMoves() {

    // your code here

    return diceState;

}
```

Watch my videos on the same:

{% youtube fdWEWPYJlE0 %}
{% youtube ln8Qoo_MYwo %}
{% youtube pRNa9KhG_DY %}

Please like share and subscribe if love my videos.

My solution code at:

{% github salRoid/Random-Dice-Moves %}