teleren/devto huggingface dataset:
Why explicit return type is a good thing
Tags: typescript, webdev
Published: 2022-09-06 07:06:48

Back when I was just starting with TypeScript, I used to neglect the value of declaring an explicit return type for my functions. Why bother specifying it when there is type inference and IntelliSense, right? Well, I was very wrong.

Turns out that its main benefit is actually _not_ to whomever might call my function, but rather to whomever might edit my function in the future. Here's why...

Imagine I have this function:

```typescript
function getAge(person: Person) {
  return calculateAge(person.birthdate);
}
```

This is all good, as obviously it returns a `number`, and IntelliSense tells me that, too. But then later on, someone edits my function to add a guard condition as follows:

```typescript
function getAge(person: Person) {
  if (person.birthdate === undefined) return null;

  return calculateAge(person.birthdate);
}
```

This won't trigger a TS error at this function, but now the inferred return type has become `number | null`, which is clearly different from the original intention. Now we have introduced, possibly unintentionally, a breaking change.

Now imagine if I have specified a return type in the first place, as follows:

```typescript
function getAge(person: Person): number {
  // . . .
}
```

then my team mate would have known from the start what can and can't be changed in the implementation without making a breaking change.
What do you think about providing Cypress and RTL selector and assertion functions alongside your components?
Tags: react, cypress, testing
Published: 2022-09-06 07:05:39

Here's an idea I've just started toying with. 

So in my project the folder structure for any given component looks like this: 

```
/MyComponent
   MyComponent.tsx - The actual component
   MyComponent.stories.tsx - Storybook stories
   MyComponent.test.tsx - RTL tests. 

```

Fairly straight forward. 

Something I've been running into recently, particularly with writing Cypress tests, is that often writing either interactions with my components (eg. click the button, select an item from the autocomplete) or assertions on them (eg. the multiselect contains value 'foo') has quite a lot friction. I'm often going into the RTL test and seeing what I've done there, and copying an modifying it. 

Now I know that Testing Libraries whole philosophy is 'write tests in the way that a user would interact with the application' - but it's often not that straightforward, or it's a bit tedious. 

So what I've considered is two more files along side the others; 

```
MyComponent.rtl-selectors.ts
MyComponent.cypress-selectors.ts
```

These would contains functions like: 

```
function selectItemInMultiSelect(label: string, itemName: string) //...

function assertMultiSelectContainsItem(label: string, itemName; string) //... 
```

And the idea is, you could import these functions in your RTL/Cypress tests to assist with interactions. 

Has anyone tried such a thing, and how did it go?
How To Include ‘bits/stdc++.h’ Header File With Clang Compiler on macOS
Tags: clang, cpp, macos
Published: 2022-09-06 06:59:17

I have written a comprehensive article on how you can use the infamous `bits/stdc++.h` header file with Clang compiler in the same way as you would use any standard header file. Please give it a read. 
[Link to Medium Article](https://justvikram.medium.com/how-to-include-bits-stdc-h-header-file-with-clang-compiler-on-macos-4ed52a9f80f5)

**TLDR**
Download the [linked file](https://dropover.cloud/b831d6). Go to `/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1` and copy the downloaded file to that directory. You can start using `#include <stdcpp.h>` in your projects instead of manually including all required header files.
Hyperrrrr-linx (sp?) ;D
Published: 2022-09-06 06:49:37

Google docs and sheets just automatically makes hyperlinks when you enter a URL. Well, apparently html creates hyperlinks with an anchor tag (`<a>`) and an href attribute, which is required.

Remember how images use the relative or the absolute URLs? Well, heheh... yup, hyperlinks can use either too. If the hyperlink uses to a webpage on our own website, then we would use the relative URL. If it leads to a different website (not within the server file containing our website, which is most likely the case if it's a different website), we would use the absolute URL. To remind you, relative URLs are made up of the file path that leads to the webpage file within the enclosing website's server file. Relative URLs usually start with the file name, and Absolute URLs typically start with `https://www.[__].com`

#####Example Time!
#####Here is the code as written:

```
<a href="https://www.boredpanda.com/cat-virus-exe-funny-pics/?utm_source=google&utm_medium=organic&utm_campaign=organic">When kittehs strike!</a>
```

#####And, here is the code as I intend the user to view it:

<a href="https://www.boredpanda.com/cat-virus-exe-funny-pics/?utm_source=google&utm_medium=organic&utm_campaign=organic">When kittehs strike!</a>

######Disclaimer: no code was harmed in the making of this blog post. Also, markdown apparently creates a hyperlink just from entering the URL, hence the "codified" URL above, near the top.
Install Preact with Typescript using Vite
Tags: preact, typescript, vite, webdev
Published: 2022-09-06 06:43:21

In section we will install preactjs with typescript using vite tool. Vite is modern build tool which provide faster development experience. Fast 3kB alternative to React with the same modern API.

**PreactJS Features**

1.Familiar React API & patterns: ES6 Class, hooks, and Functional Components

2.Extensive React compatibility via a simple preact/compat alias

3.Everything you need: JSX, VDOM, DevTools, HMR, SSR.

4.Highly optimized diff algorithm and seamless hydration from Server Side Rendering

5.Supports all modern browsers and IE11

6.Transparent asynchronous rendering with a pluggable scheduler

7.Instant production-grade app setup with Preact CLI

### Create Vite Project For Preact
Install vite via npm:
```sh
npm create vite@latest
```
Install vite via yarn:
```sh
yarn create vite
```
Select preact project
```react
✔ Project name: … preact-vite
? Select a framework: › - Use arrow-keys. Return to submit.
  vanilla
  vue
  react
❯  preact
  lit
  svelte
```
Next Select preact with typescript
```react
✔ Project name: … preact-vite
✔ Select a framework: › preact
? Select a variant: › - Use arrow-keys. Return to submit.
  preact
❯  preact-ts
```
Now move to project directory and install & run npm:
```sh
cd preact-vite
npm install
npm run dev
```
_src/app.tsx_
```react
import { useState } from 'preact/hooks'
import preactLogo from './assets/preact.svg'
import './app.css'

export function App() {
  const [count, setCount] = useState(0)

  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src="/vite.svg" class="logo" alt="Vite logo" />
        </a>
        <a href="https://preactjs.com" target="_blank">
          <img src={preactLogo} class="logo preact" alt="Preact logo" />
        </a>
      </div>
      <h1>Vite + Preact + TypeScript</h1>
      <div class="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/app.tsx</code> and save to test HMR
        </p>
      </div>
      <p class="read-the-docs">
        Click on the Vite and Preact logos to learn more
      </p>
    </>
  )
}
```
![preact with typescript using vite tool](https://demo.larainfo.com/screenshot/tailwindcss/preact-with-typescript-using-vite.png)
Strategy Pattern in Go
Tags: go, designpattern
Published: 2022-09-06 06:39:05

Imagine you have to build a program that simulates birds.

There can be different type of birds with different flying behaviours.

A parrot that flies low , an eagle that flies high and ostrich which doesn’t fly at all

We will start with Bird interface.

```go
// Interface
type Bird interface {
    Fly()
    Display()
}
```

So anything that implements Fly() and Display() is a Bird.

A parrot

```go
type Parrot struct {
    color string
}

func (p *Parrot) Fly() {
    fmt.Println("I can fly")
}

func (p *Parrot) Display() {
    fmt.Printf("I am a Parrot . I have color =%s", p.color)
}
```

or an Eagle

```go
type Eagle struct {
    color string
}

func (p *Eagle) Fly() {
    fmt.Println("I can fly high")
}

func (p *Eagle) Display() {
    fmt.Printf("I am a Eagle . I have color =%s", p.color)
}
```

As you can see the Fly() is common mechanism for lot of bids, so we can move this into a common construct.

In Java, we would create an abstract class, which has some common method implemented and later extend the abstract class to implement varying behaviour.

In Go we can do so be creating a type that partially implements  Fly() method

```go
//abstracting out just flying behaviour

type FlyStrategy struct {
	doFly FlyBehaviour
}

func (f *FlyStrategy) Fly() {
	f.doFly()
}

```

We extract out how a bird flies as `FlyBehaviour` 

```go
type FlyBehaviour func()

func FlywithWings() {
   fmt.Println("I am  flying with my wings")
}

func FlyNoWay() {
   fmt.Println("I can't fly")
}

func FlyHigh(){
   fmt.Println("I am  flying high")
}
```

Now to extend this behaviour in Java we would use `extend` but Go doesn't support inheritance in the classical sense; instead, in encourages *composition* as a way to extend the functionality of types. Go supports *embedding* of structs and interfaces to express a more seamless *composition* of types.

So to extend `FlyStrategy` we will simply embed it inside `Parrot ` type

```go
// Implementation of Parrot with FlyStrategy embed
type Parrot struct {
	color string
	FlyStrategy
}

func (p *Parrot) Display() {
	fmt.Printf("I am a Parrot . I have color = %s", p.color)
}

func main() {

	var greenParrot Bird

	greenParrot = &Parrot{
		color:       "green",
		FlyStrategy: FlyStrategy{doFly: FlywithWings},
	}

	greenParrot.Fly()
	greenParrot.Display()

}
```

Advantage of this pattern is that we can dynamically update flying strategy .

```go
// Interface
type Bird interface {
	Fly()
	Display()
//new
	UpdateFlyStrategy(flyb FlyBehaviour)
}

....
....

type FlyStrategy struct {
	doFly FlyBehaviour
}

func (f *FlyStrategy) Fly() {
	f.doFly()
}

//new
func (f *FlyStrategy) UpdateFlyStrategy(flyb FlyBehaviour) {
	f.doFly = flyb
}

....
....

greenParrot.UpdateFlyStrategy(FlyHigh)
greenParrot.Fly()
```
Fix Windows Search boxes not functioning after activation
Tags: windows, search, bash, cmd
Published: 2022-09-06 06:37:02

open command prompt and run $`ctfmon`
or open ** Windows Key+ R** then type `ctfmon`
For this you will have to repeat the same process every time your computer is restarted. 
you can automate this by adding a script in the windows startup folder.
To do that;
create a .bat script with the line `ctfmon` and save it as `ctfmonrunner.bat`
now copy the file and go paste inside the startup dir.
_C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup_

All done!
MERN Stack Login System with JWT and Google OAuth #1
Tags: mern, login, node, javascript
Published: 2022-09-06 06:25:04

This is part 1 of the complete login system with node.js

Source: https://github.com/0xMALVEE/mern-login-system-2022.git
Video 1: https://youtu.be/ALYnRoeQoLs
How to target desktop, tablet and mobile using Media Query ?
Tags: media, queries, css, responsive
Published: 2022-09-06 06:22:26

---
title: How to target desktop, tablet and mobile using Media Query ? 
published: true
description: How to write media queries
tags: media, queries, css, responsive
---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gb0bjcx3uptk969hf8yd.png)

&nbsp;
Media Query is a popular way for delivering a style sheet to different devices with different screen sizes and resolutions. They are used to alter the look of a website across numerous devices. A media query is made up of a media type and one or more expressions that can be true or false. If the supplied media matches the type of device on which the content is viewed, the query returns true. If the media query returns true, the style sheet is used.

The screen resolutions of different devices are listed below:

- Mobile (Smartphone) max-width: 480px
- Low Resolution Tablets and ipads max-width: 767px
- Tablets Ipads portrait mode max-width:1024px
- Desktops max-width:1280px
- Huge size (Larger screen) max-width: 1281px and greater

**Syntax:**

```css
@media( media feature ) {
    // CSS Property
}
```

Assuming that you have a css file `style.css`:

```css

        /* Media Query for Mobile Devices */
        @media (max-width: 480px) {
            body {
                background-color: red;
            }
        }
          
        /* Media Query for low resolution  Tablets, Ipads */
        @media (min-width: 481px) and (max-width: 767px) {
            body {
                background-color: yellow;
            }
        }
          
        /* Media Query for Tablets Ipads portrait mode */
        @media (min-width: 768px) and (max-width: 1024px){
            body {
                background-color: blue;
            }
        }
          
        /* Media Query for Laptops and Desktops */
        @media (min-width: 1025px) and (max-width: 1280px){
            body {
                background-color: green;
            }
        }
          
        /* Media Query for Large screens */
        @media (min-width: 1281px) {
            body {
                background-color: white;
            }
        }
```
814. Leetcode Solution in Java
Tags: java, chiki1601
Published: 2022-09-06 06:18:10

```
class Solution {
    public TreeNode pruneTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        
        if (root.val == 1 || root.left != null || root.right != null) {
            return root;
        }
        
        return null;
        
    }
}
```

#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/binary-tree-pruning/
Computed Nano Stores
Tags: astro, javascript, webdev, beginners
Published: 2022-09-06 06:11:25

Now that we had a look at [Maps with Nano Stores](https://daily-dev-tips.com/posts/astro-nano-stores-maps/) let's take a look at the next element, computed stores.

A computed store can take an initial static store and do some computing.
It can even compute from two different stores.

## Nano Stores computed maps

If you'd like to follow this article, use this [GitHub branch](https://github.com/rebelchris/astro-react/tree/part-4) as your starting point.

The first thing we'll do is add a new value to our color objects called primary.
We can use this to determine if a color is a primary color.

Open up the `src/store/colors.js` file and change the color map.

```js
const colors = map({
  blue: {
    primary: true,
    color: 'blue',
    hex: '#9bf6ff',
  },
  green: {
    primary: false,
    color: 'green',
    hex: '#caffbf',
  },
});
```

Then we can start by adding the computed value list.
First, import it.

```js
import { computed, map } from 'nanostores';
```

Then we can use it. Since we are using a map, we have to extract the object values manually.
If you were using Atoms, you'd be able to loop directly over those.

```js
const primaryColors = computed(colors, (list) =>
  Object.values(list).filter((item) => item.primary)
);
```

Now let's go to our `React.jsx` component and add some more buttons to play with.

```js
<button onClick={() => addColor('blue', '#a0c4ff', true)}>Change blue</button>
<button onClick={() => addColor('red', '#ffadad', true)}>Add red</button>
<button onClick={() => addColor('purple', '#bdb2ff', false)}>Add purple</button>
```

Now, let's load the primary colors and assign them to a useStore.

```js
import { primaryColors } from '../store/colors';

const primaryItems = useStore(primaryColors);
```

Then under the existing list, we'll render the primary color list.

```js
<h4>Primary colors</h4>
<ul>
    {Object.values(primaryItems).map(({color, hex}) => (
        <li key={color} style={{ backgroundColor: hex }}>
            {color} {hex}
        </li>
    ))}
</ul>
```

You can now run your application. Try clicking the buttons. This click should result in both the map and computed list changing!

![Computed map with Nano Stores](https://cdn.hashnode.com/res/hashnode/image/upload/v1661580696020/dcCG2jt0Z.png)

And as usual, you can also find the complete code on [GitHub](https://github.com/rebelchris/astro-react/tree/part-5).

### 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)
Next-Generation Configuration for NodeJS and ReactJS: wj-config
Tags: node, react
Published: 2022-09-06 05:51:15

Hello everyone.  Please have a look and comment what you think about this.  It is a configuration NPM package that works identically for NodeJS and ReactJS, and probably other browser frameworks and libraries.  No more fake environment constructs, at least for the most part.

Thank you!

[Next-Generation Configuration for NodeJS and ReactJS: wj-config](https://webjose.hashnode.dev/next-generation-configuration-for-nodejs-and-reactjs-wj-config)
UUID
Published: 2022-09-06 05:20:01

Soo i was still kinda messing with my CRUD function i have made, and came up with this issue where my ID# for each entry could be the same if i were to delete the post in between the collection. 
Since my way of generating not so unique ID was to get all the entries from the DB and count them up, and just add 1 to the total number. 

with this approach, if i were to erase post #2, out of 5 entries, my 6th post which should have an id of 6 would have 5 instead. 

In order to fix this issue, I decided to take a look at UUID. 
At first I wasnt so sure how to use it since it was giving my error when i simply set `{'id' : uuid.uuid4()}`. 
The thing is that I had to generate the ID first and give it to the key value pair. 

and there goes my other problem of integer length being too long, and so on but I was able to make it work with what I think "cheap shots" but hey, as long as it works, i am happy. 

Probably going to fix it once I get more use to using UUID.

TL;DR UUID works and i am happy nonetheless.
What I've learned during August 22-26 Week and 29-02 September Week
Tags: beginners, career, java, javascript
Published: 2022-09-06 04:58:05

During this two weeks I've been learning a lot about Java more specifically about collections, Spring and Spring-boot framework. 

## What are colllections in Java? 
A collection is defined as a group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, collections are a framework that includes data structures and methods using them will help us to  reduce effort on designing and implementing it. 

## Types of collections
- List: ArrayList, LinkedList, Vector, Stack.
- Map: HashMap and TreeMap
- Set: HashSet and LinkedHashSet

## What is Spring? 
Spring is the most popular java framework and allows us to build scalable projects faster and easier. Some of the spring applications are: build microservices, create web apps and serverless applications. 
It's friendly and easy to learn. 

Some advantages of using Spring are: 
- Predefined Templates
- Easy to test
- Lightweight
- Declarative Support 
- Fast development 

Now that we have the knowledge of how Spring works let's take a look to Spring-boot 
## Spring-boot and Java
Spring-boot is a tool that simplifies the development of web applications and microservices. It offers a dependency injection that allows us to define our own dependencies in objects. It also works as MVC (Model View COntroller) and makes easier integration with other technologies like React js.
What is Flutter? Is Flutter a Good Business Prospective?
Published: 2022-09-06 05:10:06


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hz916wvwvmisc94fk703.jpg)
**What is Flutter?**
Flutter is Google’s mobile app SDK for building high-quality native apps and beautiful, native-feeling cross-platform apps. Flutter is designed to reduce code size, improve your app’s performance, and help it run beautifully on many devices, from small-screen smartphones to large-screen watches. Flutter is Google’s framework for building modern, high-performance apps on [iOS](https://positiwise.com/technologies/ios-application-development/) and [Android](https://positiwise.com/technologies/android-application-development/). Flutter uses Dart, a language that compiles to run-time and generates native code. With Flutter’s unique approach to UI development, you can build beautiful apps fast.

Flutter is a new mobile UI framework for building high-quality mobile apps. Flutter provides a modern software development kit (SDK) that helps you build beautiful, high-quality apps using advanced development techniques to create highly interactive and engaging experiences for your users.

Flutter leverages Dart’s type system to provide an experience closer to programming in Java than Objective-C. Dart also offers strong static typing with optional dynamic typing (dynamic typing is available through annotations). Another strength of Dart is its robust compile time verification which allows the compiler to catch many errors at compile time.

Dart has a rich library set, enabling flutter developers to build high-quality apps quickly. Flutter provides easy access to UI features such as layout managers, gesture recognizers, and animation APIs while providing support for custom widgets and other components.

**Benefits of Using Flutter in Your Business**
The Flutter team has been working hard to make it easier for flutter developers to get started with this framework. Here are some of the benefits:

**Fast Process**
Dart is a swift programming language that allows you to build apps quickly and efficiently. Flutter uses Dart immediately after importing it into your app, so no additional setup is required. You can start developing right away without any setup time. Flutter is fast because it compiles the code on-device, eliminating the need for an internet connection. The result is a quicker flutter development process and a shorter time to market.

Flutter takes advantage of modern mobile devices and systems by building on top rather than working against them. This means you can use existing code instead of rewriting it from scratch. You can also use third-party libraries with Flutter without worrying about compatibility issues with your [flutter app development](https://positiwise.com/technologies/flutter-application-development/) or platform.

Read Full article: [What is Flutter? Is Flutter a Good Business Prospective?](https://positiwise.com/blog/what-is-flutter-is-flutter-a-good-business-prospective/)