teleren/devto huggingface dataset:
TypeScript Cheat sheet
Tags: javascript, typescript, react, nextjs
Published: 2022-07-01 09:14:21

# TypeScript CheatSheet
## want to edit this file ? https://github.com/premshetty/tscCheatsheet
### basic types

```ts
let id: number = 5;
let fname: string = "Max";
let isCool: boolean = true;
let x: any = [1, true, 3];
```

### tuple

```ts
let tuple: [number, string] = [1, "Max"];
```

### tuple array

```ts
let tupleArray: [number, string][] = [
  [1, "Max"],
  [2, "Manu"],
  [3, "Max"],
];
```

### union types

```ts
let union: number | string = "Max";
```

### enums

```ts
enum Direction1 {
  Up = 0,
  Down,
  Left,
  Right,
}

enum Direction2 {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}
```

### objects

```ts
const user: {
  name: string;
  age: number;
  hobbies: string[];
} = {
  name: "Max",
  age: 30,
  hobbies: ["Sports", "Cooking"],
};
```

### object with type

```ts
type user1 = {
  name: string;
  age: number;
  hobbies: string[];
};

const user1 = {
  name: "Max",
  age: 30,
  hobbies: ["Sports", "Cooking"],
};
```

### type assertions

```ts
let cid: any = 1;
let customerIdasNum = cid as number;
```

### functions

```ts
function addNum(x: number, y: number): number {
  return x + y;
}

// void type for no return value
function log(message: string | number): void {
  console.log(message);
}
```

### interfaces || custom types

```ts
interface User {
  readonly name: string; // readonly means that the property can only be read, not written
  age: number;
  experience?: number; //add? for optional property
}

const user2: User = {
  name: "Max",
  age: 30,
};
```

### customtype

```ts
type point = number | string;

const p1: point = 1;
```

### interfaces with functions

```ts
interface addFunction {
  (x: number, y: number): number;
}

const add: addFunction = (x: number, y: number): number => {
  return x + y;
};
```

### classes

```ts
class Person {
  private id: number; // private means that the property can only be read, not written
  name: string;
  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }
  register() {
    console.log(`${this.id} is registered`);
  }
}
const prem = new Person(1, "Prem Kumar");
const prem1 = new Person(2, "kumar kumar");
prem.register();
```

### generics reusable components with type parameters

```ts
function getArray<T>(items: T[]): T[] {
  return new Array().concat(items);
}

let numArray = getArray<number>([1, 2, 3]);
let strArray = getArray<string>(["Max", "Manu"]);
```
## want to edit this file ? https://github.com/premshetty/tscCheatsheet
Fresh – Is this new Javascript framework the Node-killer?
Tags: discuss, javascript, deno, webdev
Published: 2022-07-01 11:21:28

The time has come once again to evaluate a new Javascript framework…but wait. This isn’t your run of the mill React clone with slight variations promising to change everything.

Fresh is a Deno-based web framework that sends no javascript to the client by default. All of the bulk rendering and computation can operate on the server, and the client only needs to render small islands of UI.

For those who don’t know, Deno is a runtime for Javascript built by the original creator of NodeJS as a solution to a lot of the problems with the original Node. While the ecospace is still quite underdeveloped, Fresh might just be the framework that puts Deno on the map.

---

###Fresh Architecture
The two main parts of a Fresh application are routes and islands.

Routes are the way in which your web app responds to different requests. This can mean serving a response as part of an API, or serving HTML for your front end.

Islands are isolated preact (effectively a more lightweight version of React) components that are rendered on the client side. You can serve these to the client via routes. Fresh automatically handles the updating of Islands to minimize client load times.

You can create new routes and islands by creating files in the /routes and /islands folders respectively. 

Since the bulk of processing is done on the server-side, Fresh can load pages considerably faster than most frameworks that use Client-Side rendering and even many Server Side Rendering(Since Fresh doesn’t ship the whole rendering infrastructure to the client)

---

###Demo Application
Want to play around with a demo? First install Deno, and then create a demo project with:

`deno run -A -r https://fresh.deno.dev my-project-name`

And then run the project with:

`deno task start`

---

###Our Review
Working with Fresh felt incredibly lightweight and simple compared to most of the new frameworks that we’ve tried for the blog.

The routing/island system is incredibly intuitive and solves a lot of the bloating issues that make web frameworks undesirable. I fully plan to use Fresh for some projects in the future.

Obviously, the biggest challenge when working with Fresh is the size of the Deno ecosystem, but Fresh honestly seems like a big enough step in the right direction to warrant putting up with the growing pains of Deno.

If enough people feel the way we do about it, it might just get enough people into the Deno ecosystem to finally kill Node.

---


Do you agree? Let us know down below!

As always, happy coding from your friends at [Codesphere](https://link.codesphere.com/OE), the swiss army knife every development team needs!
Web development is like assembling IKEA furniture
Tags: ikea, instructions, standards, webdev
Published: 2022-07-01 11:00:39

---
title: Web development is like assembling IKEA furniture
published: true
description: I'm currently putting things together for a new flat and I realised that there are a lot of similarities between assembling IKEA furniture and doing web development.
tags: ikea, instructions, standards, webdevelopment
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/33tjzm5mf96f4a2wvzlp.png
# Use a ratio of 100:42 for best results.
---
 
When you put together IKEA furniture, it feels a lot like web development.

* You get a huge bag of seemingly random parts and you should sort them before you start
* Everything is standardised and uses building blocks
* The manual is meant to be universally understandable and such needs some effort to grasp
* Forcing something to fit means you're doing it wrong
* Leftover items mean you skipped a step
* You can use power tools to speed things up but you are likely to break things if you do
* Plan to assemble it right the first time, because taking it apart will mean you break it.
* Some parts are impossible to put together on your own - partner with another person and get a second pair of eyes to prevent you from doing something stupid
* Things look small and easy to handle when flat packed, but once you assembled them they take up a lot more space and are harder to move elsewhere
Clean Code Tip: Avoid using too many Imports in your classes
Tags: cleancode
Published: 2022-07-01 10:23:04


Actually, this article is not about a tip to write cleaner code, but it is an article that aims at pointing out a code smell.

Of course, once you find this code smell in your code, you can act in order to eliminate it, and, as a consequence, you will end up with cleaner code.

The code smell is easy to identify: open your classes and have a look at the imports list (in C#, the `using` on top of the file).

## A real example of too many imports

Here's a real-life example (I censored the names, of course):

```cs
using MyCompany.CMS.Data;
using MyCompany.CMS.Modules;
using MyCompany.CMS.Rendering;
using MyCompany.Witch.Distribution;
using MyCompany.Witch.Distribution.Elements;
using MyCompany.Witch.Distribution.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using MyProject.Controllers.VideoPlayer.v1.DataSource;
using MyProject.Controllers.VideoPlayer.v1.Vod;
using MyProject.Core;
using MyProject.Helpers.Common;
using MyProject.Helpers.DataExplorer;
using MyProject.Helpers.Entities;
using MyProject.Helpers.Extensions;
using MyProject.Helpers.Metadata;
using MyProject.Helpers.Roofline;
using MyProject.ModelsEntities;
using MyProject.Models.ViewEntities.Tags;
using MyProject.Modules.EditorialDetail.Core;
using MyProject.Modules.VideoPlayer.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace MyProject.Modules.Video
```

Sounds familiar? 

If we exclude the imports necessary to use some C# functionalities

```cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
```

We have lots of dependencies on external modules.

This means that if something changes in one of the classes that are part of those namespaces, we may end up with code that is difficult to update.


![Class diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hf7433gfghez49b2fhc.png) 

Also, guess what comes with all those imports? **Constructor with too many parameters** (and, in fact, in this class, I have 11 dependencies injected in the constructor) and **code that is too long** and difficult to understand (and, in fact, this class has 500+ lines).


A solution? Refactor your project in order to minimize scattering those dependencies.

## Wrapping up

Having all those imports (in C# we use the keyword `using`) is a good indicator that your code does too many things. You should focus on minimizing those imports **without cheating** (like using global imports).


Happy coding!

🐧
Creating Protected Routes With React Router V6
Tags: react, webdev
Published: 2022-07-01 10:21:31

Hey, if you’re looking to find out how to create a Private Route in Reactjs, I’m going to show you how you can do it in only 2 steps. This approach is actually very clean and makes our component much simpler.

> The idea is that a user must first meet certain requirements to access that route. In this case, the dashboard page can only be accessed by logged-in users

## Step 1

Let’s start by creating a Component, and we call it <PrivateRoute/>. we can pass in more than one route inside of this component. The <Outlet/> allows the Users component to render its child routes.
{% embed https://gist.github.com/b481ff80831c477c9aa1cda8a3caab5e.git %}

## Step 2

we would simply pass in <PrivateRoute> to a <Route>, and then nest all the components that we want to be private inside of this route.
{% embed https://gist.github.com/4cefd3966f25b641243c6417c8f119ae.git %}

that’s it 😄, Any developer who is looking forward to learning React or even the ones who have been using React for a while should be able to use and enjoy the stuff in this article!! 😄

The article has also been published in https://atefe-dev.medium.com/creating-protected-routes-with-react-router-v6-95498195128b
Leetcode Solutions: Check If a Word Occurs As a Prefix of Any Word in a Sentence
Tags: python, leetcode, programming, logic
Published: 2022-07-01 10:02:11

Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.

Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.

A prefix of a string s is any leading contiguous substring of s.

Here is my solution: 



```py

class Solution(object):
    def isPrefixOfWord(self, sentence, searchWord):
        """
        :type sentence: str
        :type searchWord: str
        :rtype: int
        """
        
        s = sentence.split(" ")
        
        for i, word in enumerate(s):
            if word.startswith(searchWord):
                return i + 1
        
        
        return -1
            
        
```
Leetcode Solutions: Rearrange Array Elements by Sign
Tags: programming, leetcode, python
Published: 2022-07-01 09:50:22

You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.

You should rearrange the elements of nums such that the modified array follows the given conditions:

Every consecutive pair of integers have opposite signs.
For all integers with the same sign, the order in which they were present in nums is preserved.
The rearranged array begins with a positive integer.
Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

Here is my solution: 



```py

class Solution(object):
    def rearrangeArray(self, nums):
        """
            :type nums: List[int]
            :rtype: List[int]
        """
        
        pos = []
        neg = []
        
        for num in nums:
            if num < 0:
                neg.append(num)
            else:
                pos.append(num)
        
        res = []
        
        z = zip(pos, neg)
        
        for l, r in z:
            res.append(l)
            res.append(r)
        return res
        
        

```
Kubectl exec/port-forward with AWS ALB and nginx-ingress-controller
Tags: alb, aws, nginx, kubernetes
Published: 2022-07-01 09:46:00

I was facing issues when I performed kubectl with exec or port-forward option on my Rancher clusters that used EKS and ALB, it was giving me this error

```
kubectl exec -it app -- bash

Error from server (BadRequest): Upgrade request required
```

exec and port forward are using SPDY protocol and ALB does not support it.


The HTTPS request is going from the user to ALB, then SSL is terminated on the ALB, and the request is forwarded to the Nginx controller service after that forward to the rancher service.   

[See the part 1 to setup Rancher on EKS and ALB ](https://dev.to/aws-builders/setup-rancher-on-eks-alb-50)

After that, you need to do the following:


1- Install Nginx Ingress Controller


```
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
helm repo update
```

Kubernetes v1.16+ use version 3.x.x 

```
helm upgrade --install nginx ingress-nginx/ingress-nginx --namespace cattle-system --set controller.service.type=NodePort  --set controller.service.targetPorts.https=http --set-string controller.config.use-forwarded-headers="true" --version 3.12.0
```

Kubernetes v1.19+ use version 4.x.x

```
helm upgrade --install nginx ingress-nginx/ingress-nginx --namespace cattle-system --set controller.service.type=NodePort  --set controller.service.targetPorts.https=http --set-string controller.config.use-forwarded-headers="true" --version 4.2.3
```

2- Edit the rancher Ingress
```
kubectl edit ingress -n cattle-system rancher
```
Change the host and name inside spec with the following:
```

spec:
   rules:
   - host: '*.example.com'
     http:
       paths:
       - backend:
           service:
             name: nginx-ingress-nginx-controller
             port:
               number: 80
         pathType: ImplementationSpecific
```
3- Create a new ingress with the following:

```
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
  name: rancher-exec
  namespace: cattle-system
 
spec:
   rules:
   - host: 'rancher.example.com'
     http:
       paths:
       - backend:
           service:
             name: rancher
             port:
               number: 80
         pathType: ImplementationSpecific
```

You need to add ingressClassName: nginx  only for **rancher-exec**

 
```
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
  name: rancher-exec
  namespace: cattle-system
 
spec:
   ingressClassName: nginx 
   rules:
   - host: 'rancher.example.com'
     http:
       paths:
       - backend:
           service:
             name: rancher
             port:
               number: 80
         pathType: ImplementationSpecific
```

**Note**: It will remove the ALB if you add ingressClassName: nginx to **rancher** ingress

Test the kubectl exec and port-forward

```
kubectl create deployment nginx2 --image nginx:alpine
kubectl expose deployment nginx2 --port=80
kubectl exec -it nginx2-XXXXX -- sh
kubectl port-forward service/nginx2 --address 0.0.0.0 80:80
```
Leetcode Solutions: Partition Array According to Given Pivot
Tags: programming, python, leetcode
Published: 2022-07-01 09:36:01

Here is the problem: 

You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:

Every element less than pivot appears before every element greater than pivot.
Every element equal to pivot appears in between the elements less than and greater than pivot.
The relative order of the elements less than pivot and the elements greater than pivot is maintained.
More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj.
Return nums after the rearrangement.

Here is my solution: 

```py

class Solution(object):
    def pivotArray(self, nums, pivot):
        
        left = []
        right = []
        p = []
        
        for num in nums:
            if num < pivot: 
                left.append(num)
            elif num > pivot:
                right.append(num)
            else: 
                p.append(num)
        
        
        return left + p + right
        
        
        

```
Voyage in Paradise - for all the music lovers 🎼
Published: 2022-07-01 09:18:43


This project created by music lovers for music lovers: featuring top global music artists, rhythm-based gameFi, and a listen-to-earn platform within the metaverse.

Highly recommend all music lover to join this project now 🙂

Doxxed and experienced Team with years of experience in the gaming/blockchain industry
One-on-one Mastering feedback sessions with artists
Backstage appearance with artists
Early access to music events
Personalized videos from artists
Raffle for exclusive VIP Festival experiences and airdrops with many more

Coming soon!
Collection Size: 3333
Mint Price: 4 SOL
Mint Date: TBA

DYOR and thanks me later!
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vhvsixlykwtd1efjrt2p.jpg)
Onigiri - Japanese MMORPG with >5m+ fan base
Published: 2022-07-01 09:14:53

GM! Would love to share this amazing up and coming with you guys!



ONIGIRI is an MMORPG set in the mythical land of ancient Japan. In the vast world of ONIGIRI, a unique Japanese fantasy world awaits players, with many unique characters and architecture appearing in each field. The best part of ONIGIRI is that you have the ability to explore this world with other players.

Doxxed and experienced Team with years of experience in gaming/blockchain industry
Established game with nearly 10 years.
IP infrastructure already being built.

Mint details:
July 3rd - 3,000 NFTs - 0.10 ETH

Join Discord: https://discord.gg/S44WQqF4ab

Want to experience it : https://onigirimetaverse.com/



DYOR and Thanks me later!
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qkc4x9tgvv7pxl0977g2.jpg)
#TestCulture 🦅 Episode 5 - Must-read books for testers
Tags: discuss, testing, agile, beginners
Published: 2022-07-01 09:11:18

We questioned a few testers about books that helped them in their early days in testing. If they had to choose only ONE book, which one would they choose? 🤔

One of them explained that ‘Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation’ by 
Jez Humble and David Farley helped him at the beginning and still helps him.


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

This book presents cutting-edge techniques, including automated infrastructure management and data migration, as well as the use of virtualization. It reviews key issues, identifies best practices, and shows how to mitigate risks.

It is designed for developers, testers, but also system administrators. It helps to get properly organized and to go from idea to production faster. This book was written by two authors specializing in testing, DevOps and software engineering.

Another book was mentioned: ‘Agile Testing: A Practical Guide for Testers and Agile Teams’ by Lisa Crispin and Janet Gregory.


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

This book explains agile testing and the role of testers with concrete examples. It also explains how to use the quadrants of agile testing in detail and reflects the picture of agile software from a tester's point of view, explaining the 7 key success factors of agile testing.


Another recommandation is'Lessons learned in software testing', by Cem Kaner, James Bach, and Bret Pettichord. 


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

Another book recommended by him was ‘Dear evil tester’ by Alan Richardson. _‘It was really interesting and opened my mind up to other approaches’_.


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

Alan Richardson describes his book as a ‘revolutionary testing book for the mind which shows the reader an alternative approach to testing built on responsibility, control and laughter’.

Last but not least, a French book was recommended: ‘Le chaînon manquant: Le Chemin du Continuous Testing’, by Valentin Guerlesquin and Henri Bigot.


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

These two experts present the implementation of automated testing in their company. This approach allows you to learn about continuous testing at the same pace as the two experts, which gives you a good understanding of the subject.

And you, if you had to choose ONE book that helped you in your early days in testing, which one would you choose? 🤔 


Thread [on Twitter.](https://twitter.com/agilitest/status/1512438388271505411?s=20&t=i7kfpJ3U-nbZF7vjk3AO4A)
NVIDIA Triton Spam Detection Engine of C-Suite Labs
Tags: nvidia, triton, spam, aws
Published: 2022-07-01 08:12:47

_This has been a joint project of NVIDIA and AWS Community Builder in Machine Learning program._

Unwanted and unsolicited bulk digital communication (“spam”) is responsible for substantial direct and indirect economic damage every year.

Traditional ways to identify spam by detecting certain keywords, manually reviewing text records, or even running Natural Language Processing (“NLP”) pipelines are no longer sufficient.

This article describes the architecture of the state-of-the art Spam Detection Engine of [C-Suite Labs](https://www.csuitelabs.com/) consisting of multiple inter-dependent distinct classifiers delivering real-time, high-performance superior accuracy with minimum required manual review.

This article focuses on the DistilBERT spam content model. 

**Application of NVIDIA Triton Inference Server for this use case provides the inference throughput 2.4 times higher than TorchScript Inference Server with 52.9 times lower model latency.**

Please read the rest of the article at https://jiripik.com/2022/06/30/nvidia-triton-spam-detection-engine-of-c-suite-labs/