teleren/devto huggingface dataset:
Typescript: Conditional types
Tags: programming, typescript, tutorial
Published: 2022-06-08 12:46:18

Conditional types

{% embed https://www.youtube.com/embed/N-GWQKjgnnQ %}
_See this and many other articles at [lucaspaganini.com](lucaspaganini.com)_

Conditional types in TypeScript are super powerful, they allow us to create type functions. I'll show you.

Let's say we have 3 types: `A`, `B` and `C`.

```ts
type A
type B
type C
```

They could be anything, but let's say that `A` is `string`, `B` is `number` and `C` is the union of `A` and `B`.

```ts
type A = string;
type B = number;
type C = A | B;
```

Now, we want to convert `string` and `number` to literal numeric representations.

`string` should be `1`,

```ts
type NumberA = 1;
type NumberB = number;
type NumberC = 1 | number;
```

`number` should be `2`, and anything else should be `0`.

```ts
type NumberA = 1;
type NumberB = 2;
type NumberC = 1 | 2;
```

If this was a function, you would simply use conditionals to drive the code. It would look something like this:

```ts
const ToNumber = (T) => (T === string ? 1 : T === number ? 2 : 0);
```

That syntax doesn't work for types, but it's pretty close.

```ts
type ToNumber = (T) =>
  T === string
  ? 1
  : T === number
  ? 2
  : 0
```

Instead of an arrow, we use equals.

```ts
type ToNumber(T) =
  T === string
  ? 1
  : T === number
  ? 2
  : 0
```

Instead of parenthesis, we use angle brackets.

```ts
type ToNumber<T> =
  T === string
  ? 1
  : T === number
  ? 2
  : 0
```

And instead of triple equals, we use extends.

```ts
type ToNumber<T> = T extends string ? 1 : T extends number ? 2 : 0;
```

See, we are not asking TypeScript if `T` is equal to `string`, what we're asking is if `T` is a subset of `string`.

That also includes literal string types, such as `"abc"`.

```ts
type A = string
type B = number
type C = A | B

ToNumber<A> // -> 1
ToNumber<B> // -> 2
ToNumber<C> // -> 1 | 2
ToNumber<boolean> // -> 0
ToNumber<"abc"> // -> 1
```

## Conclusion

References are below.

This article is part of my TypeScript Narrowing Series. You can read the full series for free on my blog.

Leave a like, have a great day, and I'll see you soon!

## References

1. [Conditional Types _TypeScript Documentation_](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html)
What are the Types of Functions in JavaScript?
Tags: beginners, functions, typesoffunctions, javascript
Published: 2022-06-08 12:44:07

## What is a Function?
A function is a block of reusable code that performs a specific task.

There are 3 types of functions in JavaScript:
<ul>
<li>Anonymous functions</li>
<li>Named functions</li>
<li>Immediately Invoked Function Expression</li>
</ul>

## Anonymous Functions
These are functions without names attached to them. Typically, these functions will be declared with the `function` keyword but without a name.

The syntax of an anonymous function looks like:
```js
// declaring an anonymous function
function(){
 // function body
}
```
Here is an example of an anonymous function:
```js
// declaring an anonymous function
function(){
  console.log('I am anonymous!'); // I am anonymous!
}
```
In the above example, we have defined an anonymous function that prints out the string *'I am anonymous!'* to the console.

It is important to note that we cannot access the anonymous fuction after its creation.  However, if we want to access it, we can assign the function to a variable.
```js
// declaring an anonymous function
let anonymousFun = function(){
  console.log('I am anonymous!'); 
}
anonymousFun(); // I am anonymous!
```

## Named Functions
These are functions which on declaration, they are assigned a name. This allows us to access the function later on just by referencing the name of the function.
The general syntax looks like:

```js
function functionName(/*parameters*/){
  // function body
}
``` 

Here is an example of a named function:
```js
function myNamedFun(){
   console.log('I am a named function'); 
}

// accessing the function
myNamedFun(); // I am a named function

``` 


## Immediately Invoked Function Expression
Immediately Invoked Function Execution(IIFE) is a function that executes immediately after its declaration.
The general syntax for IIFEs looks like:

```js
(
  function(){
    // function body
}
)()
``` 

Here is an example of a IIFE function:
```js
(function immediatelyInvoked(){
   console.log('I will execute imediately!');  // I will execute imediately!
})();

``` 

I like thinking about IIFEs as code blocks that live in their 'own environment' such that they are not affected by any other code that will execute thereafter.

You can find the IIFE helpful when you want to quickly initialize variables or objects in a larger function.

If you are keen, you must have noticed that the IIFE is more of an anonymous function. Therefore, we can assign them a variable and later on use the variable as shown below:

```js
let myFun = (function immediatelyInvoked(){
   return 'I will execute imediately!';  
})();

console.log(myFun) // I will execute imediately!
``` 

## Key Takeaways

<ol>
<li>A function is a block of reusable code that perfoms a specific task</li>
<li>There are 3 types of functions in JavaScript:</li>
  <ul>
<li>Anonymous functions</li>
<li>Named functions</li>
<li>Immediately Invoked Function Expression</li>
</ul>
</ol>
Best Mock Apis for testing & prototyping
Tags: testing, frontend, fake, webdev
Published: 2022-06-08 12:42:34

**[Mockyard.in](https://www.mockyard.in/)**

`[Mockyard](https://www.mockyard.in/)` offers a REST API for developers to test their apps with realistic, high-quality mock data. Our API is perfect for prototyping, user experience testing and performance testing.

>I found it best to serve the sole purpose.



why you should use Mockyard.

1. ease to use.
2. no clumsy authentication.
3. realistic data to use in your serious project.
4. thousands of users, products & blog data.
5. increase productivity during development.

The [Mockyard](https://www.mockyard.in/) API is an easy way to create mock objects in JSON format. These JSON files are generated from our database of over 1 billion records that are constantly being updated by our team of human writers.

It offers a REST API for developers to test their apps with realistic, high-quality mock data. Our API is perfect for prototyping and testing any application that needs a database.
Which Headless CMS Should I Use?
Tags: javascript, opensource, cms
Published: 2022-06-08 12:35:11

---
title: Which Headless CMS Should I Use?
published: true
description: This video is an update with what tools there are currently available, and my experience of using a variety of open source Headless CMS.
tags:
- javascript
- opensource
- cms
---

**A little while ago I was working on a POC / tender for a new CMS. As part of that process, I investigated what JavaScript CMSes there were out there. I was particularly keen on self-hosted ones because I personally prefer keeping ownership of my own data.**

[I wrote about my findings on my blog](https://deliciousreverie.co.uk/posts/javascript-cms-landscape/), however times have changed and there are even more now!

This video is an update with a few of the newer ones on the market. Hope it helps someone to evaluate and make a decision for their project!

Here's the video:

http://youtube.com/watch?v=QGVGRqjtx-o
Angle Between Hands of a Clock
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 12:30:36

Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.

Answers within `10-5` of the actual value will be accepted as correct.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/12/26/sample_1_1673.png)

**Input:** hour = 12, minutes = 30
**Output:** 165

**Example 2:**

![](https://assets.leetcode.com/uploads/2019/12/26/sample_2_1673.png)

**Input:** hour = 3, minutes = 30
**Output:** 75

**Example 3:**

![](https://assets.leetcode.com/uploads/2019/12/26/sample_3_1673.png)

**Input:** hour = 3, minutes = 15
**Output:** 7.5

**Constraints:**

*   `1 <= hour <= 12`
*   `0 <= minutes <= 59`

**SOLUTION:**

    class Solution:
        def angleClock(self, hour: int, minutes: int) -> float:
            mAngle = minutes * 6
            hAngle = (hour * 30 + minutes / 2) % 360
            diff = abs(mAngle - hAngle)
            return min(diff, 360 - diff)
Handling Appstore Server-to-Server V2 Notifications using Golang
Tags: go, sns, pushnotifications, programming
Published: 2022-06-08 12:15:27

How to implement App store server to server v2 notifications?

When I started implementing app store SNS v2 in golang, I was a bit confused about how to verify and parse JWS data.

Thanks to this [thread](https://stackoverflow.com/a/69739376), I learned lots of important things there. While doing the implementation, I simplified it for you guys.

This article will help you learn about SNS implementation in a very simple way.

App Store has released server-to-server notification version 2 with more events(notification types and sub types) than version 1.

In version2, they are sending JSON Web Signature (JWS) formatted (Which is a JWT token) notification to improve the security of data.

To read full article, please [visit our blog](https://blog.canopas.com/golang-handling-appstore-server-to-server-v2-notifications-ef1e8eb05118).
Flexy React Material UI Template – Free
Published: 2022-06-08 12:03:54


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

Flexy Next Js Template is free to use Admin Template created by [Wrappixel](https://www.wrappixel.com/?ref=232), an admin themes and templates provider. This template comes with a built-in dashboard and has different UI elements which make it a great starting point for your next project. All you need to do is add content and customize where needed. Each block can be styled in different ways to suit your needs, and you can combine them to build the interface the way you want.

The modular and intuitive design of the template makes it easy for users to interact with your interface and provides a smooth and consistent interface across devices, browsers, and platforms.

The framework is MUI enabled, which enables you to use Google Web Fonts in your templates. The templates are retina-ready, which makes them look great on both desktop and mobile devices. Along with this, the template is search engine optimized and fully responsive.

[Live Demo](https://demos.wrappixel.com/free-admin-templates/nextjs/flexy-nextjs-admin-free-dist/landingpage/)
[Download](https://www.wrappixel.com/templates/flexy-next-js-free-admin-template/?ref=232)

**Product Features -**

- 8+ readymade UI component pages
- MUI(5) Enabled Framework
- Unlimited Google Web Fonts
- Retina Ready templates
- SCSS Base CSS framework
- Search Engine Optimized Code 
- Lightning-fast performance

If you wish to access numerous other features like different application designs, dashboard styles, charts, tables, widgets, plugins, detailed documentation, and others, please check our premium version - [Flexy React Material Dashboard](https://www.wrappixel.com/templates/flexy-react-material-dashboard-admin/?ref=232). Our premium version comes with a 100% Moneyback Guarantee, 1 Year of Free Updates, and Expert Support.
Como organizar importações automaticamente no VSCode
Tags: typescript, vscode, react, node
Published: 2022-06-08 12:02:31

O VSCode tem uma opção para remover quaisquer importações não utilizadas, classificar importações existentes por caminhos de arquivo e classificar importações nomeadas.


![Exemplo da auto correção do VSCode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h5nu8hiwhz9ikr99upx4.gif)

Abra as configurações (⇧⌘P ou Ctrl+Shift+P), pesquise por **Preferences: Open Settings (JSON)**. Então abrirá o arquivo settings.json. Agora adicione a configuração.


```
"[typescript]": {
    "editor.codeActionsOnSave": {
        "source.organizeImports": true
    }
},
"[typescriptreact]": {
    "editor.codeActionsOnSave": {
        "source.organizeImports": true
    }
}
```

Pronto, Sempre que você salvar o arquivo *.ts ou *.tsx, o VSCode organizará automaticamente as importações.


Agradecimentos ao conteúdo original em inglês: https://eshlox.net/2019/12/02/vscode-automatically-organize-typescript-imports
Happy Number
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 12:00:42

Write an algorithm to determine if a number `n` is happy.

A **happy number** is a number defined by the following process:

*   Starting with any positive integer, replace the number by the sum of the squares of its digits.
*   Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
*   Those numbers for which this process **ends in 1** are happy.

Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.

**Example 1:**

**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

**Example 2:**

**Input:** n = 2
**Output:** false

**Constraints:**

*   `1 <= n <= 231 - 1`

**SOLUTION:**

    class Solution:
        def isHappy(self, n: int) -> bool:
            visited = set()
            while n != 1:
                if n in visited:
                    return False
                visited.add(n)
                nn = 0
                while n != 0:
                    c = n % 10
                    nn += c * c
                    n = n // 10
                n = nn
            return True
K-diff Pairs in an Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 11:30:35

Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_.

A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true:

*   `0 <= i, j < nums.length`
*   `i != j`
*   `nums[i] - nums[j] == k`

**Notice** that `|val|` denotes the absolute value of `val`.

**Example 1:**

**Input:** nums = \[3,1,4,1,5\], k = 2
**Output:** 2
**Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of **unique** pairs.

**Example 2:**

**Input:** nums = \[1,2,3,4,5\], k = 1
**Output:** 4
**Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

**Example 3:**

**Input:** nums = \[1,3,1,5,4\], k = 0
**Output:** 1
**Explanation:** There is one 0-diff pair in the array, (1, 1).

**Constraints:**

*   `1 <= nums.length <= 104`
*   `-107 <= nums[i] <= 107`
*   `0 <= k <= 107`

**SOLUTION:**

    class Solution:
        def findPairs(self, nums: List[int], k: int) -> int:
            exists = {}
            ctr = set()
            for i, num in enumerate(nums):
                exists[num] = exists.get(num, []) + [i]
            for i, num in enumerate(nums):
                for val in [num - k, num + k]:
                    if val in exists:
                        for j in exists[val]:
                            if j > i:
                                ctr.add(tuple(sorted([nums[i], nums[j]])))
            return len(ctr)
BeautifulSoup: REPLACEMENT CHARACTER
Tags: python, beautifulsoup
Published: 2022-06-08 11:13:31

**BeautifulSoup**: Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER

Use **UnicodeDammit**, more https://www.crummy.com/software/BeautifulSoup/bs4/doc/#unicode-dammit

```python
self.bs = BeautifulSoup(
    UnicodeDammit(
        content, 
        ["latin-1", "iso-8859-1", "windows-1251"]
    ).unicode_markup,
    "html.parser")
```
3 Weird Reasons Why You Should Learn Programming
Tags: programming, webdev, javascript
Published: 2022-06-08 11:09:13

The programming language is a powerful way to connect and communicate with electronic devices and computers, and that's why it's so popular among people who aren't familiar with the programming language or who aren't in the telecommunication industry because they have doubts about anything about it.
The information is usually available on the internet, and there are several ways to get it quickly. The information is often found in YouTube channels on practical learning, and the theoretical knowledge is on Medium – Where good ideas find you., which is free of charge. You don't have to learn programming, so it's easy to learn.
It’s already 2022
There are lots of advantages now that everything is digital. From smartwatches to smartphones and everything else, you can check from the comfort of your own home. So now that you see the world has changed a lot and has provided lots of opportunities because technology changed this world.
Since its industry is booming and booming because of technology, so why are you waiting to learn technical skills because the industry has billions of dollars, and there are lots of jobs to choose from. So start learning expert skills and go for higher jobs.
Programming can be your next passion
I believe programming is a part of the future generation because new technological advances change a lot of people's minds and the new generation has a lot of impact on the world, so yes, it is a passion to do programming, very curious about new things and eager to learn if you learn you have a lot of security in the future.
You will have tons of helpers
Basically, programming is booming, and millions of people are learning and enhancing their skills of programming. Even if you are learning programming skills for yourself, you can ask other people for help because there are many websites that are available to help.
The platform is really friendly to helping you because it allows you to connect with people to figure out what the problem is that you face. The people are willing to help you for free because they can relate to what you are going through.
Binary Number with Alternating Bits
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 11:00:47

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

**Example 1:**

**Input:** n = 5
**Output:** true
**Explanation:** The binary representation of 5 is: 101

**Example 2:**

**Input:** n = 7
**Output:** false
**Explanation:** The binary representation of 7 is: 111.

**Example 3:**

**Input:** n = 11
**Output:** false
**Explanation:** The binary representation of 11 is: 1011.

**Constraints:**

*   `1 <= n <= 231 - 1`

**SOLUTION:**

    class Solution:
        def hasAlternatingBits(self, n: int) -> bool:
            bi = "{:b}".format(n)
            for i, c in enumerate(bi):
                if i > 0:
                    if c == bi[i - 1]:
                        return False
            return True
From wanting to be part of the CTO
Tags: career, devrel, devops, startup
Published: 2022-06-08 11:00:26

After seeing the initiative [Buser](https://www.linkedin.com/company/buserbrasil/) had to train people at home with the [Buser Tech](https://blog.buser.com.br/novidades/buser-lanca-programa-capacitacao-profissionais-tecnologia/) program (led by [Renzo](https://www.linkedin.com/in/renzonuccitelli/) as Buser’s head of education), I wanted to approach them somehow — I didn’t know how or what to do, but I wanted to be part of the **“party”**.

I have helped many engineering people evolve professionally (that's 0.001%), but I have never trained anyone from scratch and I felt it was time to learn from those who have been doing it for a few years.

I have known [Tony](https://www.linkedin.com/in/tonylampada/) (ex-CTO of Buser) for many years, in late 2021 I took the liberty to message him and express my interest.

I didn’t feel comfortable coming into Buser to suck knowledge, so I proposed to join the engineering team as a developer and follow what is going on in Buser Tech.

In the 1:1 with Tony he shared with me that he was looking for someone to take over the CTO role at Buser. I confess I didn’t understand why he was sharing that with me, the only answer that came to me at the moment was:

> “If you are saying this for me to be CTO you are saying it to the wrong person.”

Upon arriving and bumping into the software we developed at Buser I started to wonder how the folks in the Buser Tech program (with virtually zero software development experience) were going to get up the development environment that I with a few years of engineering experience was having some friction. I took this as my first challenge to reduce the friction of onboarding the engineering team by bringing a developer experience look.

After a few days/weeks I felt that we could improve our people and project management, I went to talk to Tony and made myself available to help as Tech Manager.

The subject of possibly being a CTO stayed in my mind for days and days, I even indicated a CTO for the position that unfortunately did not match, but life goes on, and my internal monsters kept haunting me about the CTO position.

Usually when I get a chill in my stomach it sounds like I am looking at a big challenge and there is a big unknown — especially what I need to evolve as a person and a manager, in this case a company with more than 500 people.

After being an entrepreneur for a few years, I don’t want to make a company from scratch until I reach 500 people (Buser’s current moment), but I am sure that the challenge of Scale-up a startup takes me closer to my professional goal.

Even though my stomach is chilly and I believe I have many skills to evolve, I am taking on the CTO position at Buser.

_Is Tony leaving Buser?_ **No**, he is moving back closer to the engineering and education team — where he feels he delivers much better results for the company. [See here](https://www.linkedin.com/pulse/vida-longa-ao-cto-tony-lampada/) the post he made publicly about this move (publication written in Portuguese).
Scale8.com - An open-source and privacy friendly alternative to GA & GTM
Published: 2022-06-08 10:59:36

A fast, simple, open-source and privacy-friendly alternative to Google Tag Manager and Google Analytics. Focusing on delivering the features and tools that matter most to publishers. The project is completely free to run on your cloud platform.

We are live today on Product Hunt - please take a look and upvote!

https://bit.ly/3zr3wMe

We'd love to get feedback from this community. A 'star' on GitHub would also be incredibly appreciated if you feel this project is relevant to you.

https://github.com/scale8/scale8
UI breaking on moving from one route to another
Tags: nextjs, reacj, nodej
Published: 2022-06-08 10:52:22

I have a website built on NextJS. There are a few pages on the website. When a user moves from "/clicworth" to "/property-in-gurugram" the UI of "/property-in-gurugram" is breaking. This doesn't happen if user moves to "/property-in-gurugram" from any other page.

Test link: https://qa.clicbrics.com/clicworth