teleren/devto huggingface dataset:
Code Smell 36 - Switch/case/elseif/else/if statements
Tags: oop, webdev, tutorial, codenewbie
Published: 2020-11-28 14:09:17

*First programming lesson: Control structures. Senior developer lesson: avoid them.*

Problems:
- Too many decisions together

- Coupling

- Duplicated code

- Violation of [Open/Closed Principle](https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle).

- A new condition should not change the main algorithm.

- Nulls

# Solutions

1. Polymorphism

2. Create hierarchies/compose objects following *Open closed principle*.

3. Use [State pattern](https://en.wikipedia.org/wiki/State_pattern) to model transitions.

4. Use [Strategy Pattern](https://en.wikipedia.org/wiki/Strategy_pattern)/[Method Object](https://wiki.c2.com/?MethodObject) to choose for branches.

# Examples

- Discrete Values

- State transition

- Algorithm choice.

# Sample Code

## Wrong

{% gist https://gist.github.com/mcsee/fd1c07ce153817a5572cb3cb84ae1007 %}

## Right

{% gist https://gist.github.com/mcsee/ef02daf9882bbf6a6f12820b31e19920 %}

# Detection

Since there are [valid cases](https://maximilianocontieri.com/how-to-get-rid-of-annoying-ifs-forever) for If/else usages, we should not pull the plug and forbid these instructions. We can put a ratio of if statements/other statements as a warning instead.  

# Relations

{% post https://dev.to/mcsee/code-smell-12-null-la4 %}

# More info

{% post https://dev.to/mcsee/how-to-get-rid-of-annoying-ifs-forever-1jfg %}

# Credits

Photo by <a href="https://unsplash.com/@akummur">Adarsh Kummur</a> on <a href="https://unsplash.com/s/photos/tree">Unsplash</a>

> If debugging is the process of removing software bugs, then programming must be the process of putting them in.

_Edsger Dijkstra_
Possible Error when we have both javac 11.0.9.1 and javac 8
Tags: java, programming, discuss, help
Published: 2020-11-28 14:08:02

I usually uses Eclipse and online editors to run my java programs. But yesterday, I took my sublime editor, write a simple java program, data structure model and run the program using the javac command in command line.

`javac filename.java`

But first it shows I am not having javac and need to install using `sudo apt ...` command as shown in the screen.

I ran it and installed the javac and when I checked, it was javac 11 version. So I included the javac 8 while again installing the javac to get version 8, still the version shows 11.

So I just leave it and compiled the program. It compiled succesfully, but it couldn't run and shows a message.(![1](https://dev-to-uploads.s3.amazonaws.com/i/9lzndtji135b6zt370bx.png)
 )

So I searched for the error and found a possible fix for it. 
We can use the following command to successfully compile and run the code in javac 8.
`javac -target 8 -source 8 filename.java`
`java filename`

But it shows a warning which I am not that much familiar and not that much understandable.
The warning is as follows:
`warning: [options] bootstrap class path not set in conjunction with -source 8
1 warning
`

I don't know what exactly its saying but I got my code compiled and run successfully.
So the above command is one of the fix that can be used to fix the above error, if anyone faces it.

More discussion about the warning is most welcome and I am very much excited to know what's exactly the warning is.

Thank You
Simple React fade animation hook
Tags: react, animation, hook
Published: 2020-11-28 14:06:00

Hey you! Yea you! Do you need a quick and simple fade animation on your React component? Don't feel like installing a library? 
Then let's go! 💨💨💨

{% codesandbox 3gjkn %}

# Show me the code already! 👀
The hook returns `[isVisible, setVisible, fadeProps]`, just like `useState()` hook, but you also need to set the `fadeProps` on the element you want to fade.

```jsx
const MyFadingComponent = () => {
	// Just like useState() hook, the fadeProps go on the fading DOM element
	const [isVisible, setVisible, fadeProps] = useFade();

	// You can use isVisible to mount/unmount the component!
	return <>
		<button onClick={() => setVisible(!isVisible)}>Toggle visibility</button>
		{isVisible && <h2 {...fadeProps}>Now you see me...</h2>}
	</>;
};
```

# And the hook! 🎣
It uses `onAnimationEnd` to delay setting the `isVisible` state to `false`, which allows the animation to finish before the component unmounts!
```jsx
const useFade = (initial) => {
	const [show, setShow] = useState(initial);
	const [isVisible, setVisible] = useState(show);

	// Update visibility when show changes
	useEffect(() => {
		if (show) setVisible(true);
	}, [show]);

	// When the animation finishes, set visibility to false
	const onAnimationEnd = () => {
		if (!show) setVisible(false);
	};

	const style = { animation: `${show ? "fadeIn" : "fadeOut"} .3s` };

	// These props go on the fading DOM element
	const fadeProps = {
		style,
		onAnimationEnd
	};

	return [isVisible, setShow, fadeProps];
};
```

# Styles 💅

```css
@keyframes fadeIn {
	0% { opacity: 0; }
	100% { opacity: 1; }
}

@keyframes fadeOut {
	0% { opacity: 1; }
	100% { opacity: 0; }
}
```

# What's the point? 🙄
If we would use the `useState()` hook and then apply the state with an expression like `isVisible && <Component />`, our component will unmount before the CSS animation has finished, which is not what we want! The `useFade()` hook delays unmounting until the animation is finished.

# What's cool about this? 😎
The syntax is just like `useState()`, you can simply use an `isVisible && <Component />` expression to mount/unmount the component. 

Here's how you do it with [React Transition Group](https://codesandbox.io/s/thirsty-pasteur-m77l2vp00x?from-embed), you need a wrapper component and wire the enter/exit animation to the state yourself, yuck! [Framer Motion](https://codesandbox.io/s/fade-between-pages-2d7y7) and [React Spring](https://www.react-spring.io/docs/hooks/use-transition) are similar.

# Room for improvement (please help!)
Toggling between two elements does not really work at the moment:
```jsx
const [isVisible, setVisible, fromProps, toProps] = useFade();

{isVisible ? <ComponentA {...fromProps} /> : <ComponentB {...toProps} />}
```

I'm trying to pass the opposite fade animation to `ComponentB`, but can't figure out how to get it right. If you have an idea, let me know!

{% codesandbox 3gjkn module=/src/Example2.js initialpath=/example2 %}
Go - aws-sdk-go/service Unit Test
Tags: aws, go, testing
Published: 2020-11-26 17:22:42

Here is sample codes for the unit test of aws-sdk services.

In the case of DynamoDB.

```go
package repository

import (
	"context"
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
	// ...
)

// SDK wrapper interface, which can be able to unit test.
type DynamoDbWrapper interface {
	// Define the same as SDK.
	Query(input *dynamodb.QueryInput) (*dynamodb.QueryOutput, error)

	// Define, if it needs more.
	// ...     
}

// Default implementation.
// Use this if the argument of "NewDynamoDbRepository" is not passed.
type DynamoDbWrapperAdapter struct {
	svc *dynamodb.DynamoDB
}

// Dispatch simply.
func (d *DynamoDbWrapperAdapter) Query(input *dynamodb.QueryInput) (*dynamodb.QueryOutput, error) {
	return d.svc.Query(input)
}

// Set wrp to null. In case unit test, set mock interface.
func NewDynamoDbRepository(wrp DynamoDbWrapper) updatetimerevent.Repository {
	if wrp == nil {
		wrp = &DynamoDbWrapperAdapter{
			svc: dynamodb.New(session.New()),
		}
	}
	return &DynamoDbRepository{
		wrp: wrp,
	}
}

// Find something.
func (r *DynamoDbRepository) FindSome(ctx context.Context, userId string) (some *SomeStruct, err error) {
	input := &dynamodb.QueryInput{
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":userid": {
				S: aws.String(userId),
			},
		},
		KeyConditionExpression: aws.String("UserId = :userid"),
		TableName:              aws.String("DYNAMODB_TABLE"),
	}

	// Call mock method, if r.wrp is set mock.
	result, err := r.wrp.Query(input)
	if err != nil {
		return
	}
	// ...
}
```

**Test code**

```go
t.Run("ok:Query", func(t *testing.T) {
	caseUserId := "test user"
	caseInput := &dynamodb.QueryInput{
		ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
			":userid": {
				S: aws.String(caseUserId),
			},
		},
		KeyConditionExpression: aws.String("UserId = :userid"),
		TableName:              aws.String("DYNAMODB_TABLE"),
	}
	caseItem := &dynamodb.QueryOutput{
		Items: []map[string]*dynamodb.AttributeValue{},
	}

	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	s := NewMockDynamoDbWrapper(ctrl)
	s.EXPECT().Query(gomock.Eq(caseInput)).Return(caseItem, nil)

	repo := NewDynamoDbRepository(s)
	got, err := repo.FindSome(context.TODO(), caseUserId)
	assert.NoError(t, err)
    // assert...
})
```
Life update: Freelancing, Selling a project & joining a company
Tags: javascript, webdev, programming, career
Published: 2020-11-28 13:53:10

So I have been away from dev.to, social media and basically off the internet for like 6 months. A lot happened during this time.

I was burnt out from work stress, as I have been constantly working from past 4 years as a web developer, handling it was quite difficult for me and I literally quit my job, took a long break and I eventually sold one of my weekend project [appydev](https://appydev.co).

I had literally no idea on what exactly I was supposed to do next, I decided not to go back stressing about this again, since I had earned some money from the website acquisition, I had some money for rent and living.

One good thing about being a web developer is there will always be someone who needs something built on the internet, I did not plan on it but I started taking large freelancing projects. 

I made quite a few E commerce websites, a lot of people were trying to go online with the businesses due to the pandemic. Was working my own hours, earning decent money, not as much as a full time developer but it was a very good experience, I handled clients, assigning working hours to projects and a lot of other things, it taught me a lot. 

I even got time to revamp my portfolio site, [go check it out](https://fayazz.co?ref=devarticle).

I was getting offers from multiple companies to join their organisations, but I kept declining it, I need a break honestly.

After 4 months of freelancing and consulting, I finally accepted an offer from a company, I have joined as a fullstack software engineer. 

## What made me join their organisation?
1. I get to work on the tech stack I love and I am comfortable with -  Nuxt.js, Tailwindcss, Node.js, Express
2. They're remaking their entire project from scratch using all the modern technologies, I get to learn a lot.
3. Some extremely talented people in the team. 
4. No leave policies, No concept of shift timings, I can literally stop working at 3 pm, If I do not have any work for the day, they actually encourage you to do this.

So, back to writing, I miss writing on the dev.to platform, and I plan to write more and it feels good to be back.
How to create a Queue  using javascript
Tags: javascript, tutorial, beginners
Published: 2020-11-28 13:27:57

JavaScript comes with some out of the box data structures. This includes Arrays and objects. Linked List, graphs, trees, queues, and stacks are not included with JavaScript. These data structures need to be constructed using a class. The data structures mention are important to know since different data structures excel at storing and retrieving data more efficiently than others depending on the scenario. Today we will be covering how to make a Queue. 

##**What is a Queue?**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/v5yb0qjckcm041ajyfc0.jpg)
A queue is a data structure that follows a simple rule. first-in, first-out, or FIFO. You can think of the queue as a line to the movies. The first person in line will buy the tickets first and get out of the line.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/h7s1m3s5stqz9d74oqal.png)
 A common use for this data structure is breadth first search. Breadth first search allows us to traverse a tree data structure by finding the shortest path.

##**What does a  Stack Contain and how to build it?** 

```javascript
class Queue{
    constructor(){
        this.data = []
    }
}
```

To get started building a queue we need to create a queue class and inside the constructor, the object will be initialized with an empty array( `this.data` ); 

###**Enqueue**

```javascript
    enqueue(value){
        this.data.push(value)
        return this; 
    }
```
The first instance method that will be covered is enqueue. Enqueue takes in a value as a parameter. Enqueue add items to the end of the array using push. Finally, return the instance of the class. 



###**Dequeue**

```javascript
    dequeue(){
        // Linked list would be more ideal here since shift in an array is an O(N) time complexity 
        const removedValue = this.data.shift();
        return removedValue; 
    }
```
The instance method dequeue removes values from the beginning of the array.  We will be using array building methods to remove a value from the end of the array. The shift()  method will be used.  Finally, the removed value is returned

###**Peek**

```javascript
    peek(){
        return this.data[0];
    }
```
The instance method peeks () returns the first value of an array

###**Empty**

```javascript
    empty(){
        return this.data.length === 0;
    }
```
Finally, the empty() instance method just returns true if there are any values in the stack or false if the stack is empty.

Queues are very simple to build using array methods and are used for traversing trees and graphs. I hope this gave you a bit of insight into what queues are and what they are used for.
Find the right Windows Server image for Azure Container Instances
Tags: azure
Published: 2020-11-28 13:22:16

<sub><span>Photo by <a href="https://unsplash.com/@fran_">Fran Jacquier</a> on <a href="https://unsplash.com/s/photos/lego">Unsplash</a></span></sub>

# The Issue

I need to generate OLE stream from File to embed them in a Word document. It seems easy using native DLL. But they are only present on Windows with desktop experience.

I tried to find a cheap way to run it in Azure, but:
- Azure Web App for Container, is too expensive when it comes to host Windows container
- [Azure Function with custom image](https://docs.microsoft.com/en-us/azure/app-service/quickstart-custom-container?pivots=container-windows), require a Premium Plan, which is too expensive
- Azure Container Instance (ACI), seems good

# Find the right image, for the right job

Ok, to deploy quickly on ACI, we need to have the tiniest possible image.
So we have to select carefully the image we put the code on.
[ACI can support](https://docs.microsoft.com/fr-fr/azure/container-instances/container-instances-faq#windows-server-2019-and-client-base-images-preview) 
- nanoserver
- windows server core
- windows

Obviously both nanoserver and windows server core do not have Windows experience.

So let's try a 2004 image of a Windows Server ([see the list of tag supported](https://hub.docker.com/_/microsoft-windows)).

Azure respond with the following error : **Error OsVersionNotSupported** .

# The Error

The error specify that the image is not supported.
Weird.
But, in fact ACI supports the Long Term Support version of Windows Server, no images based on [Semi Annual Channel](https://docs.microsoft.com/en-us/windows-server/get-started-19/servicing-channels-19#semi-annual-channel).

It means, that 2004, or 1909 images are not supported, but 1809 is.
It works, but the image is huge and takes 20 minutes at least to be deployed on a 1 CPU / 1 Go Memory container.



Hope this helps !
Happiness is a choice
Tags: todayilearned, todayisearched, mentalhealth
Published: 2020-11-28 13:13:51

{% twitter 1332672395681824768 %}

Today, I learned a point. At the extreme situation, you may still not get what you want. May be your code and mine still not working at the end of the day, may be there are still errors in our program, but thing is, I learned to be thankful at the end of the day. It's a choice.

I usually post some tweets about coding related and around spirituality, You can follow me at Twitter here [https://twitter.com/RicardoSawir](https://twitter.com/RicardoSawir)
Daily Developer Jokes - Saturday, Nov 28, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-11-28 13:00:29

---
title: "Daily Developer Jokes - Saturday, Nov 28, 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=Saturday%2C%20Nov%2028%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/5e1259b9b89f4.png)

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

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

<!-- 
Joke text:
___Q:___ What do you call optimistic front-end developers?

___A:___ Stack half-full developers.
 -->
Multilevel Feedback Queue Scheduling | Operating System - M02 P11
Tags: linux, beginners, devops, codenewbie
Published: 2020-11-28 12:53:41

**This is a multipart blog article series, and in this series I am going to explain you the concepts of operating system. This article series is divided into multiple modules and this is the second module which consists of 11 articles.**

_In this article we will see about the multilevel feedback queue scheduling, which is a solution for the multilevel queue scheduling._

### Multilevel feedback queue
- We use multilevel feedback queue, to overcome the problem that arrives in multilevel queue scheduling.
- In multilevel queue scheduling problem of **starvation** is present.
- Starvation in CPU scheduling means that, if multiple process of system process arrives than the processes of interactive process and batch process will not get executed.
- This is because in multilevel queue scheduling system process has highest priority, then interactive process has medium priority and batch process has least priority.
- So, when more number of processes of high priority will arrive then processes of other categories having low priority will not get executed, which is a problematic situation. 

<!-- Image will come here -->

![Untitled Diagram.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1606567818218/01TrhVuJb.png)
- Suppose we have a process P1 in the lowest priority ready queue.
- As it is in lowest priority ready queue its time quantum for which it can execute is very less.
- It will execute for that time period and then if it got terminated then it will be removed from the ready queue.
- If the process do not complete then its feedback will be given to the upper priority queue having more time quantum to execute a process, and then the process will get execute there.
- This will keep happening if the process does not get terminated.
- If the process not get terminated and arrive in highest priority ready queue, then there it will get executed by following the principle of _FCFS (First Come First Serve)_
- Giving feedback means that we are shifting the process from the lower priority ready queue to upper priority queue and that to by maintaining its state so we do not need to execute it from beginning, we do that by using _PCB (process control block)_.

_This was all about multilevel feedback queue. Hope you liked it and learn something new from it._

If you have any doubt, question query related to this topic or just want to share something with me, then please feel free to contact me. 

### 📱 Contact Me

[Twitter](https://twitter.com/r_mishra10),
[LinkedIn](https://www.linkedin.com/in/rahul-mishra-66210b185),
[Telegram](https://t.me/rahul_mishra10),
[Instagram](https://www.instagram.com/rahul_mishra10/?hl=en),

### 📧 Write a mail
<rahulmishra102000@gmail.com>

#### 🚀 Other links

[GitHub](https://github.com/rahulMishra05),
[HackerRank](https://www.hackerrank.com/rahulmishra10201)
#PureCSS - Responsive Ruby on Rails Logo
Tags: codepen, purecss, css, rails
Published: 2020-11-28 12:39:19

---
title: #PureCSS - Responsive Ruby on Rails Logo
published: true
tags: codepen,purecss,css,rails
---

<p>Pure CSS Responsive Ruby on Rails Logo</p>

{% codepen https://codepen.io/AsyrafHussin/pen/jOMEqMR %}
The Six Secrets of a Good Life
Tags: watercooler, life, skills, purpose
Published: 2020-11-28 12:24:41

---
title: The Six Secrets of a Good Life
published: true
description: The Six Secrets of Life by Rakesh Godhwani
tags: watercooler, life, skills, purpose
cover_image: https://mk0featuredanim65enk.kinstacdn.com/wp-content/uploads/2020/01/Kung-Fu-Panda-2-Po-and-warriors-reading-a-scroll.jpeg
---

👋 dev community,

I watched a YouTube [video](https://www.youtube.com/watch?v=e4Os0GGhEZg&t=825s) today by [Rakesh Godhwani](https://www.linkedin.com/in/rakeshgodhwani/?originalSubdomain=in) who is a faculty at [IIM Bangalore](https://en.wikipedia.org/wiki/Indian_Institute_of_Management_Bangalore), the top ranked business school in India. for over 12 years.

In the video, he goes on to share the six secrets to a good and meaningful life with examples from his favourite movies.

Here is the list for those of us too lazy to watch the whole video - 

1. Collect **knowledge**, not marks 💯
2. Collect **skills**, not degrees 🎓
3. Collect **friends**, not followers 🎎
4. Collect **health**, not wealth 💰
5. Collect **experiences**, not rewards 🏆
6. Collect your **purpose** in life, not your position and power 💪

I completely love this list. It focus on what is important in life and *what really matters*. 

It is not wrong to want everything in life, say both health and wealth, but yes the focus should be on health over wealth.

Please do watch the [video](https://www.youtube.com/watch?v=e4Os0GGhEZg&t=825s) if you get a chance, as he would explain these a lot better than this short list of points. 

Thanks for reading!