teleren/devto huggingface dataset:
リーダブルコード 1-2 章 理解し易いコードの基本定理と変数名の決め方
Published: 2022-03-20 16:32:16


## この本の何が良いのか

Java や C++ の知識は必要ない、何がわかり易いコードなのかがわかってくる。

例題は殆どが具体的でわかり易い。

是非買って読みましょう！

---

## どこで買ったのか

https://www.oreilly.co.jp/books/9784873115658/

オライリー公式ストア、電子版 PDF 2112 円

kindle にはない。

---

## なぜ読み始めたか

カエデ 「よし、これで実装できたぞ！ しっかりと要件は満たしてるし、Pull Request 提出っと！」
レビュワー「ここの変数名、何でこれにしたんですか？気持ち悪いって思わない？ こういうのやめてほしいんですよね、レビューにコスト、人件費が余分にかかってる認識を持ってください」

と、変数の命名で厳しい指摘を受けたため。

---

以下にフロントエンドのジュニアエンジニアな私が書いてあって理解できたことをまとめた。

# U01 理解しやすいコード

## 1.1

```ts
{ flag ? x + x : x * x }
```

このような三項演算子よりも

```ts
if (flag) {
  return x + x
} else {
  return x * x
}
```

このような if 文のネストの方が見やすいと書いてある

## 1.2

基本的な考え方として、

> コードは他の人が最短時間で理解できるように書かなければいけない。

という基本定理があるらしい。

自分が最短時間で理解できるコードでもダメで
他人が時間をかければ理解できるコードでもダメ

だと解釈する。

また、6ヶ月後には自分のコードでも他の人のコードに見えることがあるという。

---
---

# U02 名前に情報を詰め込む

## 2.1

GetPage をやめて FetchPage か DownlaodPage にするべき

Class のなかの Size() は何のサイズかわからないので
Height(), MemoryBytes() などにするべき

Stop よりも
取り消しできない場合は Kill で
再開できる場合は Pause にする

send よりも dispatch　や route
make よりも create や generate や add

などと明確な関数名を使うべき。

---

## 2.2

中間的な役割で、すぐに破棄されるにしても

```java
returnValue += [i] * v [i]
```

だったら 

```java
sum_squares += [i] * v [i]
```

にしたほうが違う動作を間違えて書いてある時にデバックしやすい。

```java
temp = user.name
temp += user.phone_number
temp += user.email
```

だったら temp は user_info にするべき。

---

## 2.3

デバック情報を印字してサーバーを動かす --run_locally のオプションは
--extra_logging にするべき

---

## 2.4

start が ミリ秒であれば start_ms
delay が 秒であれば delay_secs 
size が メガバイトであれば　size_mb

のように、単位があれば単位も追加すべきだし

エスケープ前のコメントは unescaped_comment
暗号化前のパスワードは plaintext_password
utf8 に変えた html は html_utf8 

のように、重要な情報があるデータはその補足を変数名に入れるべき。

---

## 2.5

めちゃくちゃ長い名前を安直につけてはいけない

スコープ、その関数の行数が短ければ短めの名前でいい
しかし、スコープがとても長かったりグローバルだったら長くても一目瞭然名前にするべき。

無意味な動詞をつけてはいけない

ConvertToString は ToString 
DoServerLoop は ServerLoop 

にするべき。

---

## 2.6

C++ の場合だと
クラス名は CamelCase
クラスのメンバ変数(プロパティ)は member_
変数名は lower_separated
定数名は kConstantName

というように、物によってフォーマットを変える方針もある。

---

## 2.7

とにかく変数名を見ただけで情報がわかるようにコードを書こう！


3章の誤解されない関数名編にに続く！
PCA with Cricket Analytics and AWS SageMaker in 15 minutes
Tags: aws, sagemaker, datascience, pca
Published: 2022-03-20 16:23:03

🎁 Best Bowler in Indian Premier League [ Cricket ] 2020 season using PCA 
🎁 Principal Component Analysis  concepts
🎁 Usage of AWS Sagemaker and PCA
🎁 Code  and Data Files in the comments
https://github.com/ambarishg/sagemaker has the code and data files

{% embed https://www.youtube.com/watch?v=InTBvFRzz-0&t=42s %}
Clean up resources with kube-janitor
Tags: kubernetes, cleanup, tooling, tip
Published: 2022-03-20 16:22:37

##### About
Clean up (delete) Kubernetes resources after a configured TTL (time to live)

##### Implementation
The application is deployed as a deployment with escalated privileges. It listens to API requests to the API server, has an internal schedule queue (probably) and then deletes resources upon a rule match.

##### Reference repo
https://codeberg.org/hjacobs/kube-janitor.git

##### Installation

```bash
# pick files from https://codeberg.org/hjacobs/kube-janitor/src/branch/main/deploy/
# update rules.yaml as necessary
> cat rules.yaml
rules:
# remove deployments and statefulsets with a "demo" label set after 3 days
- id: cleanup-demo-objects
  resources:
    - deployments
    - statefulsets
  jmespath: "(spec.template.metadata.labels.demo)"
  ttl: 3d
# remove all deployments and jobs named "pr-*" after 6 hours
- id: cleanup-pr-deployments
  resources:
    - deployments
    - jobs
  jmespath: "starts_with(metadata.name, 'pr-')"
  ttl: 6h
# delete all resources within the "temp-*" namespace after 3 days
- id: cleanup-temp-namespaces
  resources:
    - namespaces
  jmespath: "starts_with(metadata.name, 'temp-')"
  ttl: 3d
# delete all PVCs which are not mounted and not referenced by StatefulSets after 4 days
- id: remove-unused-pvcs
  resources:
    - persistentvolumeclaims
  jmespath: "_context.pvc_is_not_mounted && _context.pvc_is_not_referenced"
  ttl: 4d

> kubectl apply -k .
```

##### Configuration
There are 3 ways of using this tool

1. Annotate the object with a `janitor/ttl` annotation. Useful for CI/CD scenario
` > kubectl annotate deploy test-app-dep janitor/ttl=24h`

2. Annotate the object with a `janitor/expires` annotation. Useful for dangling jobs/cronjobs
` > kubectl annotate deploy nginx janitor/expires=2022-03-31`

3. Update the rules file (edit it and (re)deploy or `> kubectl edit configmap kube-janitor`). This is the server side automation applicable for policy enforcement
- refer `rules.yaml` for example
- use jmespath for writing rules (refer [this](https://jmespath.org/specification.html))

Note:
- namespace level cleanup is not working and there is a PR to add this enhancement

##### More info
- [Sample usage in tekton pipeline scenario](https://git.cluster.fun/AverageMarcus/cluster.fun/commit/0d20f06cc790dea688c28e5a195cdc65c7dbc921)
 
---
Fascinating to see a python application working almost as a kubernetes CRD without all the complexities.
H2(In-Memory) Database With Spring Boot
Tags: h2, spring, springboot, junit
Published: 2022-06-16 17:11:36

---
title: H2(In-Memory) Database With Spring Boot
published: true
date: 2022-03-20 16:15:13 UTC
tags: h2,spring,springboot,junit
canonical_url: 
---

1. **Introduction:**

In this article, we will learn how to integrate the H2 in-memory database with spring-boot.

As H2 is an in-memory database, it relies on system memory & not disk space to store the data. We use the in-memory database when we do not need to persist the data. Usually, the in-memory databases are volatile, by default, hence data will be lost if an application is restarted.

**2. Use Case**

It is primarily used for running application test cases by the development team. When changes are made to the codebase, run automated test cases, and when it involves DML operations, H2 Database Engine is used instead of a full-blown database such as PostgreSQL.

**3. Tool(s)/Framework(s):**  
- Any java project tool suite like Spring tool suit, eclipse, IntelliJ  
- JDK 8 or above  
- Spring-boot

**4. Spring-boot & H2 database setup**

**4.1 Maven Dependencies**

> <dependency>  
> <groupId>com.h2database</groupId>  
> <artifactId>h2</artifactId>  
> <scope>runtime</scope>  
> </dependency>

**4.2 Configuring H2 DB**  
 Please refer to the below properties(application.yml) to configure H2 DB.

![](https://cdn-images-1.medium.com/max/833/1*enKsFfAXpubwetwBPUxmcQ.png)
_application.yml_

From the code snippet of application.yml below, the configuration is almost the same as using any other relational DB. The most important properties are driver class name, database platform & h2 console. please refer to the inline comment for further details.  
   
4 **.3 Testing**   
 we can test the H2 database via accessing the “[http://localhost:8080/h2-console/](http://localhost:8080/h2-console/)" URL. you can enter the username/password which was set during database setup in application.yml &

![](https://cdn-images-1.medium.com/max/492/1*yzle1LTgEd0CDuAEfpWPiQ.png)
_H2 Database login screen_

Once required credentials are entered, you can click on the “Test Connection” to verify H2 DB connectivity.

![](https://cdn-images-1.medium.com/max/499/1*X8e6bgyzn-hkQChQ2SA-Fw.png)

**5. Key takeaways**

- Very easy to use
- Lightweight and fast.
- Supports standard SQL and JDBC API.
- Provides a web console to maintain in the database.
- Small footprint − ~1.5MB jar file size

**GIT repo:**

[https://github.com/shethaptech/spring-boot/tree/main/h2-service-example](https://github.com/shethaptech/spring-boot/tree/main/h2-service-example)
Identify the Active Controller In Kafka
Tags: kafka, container
Published: 2022-03-20 16:08:03

### What is Controller?

The Controller is one of the kafka broker's, usually behaves as a normal broker and having a controlling capability of managing partition state and replicas and reassignment of the partition.

### How to get the current active controller?
Zookeeper is the storage of the kafka cluster, who elects the controller node either in the beginning of the cluster setup or when the controller node crashes. Here is the command to get the controller

- Shell command when installed on the host
```
zookeeper-shell 192.168.1.1:22181 get /controller
```
- When we are dealing with the docker container we can execute the above command in interactive mode as follows
```
# Connect to Zookeeper
docker run --net=host --rm confluentinc/cp-kafka:4.0.0 zookeeper-shell 192.168.1.1:22181

# Get the Controller
docker run --net=host --rm confluentinc/cp-kafka:4.0.0 zookeeper-shell 192.168.1.1:22181 get /controller
```

> Note:  `192.168.1.1` is the zookeeper IP
fixed length queue
Tags: python
Published: 2022-03-20 16:04:20

To create a fixed length queue and to discard old values as you and new values

```python
from collections import deque

dq = deque(maxlen=5)

for i in range(10):
    dq.append(i)

print(dq)
```

Output:
`deque([5, 6, 7, 8, 9], maxlen=5)`
HTML5 is the Future of Web Design! But What is it? A blog about HTML5 and how it's changing the web.
Published: 2022-03-20 16:02:00

If you have heard of HTML before, but don't really know what it is just yet. HTML is a markup language you can use to build websites and applications. You are probably thinking, “why do I need more than one language to build a website?” The answer is simple: HTML and CSS work together to provide the structure of your website while providing the styles and other visual hooks that can be accomplished with CSS.

 The web has changed a lot over the past two decades. We've gone from just hyperlinks and paragraphs to fully multimedia experiences that can only be created with HTML, CSS, and PHP (or JavaScript). So, as part of the HTML5 standard, we have a whole new way to build these beautiful experiences.

 HTML5 is an upcoming major version of the HTML standard. It introduces several new elements and extends many of the existing elements. 

HTML5 is a major revision of the HTML standard. It includes new structures and tags, such as 

```
<section>, <time>, and <article>
```
 It also provides support for multimedia and more semantic markup.  The main goal of HTML5 is to create a standard that can be used across all devices, including mobile phones and tablets. 

The new elements in HTML5 can be used to make your website more semantic, or “meaningful” for the browser to be able to read the website. This means that instead of using tags like <div> to organize your content, you should use the new semantic tags that HTML5 has introduced.  Here is a list of some of the new elements;

```
<header>, <section>, <article>, <time>, <nav>, <footer>, <aside, <figcaption>

```
 etc.

 

HTML5 also helps with accessibility with the introduction of attributes such as alt. For example, people who use screen readers can more easily navigate your site because they are able to find what they need by reading the tags instead of just relying on images and CSS styling.  Lastly, search engines such as Google will be able to better understand what is going on in each section of your page and determine how relevant it is to their users.

 One important thing to note is that while HTML5 has introduced many new tags, it hasn’t removed any of the old ones.  So you can still use the 

```
<div>
```
 and other legacy tags if you want to.

You can read more about how to use HTML5 elements here: https://developers.google.com/webmasters/guides/best-practices#semantic_markup.

Although it's quite complex, understanding HTML5 is well worth the effort considering the newest and coolest features that it brings. For example, you can now create interactive elements that respond to user input. This means that you can make buttons that change color or move around the page when a user clicks them.
Redux Toolkit
Published: 2022-02-25 11:23:04

# What is Redux?

Redux is a predictable state container for JavaScript apps. As the application grows, it becomes difficult to keep it organized and maintain data flow. Redux solves this problem by managing the application’s state with a single global object called Store.


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

## Redux Workflow
Redux workflow is made of 3 main components. They are:
1. **Store:** Central store from where all states are saved and managed. As usual, a reasonable application has only one store.
2. **Actions:** Actions are pure JavaScript objects that have specific properties. The property contains an action type and info that need to be updated in the state. Depending on the application a lot of actions happened.
3. **Reducers:** Reducers are pure JavaScript functions that perform the action to update the state and return the new state. It takes the current value of a state, takes the action depending on the action type, and returns the new state.
Finally, the state is updated in the store where all of the states are managed.

## What is Redux Toolkit?

The Redux store setup and the basic configuration to use in an application are similar. It is a waste of time matter to write the same script for different applications. Sometimes it’s a possibility to make mistakes. In a bigger application, there may be other packages needed to configure the Redux. Considering these matters, the needed packages and the basic configuration for the Redux setup are extracted and build a new package, which is Redux Toolkit.
In Redux Toolkit, the basic structure of the Redux and its needed packages are included, which makes our code and folder structure more understandable and organized.
#66 Days of Data
Tags: python, datascience, 100daysofcode, ankitgupta
Published: 2022-03-20 15:45:04

## **Learning Python**  👨‍💻

D 36 of #66daysofdata 📈

Today I have learnt Python Functions - Lambda Functions, Decorators, Generators!

Checkout 👉 [My #66 Days of Data timeline on Github](https://github.com/mrankitgupta/66DaysOfData)

Say me Hi! 
I'll be glad to connect on 
👇

**Twitter** @ [Mr_AnkitGupta01](https://twitter.com/Mr_AnkitGupta01)

**Github** @ [MrAnkitGupta](https://github.com/mrankitgupta)
How to Use Supabase Apple OAuth in React Native
Tags: javascript, reactnative, supabase, oauth
Published: 2022-03-20 15:14:20

[Supabase](https://supabase.com/) combined with [NextJS](https://nextjs.org/) or [Expo](https://expo.dev/) makes spinning up a side project in a few hours possible.

Supabase recently added a tutorial for Expo and support for Apple OAuth authentication. However, Apple OAuth does not work out of the box with Expo and Supabase. So I figured I'd write this article and create a [GitHub template](https://github.com/dancrtis/supabase-tailwind-rn).


![GIF of Sign in with Apple in template](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mwba6quxa7j8ry45iw14.gif)

## Supabase and Expo

I followed [Supabase's Expo quickstart]( https://supabase.com/docs/guides/with-expo) to get basic authentication working in Expo. The quickstart does not mentioned AsyncStorage which is required in `lib/supabase.js` to get it working.

My final code: 

```js
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createClient } from '@supabase/supabase-js';

// https://reactnative.dev/docs/security#storing-sensitive-info
import { supabaseUrl, supabaseAnonKey } from './supabase-keys';

export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
  localStorage: AsyncStorage,
  detectSessionInUrl: false
});
```

## Supabase Apple OAuth with Expo

Next I followed [Supabase's tutorial for Apple authentication](https://supabase.com/docs/guides/auth/auth-apple). I tried to use Supabase's sign in method onClick in my React Native auth component, which doesn't work:

```js
const { user, session, error } = await supabase.auth.signIn({
  provider: 'apple'
});
```

The user/session/error all will be `null`. I was a bit worried Apple OAuth on mobile wouldn't be supported by Supabase's Go True library, but I stumbled upon a PR which adds support [Fix: Add id_token grant flow](https://github.com/supabase/gotrue/pull/189)

Instead of using Apple as the provider I decided to use Expo's authentication library to get a token and then pass that to Supabase:

```js
import { startAsync, makeRedirectUri } from 'expo-auth-session';

import { supabase } from '../lib/supabase';
import { supabaseUrl } from '../lib/supabase-keys';

const signInWithApple = async () => {
    const returnUrl = makeRedirectUri({ useProxy: false });
    const provider = 'apple';
    const authUrl = `${supabaseUrl}/auth/v1/authorize?provider=${provider}&redirect_to=${returnUrl}`;

    const response = await startAsync({ authUrl, returnUrl });

    if (!response || !response.params?.refresh_token) {
      return;
    }

    await supabase.auth.signIn({
      refreshToken: response.params.refresh_token
    });
};
```

The full code is [available on GitHub](https://github.com/dancrtis/supabase-tailwind-rn). Apple OAuth with Supabase and support for React Native is relatively new. Feedback is always welcome if there's a better way of doing things.
Everything as an expression
Tags: functional
Published: 2022-03-20 15:06:29

In my journey of learning F#, I have come across the concept of "everything is an expression" which was an eye-opening experience for me. Now before I go into more details, let's just clear up the difference between an expression and a statement.

I like to think of an expression as anything that evaluates to a value. This includes arithmetic operations, ternary operators, function results, etc.

```javascript
// arithmetic expression that evalues to 36
5 * 6

// function call that evalues to 120
factorial(5)

// ternary operator that evalues to 9
isEven(11) ? 8 : 9 
```

Notice how all of these evaluate to a value that could be stored in a variable. Now let's look at some examples of a statement.

```javascript
// assignment
let b = 7

// branching
if (x % 7) {
    // some code goes here
} else {
    // some code goes here
}

// loops
while (true) { /* some code */ }
for (let i = 0; i < 10; i++) { /* some code */ }
```

let's say you are designing a new language and you don't like this arbitrary distinction between expressions and statements, what can we do to fix this without making the language unusable?

We can start by combining if-statements and ternary expressions into one by making if-statements return the last value in their bodies.

```reasonml
let a = if (b > 10) {
    /* some code */
    5
} else {
    /* some code */
    3
}
```

> You can refer to [Binding and continuations in ML](https://dev.to/ducaale/binding-and-continuations-in-ml-5d3e) for why blocks expressions evaluate to the last value in their bodies.

What about while/for loops? their functionality can be easily replicated by recursion so let's get rid of them. For example, the following:

```javascript
let i = 0;
while (i < 10) {
    print("hello world")
    i++
}
```
could be converted to use recursion like this:

```reasonml
let loop = (i, end) => {
    if (i < end) {
        print("hello world")
        loop(i + 1, end)
    }
}

loop(0, 10)
```

This leaves us with let-statements. in ML languages, we have let-in expressions which is inspired by [Mathematics](https://missmorrisblog.wordpress.com/2012/02/01/math-writing-let-statements-for-word-problems/)

```ocaml
(* this is the same as (5 * 5) + 1 *)
let x = 5 in (x * x) + 1
```
Notice that in our previous example, we are not assigning to a variable. Instead, we say that `x` will stand for the value `5` in the expression after the `in` keyword.

Since let-statements take expression after the `in` keyword and since they are themselves expressions, we can do something like this:

```ocaml
let x = 5 in (let y = 6 in x + y)
```
if we remove the parenthesis and do a little bit of formatting, we would end up with something like this:

```ocaml
let x = 5 in
let y = 6 in
x + y
```

---

So why all of this is important? Well, I think grokking the concept "everything as an expression" is vital to understanding why pure functional programming languages tend to avoid mutations and side effects.
Change Directory to Git Root Directory
Tags: git, linux, unix
Published: 2022-03-20 15:13:06

---
title: Change Directory to Git Root Directory
published: true
date: 2022-03-20 15:05:52 UTC
tags: git,linux,unix
series: "Sunday Snippet"
canonical_url: https://clavinjune.dev/en/blogs/change-directory-to-git-root-directory/
---

 ![Sunday Snippet #9 change directory to git root directory](https://clavinjune.dev/img/sunday-snippet/image.png "Sunday Snippet #9 change directory to git root directory")


```shell
$ pwd
/tmp/bjora-project/backend/scripts/docker
$ cd `git rev-parse --show-toplevel`
$ pwd
/tmp/bjora-project/backend
```
[ Data Structure ] - Stack & Queue
Tags: algorithms, computerscience
Published: 2022-03-20 14:58:51

스택과 큐를 들어가기에 앞서, 자료구조에 대해 알아야 한다.

# 자료구조
자료구조의 정의는 인터넷에 널리고 널렸다.

내가 생각하는 자료구조는, **"섹시하게 데이터를 다루는 방법"**이다.

그 방법중에 스택과 큐가 존재하는 것이다.

자료구조는 서비스나 어플리케이션에서 필요한 데이터를 메모리에 어떻게 구조적으로 잘 정리해서 담아주고 관리하고, 최종적으로 가장 효율적인 방식으로 필요한 데이터에
빠르게 접근하고 추가, 수정, 삭제할 수 있도록 도와준다.

Stack(스택)과 Queue(큐)는 **ADT** 라고도 불린다.

# ADT
- ADT(Abstract Data Type), 추상적 자료구조.

**ADT는 자료구조의 한 형태인데,** 자료구조의 방법이 코드로 정의 된 것이 아니라 그 구조의 행동 양식만 정의된 것을 뜻 한다.

실제로 존재하지 않지만, 규칙을 제공한다.
덕분에 자료를 좀 더 구조적으로 생각할 수 있다.

스택과 큐가 그러하다.

큐와 스택은 배열 위에 어떤 규칙을 설정한 모습이다.

# Queue
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2o6tufatvhrtw1q2ddzl.png)
큐의 사전적 의미는 **줄** 또는 **줄을 서서 기다리를 것**을 의미한다고 한다.

따라서 일상생활에서 놀이동산에서 줄을 서서 기다리는 것, 은행에서 먼저 온 사람의 업무를 창구에서 처리하는 것과 같이 선입선출인 **FIFO(First In, First Out)방식**이다.

큐는 한쪽 끝에서 추가가, 다른 쪽 끝에서는 삭제가 발생한다.

#### Queue - Front
삭제 연산이 수행되는 곳을 프론트(Front)라고 한다.
이때, Front에서 수행되는 **삭제 연산을 디큐(dnQueue)**라고 한다.

#### Queue - Rear
삽입 연산이 수행되는 곳을 리어(Rear)라고 한다.
이때, Rear에서 수행되는 **삽입 연산을 인큐(enQueue)**라고 한다.

> 큐의 데이터들은 Rear로 들어와 Front로 나가고,
Front에 있는 데이터는 가장 먼저 들어온 데이터고,
Rear에 있는 데이터는 가장 늦게 들어온 데이터이다.

#### Queue - Ex)
1. 프로세스 관리
2. BFS(너비 우선 탐색) 구현
3. 은행 업무


# Stack
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vkgfctkwveb072hnlqtt.png)
스택은 **쌓아 올린다** 라는 의미를 가지고 있다.

책을 쌓는 것처럼 쌓아올리는 형태의 자료구조이다.
따라서 위 사진처럼, 정해진 한 방향으로만 쌓을 수 있고
그 곳을 통해서만 데이터에 접근이 가능하다.

#### Stack - Top
큐는 들어오고 나가는 방향이 다르지만,
스택은 한 방향에서 들어오고 나간다.

**이를 Top이라 한다.**

> 방향이 하나라,
가장 먼저 들어온 데이터는 맨 마지막에 나가게 되고,
가장 늦게 들어온 데이터가 가장 먼저 나가게 된다.

따라서 후입선출인 **LIFO(Last In, First Out)방식**을 따른다.

#### Stack - Ex)
1. 웹 브라우저 방문기록(뒤로가기)
2. 실행 취소(Undo)