teleren/devto huggingface dataset:
After Login redirect Back to post where you are reading without login
Tags: javascript, react, queryparam, webdev
Published: 2022-09-25 14:05:59

Hi Guys
Back with another real-life scenario in software development.

Do you know when you are scrolling to some famous websites like LinkedIn, Facebook, etc without logging in?

And when you want to comment or like a post but that requires a login and After login, the website will take you to the same post or Article

How did this happen?

It is actually very easy to do,

just append the URL of the post as a query parameter in the login URL.

`const goToLoginPage=()=>{
router.push(`/login?redirectTo=${router.asPath}`);
}
`
And in the login API function just checks if the URL contains this param and then send the user to this route

`async function loginUser(){
const { redirectTo } = router.query;
const res=await loginApi(); ;
if(res.success){
router.push(redirectTo ?? '/');
}
}`
Golang 101: Metotlar (Methods)
Tags: go, methods
Published: 2022-09-25 13:56:04

Yapıların girdi olarak verildiği fonksiyonlar `method` olarak tanımlanır. Böylelikle yapıya özel işlemleri nesne yönelimli programlama da olduğu gibi kullanım kolaylığı sağlar.

```golang
package main

import (
	"fmt"
)

// Yapı
type dikdortgen struct {
	genislik  int
	yukseklik int
}

// Metotlar
func (d *dikdortgen) alan() int {
	return d.genislik * d.yukseklik
}
func (d dikdortgen) cevre() int {
	return d.genislik + d.yukseklik
}

func main() {
	// Yapıyı tanımlama
	d := dikdortgen{genislik: 10, yukseklik: 8}

	// Metodların kullanımı
	fmt.Println("Alan:", d.alan())
	fmt.Println("Çevre:", d.cevre())
}
```
```
Alan: 80
Çevre: 18
```
[çalıştır](https://go.dev/play/p/JGNrIViw3HC)

## Yapı tanımlama
```golang
type dikdortgen struct {
	genislik  int
	yukseklik int
}
```
Dikdörtgen için öncelikle bir yapı `struct` tanımlaması oluşturuyoruz.

## Metot ile Alan/Çevre Hesaplama
```golang
func (d *dikdortgen) alan() int {
	return d.genislik * d.yukseklik
}

func (d dikdortgen) cevre() int {
	return d.genislik + d.yukseklik
}
```
alan() ve cevre() metotları `dikdortgen` yapısında alıcıya sahiptir. Bu da yapıya özel fonksiyon tanımlama yöntemidir ve sadece bu yapıya sahip tanımlamalar ile kullanılabilir. Pointer ile tanımlanabilir ve bu yapının kopyası yerine üzerinde çalışmanıza izin verir.


## Kullanımı
```golang
	// Metodların kullanımı
	fmt.Println("Alan:", d.alan())
	fmt.Println("Çevre:", d.cevre())
```
Metotlar `yapı.fonksiyon()` şeklinde kullanılmaktadır.
Resume tips I learned from the internet
Tags: resumewriting, beginners, career
Published: 2022-09-25 13:53:41

## Intro

I have been digging the internet for my resume creation, as a fresher, it can be hard on what to add to your resume so that it doesn't look empty and as well as to make it like that it doesn't have too much irrelevant information

> try going through this list before sending in your resume to companies

## Tips

### General

- Try to modify your resume according to the company or job you are applying

- Try creating 2,3 versions of your resume and use them accordingly: one can be on your preferred tech stack, and one can be modified using the job description

- No too much personal info

- Check for spelling mistakes

- Make sure the contents are relevant to the job posting

- Make your project descriptions small

- Make sure you know the contents of your resume, the technologies you used, project explanations, etc...

- Make it parser friendly

- Always Send it in PDF format

- Add hyperlinks to stuff like LinkedIn or GitHub account or portfolio site

- Add a live site link and GitHub links to the projects you are mentioning


### Layout

- Keep sections in order as, objectives, skills, projects, education, and hobbies

- Try to differentiate your skills in sections: Technical Skills or Other Skills separately, try not to add Microsoft office and OS

- Add links to GitHub and LinkedIn

- Make it a Single Page Resume

- Have your best 2,3 projects in the project section

- Use bullet points as much as possible

- Don't put any random hobby in the hobbies section

- Try to make the career objective max 2 lines, or if possible don't put it

- In the education section, if possible don't add your percentages, just your College name, your degree ad the passout years


### Design

- Keep it black and white ( Can be changed if applying for designer jobs )

- Keep it readable: no fancy fonts, no too much bold text


## Conclusion

These are just some of the tips I got through my resume reviews and looking at other people's resumes, do add  your own to this list if you don't find any here

---

**If you found the content i share useful then share it with your developer friends and also follow me on [Instagram](https://www.instagram.com/gaurav_vaala/) and [Twitter](https://twitter.com/gaurav_vaala)**
Creating a Role in Postgres Properly
Tags: postgres, database
Published: 2022-09-25 13:10:51

Here's how to create a role that can log in, but don't give it a password:

```sql
CREATE ROLE nhatbui LOGIN;
```

And here is creating a role with a password that is valid until the end of 2022. After one second has ticked in 2023, the password is no longer valid:

```sql
CREATE USER nhatbui WITH PASSWORD 'st@bl3nhAt' VALID UNTIL '2023-01-01';
```

The syntax is fine. But what could possibly go wrong? Oh dear, your password will appear as plain text somewhere in the log file; it can be stolen in no easier way. To do it properly, we first create a role that can log in but don't give it a password:

```sql
CREATE ROLE nhatbui LOGIN;
```

Once the role `nhatbui` is created, we can then give it a password with this command (psql):

```sql
\password nhatbui
```

The terminal now will ask you to type in the new password. Just like other passwords, it will be hidden in the terminal. So just type without wondering. Here's what mine displays:

```sql
postgres=# \password nhatbui
Enter new password for user "nhatbui": 
Enter it again:
```

---

As far as I am aware, Postgres will hash the password before storing it, unless the supplied string is already hashed. So you don't have to hash it manually.
Reduce cognitive load with Kotlin Extension functions.
Tags: kotlin, android, backend, mobile
Published: 2022-09-25 13:05:44

We are 80% reading the code and 20% writing the code. That's why we should take care about cognitive load which our code reproduce. One way is to write intuitive and readable code. 

A very useful Kotlin feature are Extensions functions. Let's see what extensions are and how to use it in your code to make it more readable.

"Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class."

If we want to check if some money amount is valid for transaction we can create simple check function that return a Boolean like this

```
fun isValidAmount(amount: BigDecimal) = amount > ZERO && amount <  PAYMENT_MAX_AMOUNT
```
or we should disable / enable some view from the screen

```
fun hide(amountView: View) {
  amountView.visibility = View.GONE
}

fun show(amountView: View) {
  amountView.visibility = View.VISIBLE

}
```
These two functions are absolutely correct but we can go even further with Kotlin extensions in order to make code a bit more intuitive and readable. Now let's see how these two functions will look like

```
fun BigDecimal.isValidAmount() = this in ZERO..PAYMENT_MAX_AMOUNT

//and applied in code
val amount = BigDecimal(1000)
if(amount.isValidAmount()) {
// make a payment
} else {
 //show message to the user
}
```
and hiding the view function will look like this

```
// Hides the view
fun View.hide() {
  visibility = View.GONE
}

// Shows the view
fun View.show() {
 visibility = View.VISIBLE
}

// Hides or show the view based on the flag
fun shouldShow(show: Boolean) {
  if(show) visibility.VISIBLE else visibility.GONE
}

// when applied 
if(amount.isValidAmount()) {
    amountView.show() 
} else {
    amountView.hide()
}

// or even further with one liner
amountView.shouldShow(amount.isValidAmount())
```
You can see how this improves readability in our code. 

Under the hood there is nothing special. If we decompile the Kotlin bytecode into Java source file we can see nothing but regular methods with passed arguments.
So there is no performance benefit, it's just a pure Kotlin synthetic sugar!

You can play with them and use it everywhere inside the app where you think that is necessary to improve readability. They are excellent for Utility classes where you need a lot of checks and validations.
AWS Java Lambda performance optimization
Tags: java, aws, lambda, performance
Published: 2022-09-25 13:00:19

## TL;DR
Add environment variable to AWS Lambda (Java) as below:
`Environment variable Name (Key): JAVA_TOOL_OPTIONS` 
`Environment variable Value: -XX:+Tiered Compilation -XX:TieredStopAtLevel=1`

## Details
AWS Lambda (Java) gets invoked (new execution environment scenario), then cold start time = a new JVM started time + application code loading time.

Let's see how one can reduce JVM start time that could eventually reduce the cold start time using Tiered compilation level of JVM.

Two types of JIT compilers available in the JVM. C1 type of compiler optimized for faster start-up time. Best suitable for short-lived applications. C2 type of compiler optimized for better overall performance. C2 compiler analyzes code for a longer period compared to C1 in order to producer optimized compiled code for better performance.

C1 compiler is best suits the need of AWS Lambda and here's how to instruct Lambda to use C1 compiler. AWS Console -> AWS Lambda service -> Environment variable section add the below key and value. Environment variable Name (Key): JAVA_TOOL_OPTIONS
Environment variable Value: -XX:+Tiered Compilation -XX:TieredStopAtLevel=1

Image by <a href="https://pixabay.com/users/openclipart-vectors-30363/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=151346">OpenClipart-Vectors</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=151346">Pixabay</a>
Beautiful contact by email button - A step-by-step guide
Tags: css, webdev, tutorial, html
Published: 2022-09-25 12:50:32

![Info hover button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vsdm8nv3gvjir3kqhhzd.png)

## <u>HTML</u>
For HTML, we need a div element with class "button" and two text elements inside with "@" svg between them.

```html
<div class="button">
    <span>info</span>
    <svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
        <path stroke-linecap="round" stroke-linejoin="round" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
    </svg>
    <span>designyff.com</span>
</div>
```

## <u>CSS</u>

For CSS, first we'll style a "button" class.

First, we'll align items using flexbox, and set cursor to pointer and width to 50px.

Now we'll set position to relative, background color to light blue and text color to white.

We'll add a little box shadow and white border of 1 pixel width with 100px radius.

Lastly, we'll add some paddings and transition.

```css
.button {
    display: flex;
    justify-content: start;
    align-items: center;
    cursor: pointer;
    width: 50px;
    position: relative;
    background-color: rgb(69, 165, 249);
    color: #fff;
    box-shadow: 0 0 40px #777;
    border: 1px solid #fff;
    padding: 10px;
    border-radius: 100px;
    transition: .5s;
}
```
      
On hover, we'll increase the width from 50 to 100px and add transition.

```css
.button:hover {
    width: 180px;
    transition: .5s;
}
```
      
Text elements inside a button will have the width of 0 and overflow hidden with a little transition.

```css
span {
    width: 0px;
    overflow: hidden;
    transition: .5s;
}
```
      
On hover, first text element (with "info" text) will become 28 pixels wide and we'll add a little transition so that this width change is smooth.

```css
.button:hover span:first-child {
    width: 28px;
    transition: .5s;
}
```
      
The second text element (with "designyff.com" text) will become 100 px wide, and with transition, this change will look nice and smooth.

```css
.button:hover span:last-child {
    width: 100px;
    transition: .5s;
}
```
      
And that is it.

You can find full code and video tutorial [here](https://designyff.com/code/email_contact_button).

Thanks for reading. ❤️
What is Enumeration in Python
Tags: enumerate, enumeration, python, list
Published: 2022-09-25 12:29:49

If you are a programmer, you may have seen this question. What is Enumeration in Python? A data collection object is transformed into an enumerate object using the enumerate function in Python. Enumerate produces an object with a counter serving as a key for each value in the object, making it simpler to retrieve the collection’s contents.

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

Read more at:
https://hecodesit.com/what-is-enumeration-in-python/
Unique Differences
Tags: perl, python, theweeklychallenge
Published: 2022-09-25 12:27:33

## Weekly Challenge 183

[Challenge](https://theweeklychallenge.org/blog/perl-weekly-challenge-183/), [My solutions](https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-183/sgreen)

Back after a short break :)

## Task 1: Unique Array

### Task

You are given list of arrayrefs.

Write a script to remove the duplicate arrayrefs from the given list.

### My solutions

The logic in the Python and Perl solutions is basically the same. For each item in the outer list, see if it has appeared earlier in the list. In Python comparing two lists works as expected. I don't believe there is a way to do this in Perl, so I wrote an function called `same_array` to see if two arrays are the same.

### Examples

```bash
$ ./ch-1.py "[[1,2], [3,4], [5,6], [1,2]]"
[1, 2], [3, 4], [5, 6]

$ ./ch-1.py "[[9,1], [3,7], [2,5], [2,5]]"
[9, 1], [3, 7], [2, 5]
```

## Task 2: Date Difference

### Task

You are given two dates, `$date1` and `$date2` in the format `YYYY-MM-DD`.

Write a script to find the difference between the given dates in terms on years and days only.

### My solutions

This is a little tricky. Date math is never fun. So off the bat, I'll note this is not time zone aware. That really would only be an issue for the few countries that [skipped a day](https://www.bbc.com/news/world-asia-16351377) in December 2011.

The basic logic goes as follows:

1. Make sure that `date2` is later than `date1`. The challenge does not mention in what order the date is specified.
1. Subtract the difference in the calendar years between date2 and date1, and store it as `years`.
1. If date2 is earlier in the year than date1, then subtract 1 from the `years` value.
1. Calculate the number of days between `date2 - $years year(s)` and `date1`. For Python, this is done using the [dateutils](https://github.com/jmcantrell/python-dateutils) module. In Perl, I use the [Date::Calc](https://metacpan.org/pod/Date::Calc) module.
1. Print the result. I'm having a bit of a brain fart on how to do this the correct way. I'm sure after I submit my pull request, I'll figure this out :)

### Examples

```bash
$ ./ch-2.py 2019-02-10 2022-11-01
3 years 264 days

$ ./ch-2.py 2020-09-15 2022-03-29
1 year 195 days

$ ./ch-2.py 2019-12-31 2020-01-01
1 day

$ ./ch-2.py 2019-12-31 2019-12-01
30 days
```
Towards cloud native dev...
Tags: python, gcp, airflow, beginners
Published: 2022-09-25 11:22:04

I am a Python developer with 15+ years of experience. I was working as automation QA engineer (created custom testing framework, modifying it and doing functionality testing) for 4+ years and as you would have guessed it, working on something for 4 years surely does take out charm / challenge out of it. So i was looking for new things and at the start of 2022 there was email about Python developer role in some other team. I jumped onto it and got it just based on recommendation.

So, this new role was with Quantitative research team, just to give my background, I am not good at math, specially math which only has letters in their equation :). One thing i was sure about my skills and i knew that i would learn anything for the task i am working on and produce result and improve them as i get more experience / knowledge.

I was happy that i will work with Scientific side of Python libraries (numpy, scipy etc.) and then with GCP (Google Cloud Platform). First task i started with was creating Pipeline to load data into bigquery for our ML Pipeline. I faced some design decision issues just because i was not following cloud native approach. 

1. Get requests to data server timing out after first 1000 requests.

I created fully functional local Airflow pipeline but it started timing out on GCP. Why? cause i was opening new socket for every request to save host! This would have worked fine only any VM or server but not on cloud. Though, i think i should have used Session from the start. **Learned why to use sessions**

2. Re-running airflow job

I must confess that choosing BigQuery (BQ) was not my decision. As BQ has no concept of duplicate / unique row concept, we needed to make sure that if we re-run job for some day it needs to first clean the data from BQ. So I was forced to think in a different way of how to structure the data, partition on column and then in case of re-run just drop the partition. But how to decide which partition to drop? all these decisions impacted my conventional developer thinking and helped me to think like **Cloud-Native developer**.

3. Do the backfill with starting date going back to 6 years back.

This i must confess was the hardest part of the whole pipeline. How would you one-off back-fill for past 6 years and then do it periodically if some data is corrupt for specific IDs. 

When i started with this development, I was very sure that this whole thing can be completed in 1 month but in reality, I had to learn about Airflow, Bigquery, GCP limitations and access rights! In the end, i spent close to 2.5 months to get this pipeline running in production. In the end, i was very happy that my first pipeline is working fine for 3+ months without having any issues.
Arduino IDE 2.0 的設定檔與變更字體
Published: 2022-09-25 11:19:18

Arduino IDE 2.0 已經正式發行, 相信大家都開始使用了, 不過如果你是像我一樣 C 磁碟都快滿了, Arduino IDE 2.0 預設的開發板套件儲存位置可能會很快就讓你的 C 磁碟爆掉。我自己比較偏愛可攜版的軟體, 不過 Arduino IDE 2.0 目前並沒有像是 1.X 版只要建立一個 portable 資料夾就能化身可攜版的功能, 因此本文說明如何修改設定, 建置一個接近可攜版的 Arduino IDE 2.0 環境。

## 下載 zip 格式的軟體

首先就是下載 zip 格式的軟體, 這樣未來要搬移或是複製到其他機器上都很方便。以下的說明對於安裝版的 Arduino IDE 2.0 也有效。

## 設定檔路徑

不管是安裝還是 zip 格式的 Arduino IDE 2.0, 預設會有 2 個設定檔, 都放在 `使用者資料夾\.arduinoIDE\` 下, 分別是：

|設定檔名|說明|
|---|---|
|arduino-cli.yaml|設定開發板套件下載位址與安裝位置、程式庫安裝位置、使用者的草稿碼儲存位置|
|settings.json|IDE 本身的環境設定, 像是字體大小、配色主題等等|

這 2 個設定檔並無法變更位置, 只能修改內容。

# arduino-cli.yaml

如果你希望 Arduino IDE 2.0 不要將開發板套件等等安裝到預設的位置, 就必須修改這個設定檔, 主要需要修改 `directories` 項目下的幾項設定：

|設定|說明|預設位置|
|---|---|---|
|builtin/libraries|Arduino 內建程式庫安裝位置|`使用者資料夾\AppData\Local\Arduino15\libraries`|
|data|開發板套件安裝位置|`使用者資料夾\AppData\Local\Arduino15\packages`|
|downloads|安裝過程下載的檔案暫存位置|`使用者資料夾\AppData\Local\Arduino15\staging`|
|user|草稿碼預設儲存的位置|`使用者資料夾\Documents\Arduino`|

我自己的作法是在 Arduino IDE 2.0 解開的資料夾下建一個 `data` 資料夾, 並且把 `使用者資料夾\AppData\Local\Arduino15` 底下的內容全部搬移到這個新建的資料夾, 再在其中建立一個 `schetches` 資料夾放置草稿碼, 並將上述設定全部指向 `data` 內的對應資料夾, 像是這樣：

```yaml
...
directories:
  builtin:
    libraries: D:\apps\PortableApps\arduino-ide_2.0.0_Windows_64bit\data\libraries
  data: D:\apps\PortableApps\arduino-ide_2.0.0_Windows_64bit\data
  downloads: D:\apps\PortableApps\arduino-ide_2.0.0_Windows_64bit\data\staging
  user: D:\apps\PortableApps\arduino-ide_2.0.0_Windows_64bit\data\sketches
...
```

這樣一來, 之後不論是安裝新的開發板套件或是程式庫, 都會安裝到 `data` 資料夾下, 也可以將整個 Arduino IDE 2.0 的資料夾複製到其他機器上使用。

# settings.json

Arduino IDE 2.0 的 **Prefences** 功能表有提供字體大小的設定, 但是卻沒有設定字型的功能, 如果你有偏愛的字型, 可以修改這個設定檔, 幫它新增 **editor.fontFamily** 項目, 指定要使用的字型：

```json
{
  "editor.fontSize": 16,
  "editor.fontFamily":"JetBrainsMono NF",
  ...
  "arduino.upload.verify": false,
  "arduino.sketchbook.showAllFiles": false
}
```

以上就是目前我會做的簡單設定, 希望也能對大家有幫助。
Make The String Great
Tags: javascript, leetcode
Published: 2022-09-25 11:11:20


```js
/**
 * @param {string} s
 * @return {string}
 */
var makeGood = function (s) {
  let stack = [];
  for (let i = 0; i < s.length; i++) {
    let nextChar = s[i];
    if (stack.length === 0) {
      stack.push(s[i]);
    } else if (
      stack[stack.length - 1]?.toLowerCase() === s[i].toLocaleLowerCase()
    ) {
      if (
        (nextChar === nextChar?.toUpperCase() &&
          stack[stack.length - 1] !== stack[stack.length - 1]?.toUpperCase()) ||
        (stack[stack.length - 1] == stack[stack.length - 1]?.toUpperCase() &&
          nextChar !== nextChar?.toUpperCase())
      ) {
        stack.pop();
      } else {
        stack.push(nextChar);
      }
    } else {
      stack.push(nextChar);
    }
  }

  return stack.length > 0 ? stack.join("") : "";
};

console.log(makeGood("lEeeetcode"));

console.log(makeGood("kkdsFuqUfSDKK"));

console.log(makeGood("abBAcC"));

console.log(makeGood("Pp"));

```
🚀 Angular 14 + ESLint, Material + Transloco + Jest, TestCafe + Docker + Prettier 🚀
Tags: angular, typescript, webdev, javascript
Published: 2022-09-25 10:45:25

This is **the** Angular 14 Starter project you are looking for!

## GitHub
https://github.com/wlucha/angular-starter

## Features
✅ [Angular 14](https://angular.io/)
✅ [Angular Material](https://material.angular.io/)
✅ Unit Testing with [Jest](https://jestjs.io/)
✅ End-to-End Testing with [TestCafé](https://testcafe.io/)
✅ Internationalization with [Transloco](https://github.com/ngneat/transloco)
✅ Auto documentation with [Compodoc](https://compodoc.app/) 
✅ Analyse your project with [source-map-explorer](https://www.npmjs.com/package/source-map-explorer)
✅ [Docker](https://www.docker.com/)
✅ [ESLint](https://eslint.org/)
✅ [Prettier](https://prettier.io/)
✅ [Commit Linting](https://github.com/conventional-changelog/commitlint)

## Demo
[![StackBlitz Demo](https://user-images.githubusercontent.com/7531596/83507657-2424e180-a4c9-11ea-8e4f-b3f8e7d6b4c5.png)](https://stackblitz.com/github/wlucha/angular-starter)

## Setup

```bash
# Clone the project
$ git clone https://github.com/wlucha/angular-starter
$ cd angular-starter

# Install dependencies
$ npm install

# Start server
$ npm run start

# Open in browser: http://localhost:4200
```

## Docker Deployment

```bash
# Build Docker image
$ docker build . -t angular-starter

# Run Docker Container
$ docker run -p 3000:80 angular-starter
```

## Docker Hub

https://hub.docker.com/r/wlucha/angular-starter

## Commands

- `npm run start` - start the app
- `npm run lint` - lint the project
- `npm run test` - run unit tests
- `npm run build` - build the project
- `npm run build:prod` - build the project in production mode
- `npm run build:prod:stats` - build the project in product mode with stats
- `npm run analyse` - analyse bundle with [webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer)
- `npm run compodoc` - generate [compodoc](https://github.com/compodoc/compodoc) documentation
- `npm run changelog` - generate changelog
- `npm run prettier` - format the whole project

**GitHub**
https://github.com/wlucha/angular-starter