teleren/devto huggingface dataset:
Typescript - Tips & Tricks - Assert Function
Tags: typescript, webdev
Published: 2021-03-19 07:13:10

There are times that we need to create some assertions to be sure an object respects some rules.
A common case is to check if an object is defined; to do this you can create a simple assertion function like this
```ts
function assert(condition: unknown, message: string): asserts condition {
  if (!condition) throw new Error(message);
}
```
To leave you a simple case of use, I write this simple example
```ts
type Person = {
  name: string;
  email?: string;
};

function loadPerson(): Person | null {
  return null;
}

let person = loadPerson();

function assert(condition: unknown, message: string): asserts condition {
  if (!condition) throw new Error(message);
}

assert(person, "Person is not defined"); // Error: Person is not defined
console.log(person.name);
```
As you can see, in this example, the assert function detects if the person is defined and if the person isn't defined the assert function throws an error with the message that you pass in the parameters.
To level up, and explain better the power of the assert function, here another example
```ts
type Square = {
  kind: "square";
  size: number;
};

function ensureSquare(obj: unknown): asserts obj is Square {
  if (
    typeof obj === "object" &&
    !!obj &&
    "kind" in obj &&
    (obj as Square).kind === "square"
  )
    return;

  throw new Error("Object isn't a Square type");
}

const square = { kind: "square", size: 10 };
ensureSquare(square);
// const square: Square
console.log("shape", square.kind);
console.log("size", square.size);

const rectangle = { kind: "rectangle", width: 10, height: 15 };
ensureSquare(rectangle); // throw new Error("Object isn't a Square type");
console.log("shape", rectangle.kind);
console.log("size", rectangle.size);
```
In this case, you can see how the "ensureSquare" function creates an assertion to detect if the object passed as parameter is of type Square or not.
If you see the part of the example where I created the square field, you can note that the type of the square field is `{ kind: string; size: number; }`. If you observe the type of the square field after the "ensureSquare(square);" you can see how typescript converts the type of the field from `{ kind: string; size: number; }` to Square.
This conversion is done because if the code passes the "ensureSquare" function you are sure that the "square" field is of type Square. On the contrary, in the second part of the example, the "rectangle" field, on runtime, throws an error, and the code after the "ensureSquare" function will never be executed.
I think you have understood the power of the assertion functions, and I hope they will help you to prevent some future mistakes.

It's all guys, Bye Bye!
Let's share our personal websites and see how we can we improve it.
Tags: showdev, portfolio, improve
Published: 2021-03-19 07:08:58


Hi everyone, I am Tri Tran - Fullstack Developer :blush:

Every Web Developer should have a portfolio especially a junior one. Nowadays, web development has become very competitive. Knowing the skills is not enough and you also should need a portfolio to contain projects related to that skills and show up your personality :kissing:


Today I want to make a post where people can come in and share their personal websites then receive opinions on how people think it looks and improves it together. 


I will share mine first. I have built and made changes to this website for a couple of months. Thank to my personal website I got many callbacks and interviews just by seeing my resume and portfolio even though I don't have a degree and any commercial experience :smile: then eventually land my first job. 


This is my portfolio : [Portfolio](https://tranminhtri.com/)

Please give me your opinion on how it looks and what I can do to improve and I would do the same for you as well ! :satisfied:
Installing Docker Compose 1.28.2 on NVIDIA Jetson Nano is not straightforward
Published: 2021-03-19 07:08:26

---
title: Installing Docker Compose 1.28.2 on NVIDIA Jetson Nano is not straightforward
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/exrtsrn6h6jfk7kxjx5c.png)


To install Docker Compose on a Linux system is just a one-liner command but that's not true for IoT devices like Raspberry Pi and Jetson Nano. 

While installing the latest Docker Compose 1.28.2, I went through a painful dependency hell. Finally, after dozens of tweaks and tricks, I managed to install the latest version of Compose. 

Here's how I managed to get it installed:

## Hardware

- Jetson Nano
- A 5V 4Ampere Charger
- 64GB SD card

## Software

- Jetson SD card image from https://developer.nvidia.com/embedded/downloads
- Etcher software installed on your system

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nrrrgsni81pagsvr77yd.png)
## Preparing Your Raspberry Pi Flashing Jetson SD Card Image

- Unzip the SD card image
- Insert SD card into your system.
- Bring up Etcher tool and select the target SD card to which you want to flash the image.

Verifying if it is shipped with Docker Binaries

```
sudo docker version
Client: Docker Engine - Community
 Version:           20.10.3
 API version:       1.41
 Go version:        go1.13.15
 Git commit:        48d30b5
 Built:             Fri Jan 29 14:33:34 2021
 OS/Arch:           linux/arm64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.3
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       46229ca
  Built:            Fri Jan 29 14:31:49 2021
  OS/Arch:          linux/arm64
  Experimental:     false
 containerd:
  Version:          1.4.3
  GitCommit:        269548fa27e0089a8b8278fc4fc781d7f65a939b
 nvidia:
  Version:          1.0.0-rc92
  GitCommit:        ff819c7e9184c13b7c2607fe6c30ae19403a7aff
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
pico@pico1:~$ 
```

Put the below content into a file and execute it

```
#!/bin/bash
sudo apt-get update -y
sudo apt-get upgrade -y
sudo apt-get install curl python3-pip libffi-dev python-openssl libssl-dev zlib1g-dev gcc g++ make -y
sudo apt install rustc
sudo pip3 install docker-compose
```




```
sudo docker-compose version
docker-compose version 1.28.2, build unknown
docker-py version: 4.4.2
CPython version: 3.6.9
OpenSSL version: OpenSSL 1.1.1  11 Sep 2018
```

How was your experience in setting up Compose on Jetson Nano board? Do leave your comments and feedback.

References:

- https://github.com/collabnix/ioetplanet
Know How to Google Is Important. Do You Know How Do It?
Tags: productivity, beginners, webdev
Published: 2021-03-19 06:59:40

*If you like this article, you might also like my Twitter content. You can find me here - [Twitter profile](https://twitter.com/AlbertWalicki).* 🚀



Knowing how to google is the most important skill for a developer. Everyone uses Google. Junior developers, mid or senior. It's not cheating to google everything! But do you really know how to google more efficiently? Let me show you some google hacks 👨‍💻.


# Explicit phase

Search for an explicit phrase by enclosing it in quotation marks.

![Explicit phase with double quote](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vgfjum0uli74prcs0l08.jpeg)




# Site Search

Refine your search to a specific site using the site: command. For example, typing on the google site:stackoverflow.com will search only on StackOverflow. 💪

![Site search with site: method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r34kj9x2cjy7043ohhh1.jpeg)





# Multiple words
Search for multiple words using a plus sign.

![Multiple words search with plus sign](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fqozsya9qh7zzx7zzfh.jpeg)



# Exclude a word
The minus sign -  allows you to specify words that that shouldn't show up in your results.


![Exclude search word with minus operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iujd6hcw3ak6ih0njddy.jpeg)





# Related words
The tilde ~ operator searches for related words, not just the word you type.

![Related words with ~ method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9cribdjflol8b2axjc9.jpeg)





# Wildcard
The asterisk * is a wildcard. That means it can match any word! Combine it with the explicit search for awesome results.

![Wildcard operator method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rt2xfm5gkjnye04vllhx.jpeg)



# Time range
A lot of answers on the internet are outdated. Use a time range operator to narrow the scope.

![Time range method with .. operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2dow43vsz0055goutfdd.jpeg)




# File type
Narrow the scope of your search to a specific filetype! If you use operator filetype:pdf, you will get only PDF results!


![Search for specific file type with filetype: operator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9co4b7vkze0qv8gwjtk.jpeg)

# Advanced Search.
You can combine all of the above methods in <a target="_blank" rel="noreferrer" href="https://www.google.com/advanced_search">Google Advanced Search</a> 🤓

Thanks for reading!
Day 5 of 100 days of SwiftUI
Tags: 100daysofcode, 100daysofswiftui, swift
Published: 2021-03-19 06:55:32

Day 5 of HackingWithSwift's 100 days of SwiftUI. Today I learnt about functions. 

Functions in computer programming let us reuse code without repeating ourselves. In Swift, functions are written like this 
```
func addNumbers(first: Int, second: Int) -> Int {
    return first + second
}

let sum = addNumbers(first: 1, second: 2)
print(sum)
```
The code above contains a function that collects two numbers are parameters and returns their sum. To return more than one value from a function, you could simply return a tuple instead.

Functions in swift have many cool features like default, inout, and variadic parameter values.

Making a default parameter value in Swift is as simple as assigning a value to the parameter. For example
```
func getPhotos(from: String, quantity: Int = 30) -> [Photos] {
   // get photos from the internet and return an array of photos of size quanity
}

getPhotos("instagram.com")
getPhotos("instagram.com", 50)
```
The code above creates a function that gets an array of photos from the internet. By default, the number of photos to be gotten from the server is 30. By assigning `quantity: Int = 30`. if no argument is passed into the function, 30 would be used instead. That means `getPhotos("instagram.com")` gets 30 photos while `getPhotos("instagram.com", 50)` gets 50 photos

The `inout` keyword is used when you want to change the value of a parameter inside a function. By default in swift and, most programming parameters are constant. 
```
func squareNumber(number: inout Int) {
    number *= number
}
var value = 3
squareNumber(number: &value)
print(value)
```
For example, the code above creates a function that takes a number and squares it inside of the function. When calling the function you have to add `&` keyword. This means you are passing it into an inout parameter. Most of the time, it's best just to return a value from the function rather than using the inout parameter. 

With variadic functions, you can pass in any number of parameters. Variadic means the number of parameters varies. In swift a variadic parameter is written with an ellipsis.

```
func addNumbers(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
       sum += number
    }
  return sum
}

let sum = addNumbers(numbers: 1,2,3,4,5,6)
print(sum)
```


If you are interested in taking the challenge, you can find it at https://www.hackingwithswift.com/100/swiftui
See you tomorrow ;)
Little GRPC History
Tags: grpc, http2, http, tcp
Published: 2021-03-19 06:41:28

This post in based on another youtube video. I am writing my summery of the video's content.

### Learning:

Here the author explains why gPRC is being created. What type problem it going to solve, what are the problems with multiple client server communication protocol

### **Problem:**

There are so many client server protocol exits. Like, http/1, http/2, tcp/ip etc. These are the basic protocols which are used to communicate between multiple servers to server, server to client, client to client. But they are not languages agnostic. Their implementation of each programming language is very different. Plus there are so many libraries to support. If one protocol is being changed the whole supported library needs to adapt that feature and update the library. And the consumer also needs to adapt the libraries too.

### Solution:

So the gRPC solves the loads of client libraries for different protocols, different types of languages.

- One client side library for all languages. No need to change all libraries for new changes like before. It has a generator which will generate client side libraries for all types of major languages.
- It’s using http/2 under the hood. So no need to add new codes to adapt the changes for converting http/1 to http/2. Or in future if the protocol is being changed to http/3, it will be the same too for the client side.
- The messaging format is using protobuf or protocol buffers. So any client with supported grpc client libraries can communicate with each other


The original Link can be found here, [This is why gRPC was invented](https://www.youtube.com/watch?v=u4LWEXDP7_M)
SpectaQL - Autegenerated Documentation for GraphQL
Tags: graphql, node, javascript, githunt
Published: 2021-03-19 06:18:49

[https://github.com/anvilco/spectaql](https://github.com/anvilco/spectaql)

Writing and publishing good documentation on APIs is hard. That's why Anvil created and open sourced our Documentation Generator for GraphQL.

[Learn](https://www.useanvil.com/blog/2021-03-17-autogenerate-graphql-docs-with-spectaql) about the thinking behind this project.
A Complete Guide about Data Science Certification Course 
Tags: datasciencecertification, datascience, datasciencecourse
Published: 2021-03-19 06:14:16

Are you interested in Data Science and looking for the most significant details about the same by understanding the various scenarios? In this blog, you get detailed and related information on Data Science, the benefits of going for the Data Science Certification, how to achieve the online certification, and much more information.

https://www.careerera.com/blog/data-science-certification
Add Log to separate file
Tags: laravel, log
Published: 2021-03-19 05:59:54

Recently I got a a requirement to add separate log file for registration with details like ip and user agent. I did some research and found an awesome trick which is available built in to laravel.

The code looks like this.

```php
 Log::useDailyFiles(storage_path().'/logs/file_name.log');
//Log::useFiles(storage_path().'/logs/file_name.log'); alternative for single file
 Log::info([log  info]);
```
Reference
[Laravel : How to Log INFO to separate file](https://stackoverflow.com/questions/32552450/laravel-how-to-log-info-to-separate-file)
Seeing useMemo() speeds up our webpage
Tags: webdev, tutorial, react, usememo
Published: 2021-03-19 05:48:01

In some situations, we may not need to re-render a component every time.

For example, if a component depends on a number `n`, and our `n` doesn't change. Or, if the page footer is quite complicated, and we make it so that our page does not re-render it every time because it is the same every time, we can use `useMemo()`.

As an example, we are simulating a page footer here, and to add to its "work", we calculate `69!` (69 factorial). The value was the maximum number that can be displayed on a simple calculator.

Demo: https://codesandbox.io/s/vigilant-newton-5ocvf?file=/src/App.js

We can try clicking on the button to add the count on the page. The UI is quite responsive.

To experiment, let's increase the factorial to `30000!` (30,000 factorial), and here is a demo:
https://codesandbox.io/s/priceless-platform-ifigu?file=/src/App.js

We can see that every time we click on the button, the update on the page is really slow.  That's because the `Footer` component (or any costly component) is being re-rendered every time our `count` is updated.

(sidenote: it also feels much longer than the 0.36 seconds (as tested on a MacBook Air). This partly may be due to the `Footer` component has a really wide width to accommodate the number, so the browser has to spend a lot of resource to render it.  If we merely prints out the binary length of the number, it is quite faster: https://codesandbox.io/s/divine-https-i6chz?file=/src/App.js But to keep it as slow as possible, we will print out the whole number again in the example below.)

So we can use `useMemo()` to memoize the component (memoizing what `Footer` returns).

```js
const myFooter = useMemo(() => <Footer n={30000} />, []);
```

Demo: https://codesandbox.io/s/brave-noyce-zby1w?file=/src/App.js

Here, we are saying this component doesn't not depend on anything, so we provide an empty array at the end of `useMemo()`. If for any reason we depend on some value to render this component, we'd add it to this array. This is similar to how `useEffect()` works for its dependency array.

So here, when we click on the button, the page updates close to instantly, without going through the steps of getting the result from the `Footer` rendering.

Reference: https://reactjs.org/docs/hooks-reference.html#usememo (Official docs)

P.S. It is Sept 2023 right now, and I am using a MacBook Air M2. The original "slow" app is taking only 0.09 seconds to re-render, so the unresponsiveness cannot be felt as easily.  To change that, I have changed it to `60000!` (60,000 factorial), and also display only the length of it, so that we are not testing the webpage needing a super wide area to display the number.  The example is at:

https://codesandbox.io/s/priceless-platform-ifigu?file=/src/App.js

and the version using `useMemo`:
https://codesandbox.io/s/cranky-kare-fgp48m?file=/src/App.js
Prometheus Alerting Rule for Redis Clients
Tags: technology
Published: 2023-03-01 18:37:08

---
title: Prometheus Alerting Rule for Redis Clients
published: true
date: 2021-03-19 05:13:35 UTC
tags: technology
canonical_url: https://blog.hadenes.io/post/prometheus-alerting-rule-for-redis-clients/
---

Originally posted at https://blog.hadenes.io/post/prometheus-alerting-rule-for-redis-clients/

Recently, a customer auto scaling farm got out of hand due to a misconfiguration on their end, which led to Redis maximum number of connections to be exceeded, leading to a lot of requests failing.

Curiously, they were way below the default maximum number of clients of `10000`.

After some digging up, it turns out that each client needs one file descriptor (well, that would have been easy to guess…), so they failed when they reached the default `nofile` limit of 1024.

The [Redis documentation](https://redis.io/topics/clients) states the following:

```
In Redis 2.6 this limit is dynamic: by default it is set to 10000 clients, unless otherwise stated by the `maxclients` directive in Redis.conf.

However, Redis checks with the kernel what is the maximum number of file descriptors that we are able to open (the _soft limit_ is checked). If the limit is smaller than the maximum number of clients we want to handle, plus 32 (that is the number of file descriptors Redis reserves for internal uses), then the number of maximum clients is modified by Redis to match the amount of clients we are _really able to handle_ under the current operating system limit.

```

After the configuration error was fixed, we needed to ensure that never happened again, so I came up with this Prometheus alert rule to prevent that, based on the excellent set of rules from [Awesome Prometheus](https://awesome-prometheus-alerts.grep.to/rules#redis):

```

alert: RedisTooManyConnections
expr: (sum by (instance) (redis_connected_clients + 32)) > (sum by (instance)
  (process_max_fds{job="node"} * 0.8))
for: 2m
labels:
  severity: warning
annotations:
  description: |-
    Redis instance has too many connections
      VALUE = {{ $value }}
      LABELS: {{ $labels }}
  summary: Redis too many connections (instance {{ $labels.instance }})

```

This will alert if they reach 80% of the total available connections.
Java vs Python a Simple Comparison Part-2
Tags: java, programming, python, android
Published: 2021-03-19 05:10:56

#Part 1 is [here](https://dev.to/ksnc_cxcx_a_ssszs_s_s/java-vs-python-a-simple-comparison-part-1-5cc3)

#Note: These are my opinion only

So lets continue<br>

#Advantages of Python *(part 1)*
• The most important feature of python is its easy readable syntax.
• Also python is object oriented and supports classes. But it is not necessary to create classes.
• Python can be used to build windows, linux and macOS apps easily.

#Advantages of Java *(part 1)*
• Java is very easy, readable and supports every platform including windows, mac, Linux, android etc.
• Java is object-oriented, robust and more secure that python.
• Java is the most popular programming language in the world, which runs millions of devices.
• Java is not only in the earth, but also in some planets. I mean java is used by NASA to program spacecrafts like perseverance rover.

*to be continued*
How Many Servers Do You Need for a Crucial Website?
Tags: devops, jokes
Published: 2021-03-19 04:55:30

A crucial website ought to have:

* a primary server: Ryzen CPU, NVMe storage.
* a secondary standby: Xeon CPU, SSD storage.
* a third replica: Atom CPU, spinning rust storage.
* a fourth backup: ARMv5 CPU, VHS tape.
* a system to automatically perform failover.
* a cat to look over this system.
* a robot to feed the cat.
* an engineer to repair the robot.

These can get your data 99.99% secure.

Now add some cold storage:

* punch cards kept in California.
* microfilm buried in Antarctica.
* vinyl record launched to Jupiter.

If all four online servers are lost, you are looking at a lengthy downtime, but your data would be 99.9999% secure by recovering from the cold storage.

To finally reach 100%, transmit your data as radio waves toward a black hole.
If California fells into the ocean, Antarctica melts, and the sun explodes taking out Jupiter, you can travel to the black hole and access your data.

According to physics, information cannot be destroyed by a black hole.
It's the ultimate storage with infinite space.
Once you enter the black hole, you won't be able to come back, but you are with your data forever.
TIL Godot 3D in 2D Basics
Tags: todayilearned, gamedev, godot, ui
Published: 2021-03-19 04:41:03

2021-03-18

So for my game tool, I want text to drive 3d cubes (what *is* this dude making??). Basically the UI needs to manipulate a 3D scene.

So I made a new project to try and prototype this, anticipating unknown complexities and hurdles.
I have to tell you, Godot's infrastructure made this unbelievably easy. This is the result and it took very little to setup.
![UI Element on the left, 3D scene on the right](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xk24x2pew5w9b819x9d.png)

Steps of Construction?
Step 1: Setup your 3D scene. I just dropped a rotating cube and camera.
Step 2: Setup your 2D scene with your desired controls
Step 3: Add a Viewport Container
Step 4: Add a Viewport child to the Viewport Container
Step 5: Set a desired Size for the Viewport
Step 6: Drag and drop your 3D scene onto this Viewport

And that's it. Of course, manipulating it is another story. Stay tuned!
![Scene hierarchy and file system above 2D view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x4rom5hl71tqi2e60p8t.png)