teleren/devto huggingface dataset:
9章9
Published: 2024-04-09 04:22:18

このJavaのコードは`ArrayList`に対する操作を行っており、その動作を理解するには`ArrayList`の動作原理を知る必要があります。`ArrayList`は0から始まるインデックスを持ち、`add(index, element)`メソッドを使うと指定したインデックス位置に要素を挿入することができます。しかし、指定するインデックスがリストの現在のサイズを超えている場合は`IndexOutOfBoundsException`を投げます。

コードを見ると、まず"A"がリストに追加され、その後に`list.add(2, "B");`が呼び出されています。この時点でリストのサイズは1しかないので（"A"のみが含まれている）、インデックス2の位置に"B"を挿入することはできません。そのため、実行時に`IndexOutOfBoundsException`が発生し、選択肢Eが正しい答えとなります。

実際のコードにコメントを追加して説明すると以下のようになります。

```java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(); // 新しいArrayListを作成
        list.add("A"); // リストに"A"を追加 -> ["A"]
        list.add(2, "B"); // インデックス2に"B"を挿入しようとするが、
                          // リストのサイズは1なのでIndexOutOfBoundsExceptionが発生する
        list.add("C"); // このコード行は実行されない
        list.add("D"); // このコード行は実行されない
        for (String str : list) { // リストのすべての文字列を出力
            System.out.print(str); // このコード行は実行されない
        }
    }
}
```

ここで、`list.add(2, "B");`は、リストのサイズが2未満の時点で呼び出されているため、`IndexOutOfBoundsException`が発生し、それ以降のコードは実行されません。そのため、プログラムはエラーを出力して終了します。

## 追記

はい、`list.add(2, "B");` を `list.add(1, "B");` に変更することで、`IndexOutOfBoundsException` を発生させずにコードを正常に実行することができます。

`list.add(1, "B");` に変更すると、"B" がリストのインデックス1に挿入されます。インデックスは0から始まるので、この操作は"A"が追加された後の位置、つまりリストの最初の要素"A"の後に"B"を挿入することになります。

修正後のコードは以下のようになります：

```java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(); // 新しいArrayListを作成
        list.add("A"); // リストに"A"を追加 -> ["A"]
        list.add(1, "B"); // インデックス1に"B"を挿入 -> ["A", "B"]
        list.add("C"); // リストの末尾に"C"を追加 -> ["A", "B", "C"]
        list.add("D"); // リストの末尾に"D"を追加 -> ["A", "B", "C", "D"]
        for (String str : list) { // リストのすべての文字列を出力
            System.out.print(str); // 出力される文字列は "ABCD"
        }
    }
}
```

この修正により、コードは`ArrayList`の各要素を順に出力して、結果として`"ABCD"`を表示するようになります。
JS Bites: Chapter 1 - Async JS & Callback Functions
Tags: javascript, webdev, programming, tutorial
Published: 2024-04-09 04:31:34

**Welcome to JS Bites!**
This series is your bite-sized guide to mastering asynchronous JavaScript. We'll delve into concepts like callbacks, promises, and async/await

**How JS Runs (Synchronously)**
JavaScript code executes in a top-down manner, processing one line at a time. While this may seem fast to the user, allocating memory for each line can take some time behind the scenes. Each line relies on the previous line to finish executing before it can proceed.

Example:
```js
const food = "pizza";
console.log(food);
```

**Asynchronous Code**
Asynchronous code allows JavaScript to perform operations without blocking the main thread. This means the program can continue executing other lines while waiting for an asynchronous operation, like fetching data from a server, to complete.

Example:

```js
function asyncExample() {
  console.log("First");
  setTimeout(function() {
    console.log("Second");
  }, 2000);
  console.log("Third");
}

asyncExample();

// Output:
// First
// Third
// (after 2 seconds) Second
```

**Callback Functions**
A callback function is a function passed as an argument to another function. The receiving function can then invoke the callback later, often after an asynchronous operation completes.

Example: 

```js
function callWithCallback(callback) {
  setTimeout(function() {
    const result = callback(4, 6);
    console.log(result);
  }, 2000);
  console.log("First");
}

function callbackFunction(a, b) {
  console.log("Second");
  return a * b;
}

callWithCallback(callbackFunction);

// Output:
// First
// Second
// (after 2 seconds) 24

```
**Callback Hell**

Nesting callback functions deeply can lead to code that's difficult to read and maintain, often referred to as "callback hell."

Example:

```
Callback
   inside Callback
         inside Callback
              inside Callback
```

```js
function add(x,y){  
    return x+y  
}  
function subtract(x,y){  
    return x-y  
}  
function expectedResult(callBack, x, y){  
    return callBack(x,y)  
}  
console.log(expectedResult(add, 20, 10))      
console.log(expectedResult(subtract, 30, 10))
```

**Alternative Approaches**

While callbacks are a fundamental concept, techniques like Promises and Async/Await offer more structured and readable ways to handle asynchronous operations. We'll explore these alternatives in future chapters.

**Async Examples**

Asynchronous code is commonly used for tasks like:
- Fetching data from APIs
- Calling backend servers
- Loading external files
- Setting timers and intervals
Transform Your Digital Presence with CodeTrade's Custom Software Solutions.
Tags: softwaredevelopment, digitaltransformation, softwaresolution, software
Published: 2024-04-09 04:25:26


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

**CodeTrade** is a leading provider of [custom software development services](https://www.codetrade.io). We specialize in crafting [enterprise solutions](https://www.codetrade.io/enterprise-web-solution/) meticulously tailored to address your unique business needs.

Our team of [highly experienced and certified developers](https://www.codetrade.io/hire-dedicated-developers/) possesses the expertise to tackle even the most intricate software challenges. 

We partner closely with you to understand your specific requirements and leverage our knowledge to build the perfect software solution that empowers your business goals.
Introducing the Mini Punching Bag Your Compact Solution for Stress Relief
Tags: boxinggloves, boxingheadgear, minipunchingbag
Published: 2024-04-09 04:19:25

  In today's fast-paced world, stress has become an inevitable part of our daily lives. Whether it's the pressures of work, school, or personal relationships, finding healthy outlets to manage stress is crucial for maintaining mental and physical well-being. Enter the Mini Punching Bag – a compact yet effective solution for stress relief that packs a powerful punch.
Compact Design, Big Impact
The Mini Punching Bag is designed to be compact and portable, making it ideal for use at home, in the office, or even while traveling. Measuring just a few inches in diameter, it can easily fit on your desk, countertop, or any other small space. Despite its small size, don't be fooled – this miniature punching bag is built to withstand your toughest blows.
Stress Relief on Demand
With the Mini Punching Bag, you can release pent-up frustration and tension whenever you need it most. Whether you're feeling overwhelmed by deadlines at work or dealing with a challenging situation at home, a few minutes of punching and kicking can help you blow off steam and regain focus.
Physical and Mental Benefits
Regular use of the Mini Punching Bag offers a host of physical and mental benefits. Physically, it provides a great cardiovascular workout, helping to improve stamina, coordination, and agility. Mentally, punching and kicking the bag can help reduce feelings of anger, anxiety, and depression, promoting a sense of calm and well-being.
Enhanced Productivity
By incorporating the Mini Punching Bag into your daily routine, you can enhance your productivity and performance. Taking short breaks to engage in physical activity has been shown to boost cognitive function and creativity, allowing you to return to your tasks with renewed energy and focus.
Easy to Use
Using the Mini Punching Bag is simple and intuitive. Just place it on a stable surface, such as your desk or tabletop, and start punching and kicking away. You can adjust the intensity of your workout by varying the speed and force of your punches and kicks. For added convenience, the bag is easy to assemble and disassemble, making it a breeze to take with you wherever you go.
Quality Construction
Constructed from durable materials, the Mini Punching Bag is built to last. Its rugged design ensures that it can withstand repeated use without losing its shape or effectiveness. Plus, the bag is filled with high-density foam padding, providing a comfortable yet resilient surface to absorb your punches and kicks.
Join the Mini Punching Bag Revolution
Say goodbye to stress and hello to a healthier, happier you with the Mini Punching Bag. Whether you're looking to improve your fitness, manage your stress, or simply have fun, this compact and versatile tool is the perfect solution. Join the Mini Punching Bag revolution today and take control of your well-being one punch at a time.
９章8
Published: 2024-04-09 04:12:00

このJavaのコードは、ArrayListに異なるタイプのオブジェクト（文字列"A"、整数10、文字'B'）を追加し、その後で各オブジェクトをfor-eachループを使用して出力することを試みています。選択肢Fの説明は「[A10B] と表示される」というものです。これが正しい答えである理由を解説します。

```java
import java.util.ArrayList; // ArrayListクラスをインポートします。

public class Main {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>(); // 新しいArrayListを作成します。
        list.add("A"); // ArrayListに文字列"A"を追加します。
        list.add(10);  // ArrayListに整数10を追加します。
        list.add('B'); // ArrayListに文字'B'を追加します。

        // ArrayListの各要素をループで取得して出力します。
        for (Object obj : list) {
            System.out.print(obj); // ここでobjを出力します。出力時に改行は行われません。
        }
    }
}
```

このコードは以下の動作をします。

1. `ArrayList`に文字列"A"が追加されます。
2. `ArrayList`に整数10が追加されます。
3. `ArrayList`に文字'B'が追加されます（ここでの'B'はシングルクオートで囲まれているので、char型として扱われます）。

for-eachループは、`ArrayList`の各要素を順番に取り出して出力します。この場合、`ArrayList`には3つの要素があり、それらが追加された順に"A", 10, 'B'と出力されます。`System.out.print`メソッドは改行をしないので、結果として[A10B]とコンソールに表示されることになります。

従って、選択肢F「[A10B] と表示される」というのが正しい答えになります。Javaでは、文字列、整数、文字など異なる型のオブジェクトを`ArrayList`に格納でき、出力時にはそれぞれの`toString()`メソッドが呼ばれて文字列として出力されます。ここでは整数も文字も文字列に変換されて連結されるため、このような出力になります。
Hosting a simple docker-compose app with Nginx and generate a SSL with certbot on digitalocean droplet
Tags: docker, hosting, nginx
Published: 2024-04-09 03:43:44


Short and simple guide to hosting a simple docker app on digitalocean droplet with NGINX as the web server to serve our application.

This guide also works for other hosting service.

After creating your droplet, SSH into your droplet with the command below and upgrate your system packages
```sh
ssh root@<droplet_ip>

# Update the system
sudo apt update
sudo apt upgrade
```

Then clone your project and change directory into the project

```sh
git clone <remote_url>

cd <project_name>
```

# Install Docker

```sh
curl -fsSL https://get.docker.com -o get-docker.sh

sudo sh get-docker.sh

# Install docker compose
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

# Apply executable permissions to the binary
sudo chmod +x /usr/local/bin/docker-compose

# Run Project
docker-compose up -d
```

# Install Nginx

NOTE: Replace any `your_domain` to your public IPv4 or your domain name.

```sh
# Installing nginx with apt
sudo apt install nginx

# Firewall configuration to allow HTTP traffic for Nginx
sudo ufw allow 'Nginx HTTP’

# Create a new configuration in your site
sudo nano /etc/nginx/sites-available/your_domain
```

Nginx server configuration
```nginx
server {
   listen 80;
   listen [::]:80;
   server_name your_domain;
   location / {
      proxy_pass http://localhost:3000; # Replace to the port your server is listening to
      proxy_http_version 1.1;
      proxy_set_header Host $host;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_cache_bypass $http_upgrade;
   }
}
```

```sh
# Copy config to sites-enabled
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/

# Check for syntax errors
sudo nginx -t

# Restart Nginx to enable your new configuration
sudo systemctl restart nginx
```

Go to your DNS provider, and add a new A record. Name will be your domain name, and value will be the Public IPv4 address from your droplet

# Install Certbot for SSL

```sh
# Install python3 virtual environment
apt install python3-venv

# Create a virtual environment
sudo python3 -m venv /opt/certbot/
```

```sh
# Upgrade pip
sudo /opt/certbot/bin/pip install --upgrade pip

# Using pip to install certbot & certbot-nginx
sudo /opt/certbot/bin/pip install certbot certbot-nginx

# Copy the newly install certbot package
sudo ln -s /opt/certbot/bin/certbot /usr/bin/certbot

# Instructs Certbot to use the Nginx plugin to automatically configure SSL/TLS for Nginx web servers.
sudo certbot --nginx
```

Add an auto certificate renew script

```sh
# Run once every 2 days
echo "0 0 */2 * * root /opt/certbot/bin/python -c 'import random; import time; time.sleep(random.random() * 3600)' && sudo certbot renew -q" | sudo tee -a /etc/crontab > /dev/null
```
NextJS First impressions
Tags: programming, nextjs, personal, opinion
Published: 2024-04-09 03:24:36

After been using NextJS for the past 7 weeks where I learn the basic at the same time that I worked in a project for my current Job here is my impressions about the framework.

## My experience before nextjs

Before touching nextjs for the first time I worked with Laravel and vue (1 year), made some personal projects with nodejs (6 months - 1 year) and made a few little things with react js.

## The first impression

At the beginning I feel like I was working with something similar to Laravel and inertiajs. Because I have previous experience with nodejs and react my main focus was to learn the general workflow of NextJS and start working in the project of my job.

## How I study NextJS

The first things that I did when starting with nextjs were

- Watching some tutorials and begginer step guides
- Making and playing a little bit with an empty project of nextjs
- Asking my coworkers for some help related to nextjs
- Read code of projects made by my coworkers
- Use a basic template made by my coworkers

When I say `watching` it's literal that, I just watched the videos with the goal of understand the basic workflow of nextjs. After that I made a little project of nextjs, just playing with some basic functionalities of the framework like the app router, folder structure, etc. Because the majority of my teammates have experience working with nextjs, they helped me when I have some questions or show me a project that have something similar for I was looking at, and from there I spend time looking at the code of my colleagues.

## Thing that I like about nextjs

Here is a list of things that I like about nextjs.

- The speed in production
- The features that includes for default (app router, layouts, parallel routes, loading states)

## Things that i didn’t like about nextjs

In the other hand there were a few things of nextjs that I didn’t like about the framework:

- The Developer experience in the dev server of nextjs apps
- The documentation of the framework

## Conclusion

I will continue studying nextjs and becoming more comfortable with the framework, I’m going to share more of my experience of the framework in the near future, so we will see us the next time. Happy coding!.
Install K8S On Rocky Linux by A Shell Script
Tags: linux, kubernetes, lazy
Published: 2024-04-09 03:23:58

I recently had to install [Kubernetes](https://kubernetes.io/) on our on-premise servers. Sure, there were a lot of instructions on the internet that people shared. However, I am a lazy guy. I like to do anything as simple as possible so that I create a shell script depending on the [website](https://phoenixnap.com/kb/install-kubernetes-on-rocky-linux).
I have pushed it into my [GitHub Repo](https://github.com/u2633/rocky-linux-k8s-installer). Be lazy...
Deep Learning notes
Published: 2024-04-09 02:22:51

An unusual intro to deep learning.



The only primitive operation that one needs to understand to get started on in Deep Learning is dot product: vectors r and x of same dimension d can be dotted to produce a scalar {% katex inline %}  \langle r,x \rangle = \sum_{i\in [d]}{r_i x_i} {% endkatex %}.


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


To do this operation in parallel across multiple vectors {% katex inline %} r {%endkatex%}, one can write it as a matrix vector product. One way to think about these dot product is that each vector r is a measurement of (an unknown) signal x. For example if vector r is [1, 0, 0, 0], then it is measuring the first coordinate of x. Likewise vector r [0.25, 0.25, 0.25, 0.25] is measuring the average value of coordinates of x. Notice we can make many measurements of x by doing this matrix vector multiplication where each measurement is independent (and possibly redundant) and done in parallel.


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


As an aside, are you wondering what exactly is a dot product geometrically? It is simply a (scaled) projection of the high dimensional signal along a "line". The line could be x-axis (e.g. when r i s [1, 0, 0, 0]) or some 45-degree line passing through origin.

So given an "unknown" x, one is interested in asking the question, hey which direction should I measure x in to get maximum bang for buck. More on this later.


Suppose we have an image represented as a vector x. To make things concrete, imagine it is a 10x10 image with each value in [0, 1] representing the grayscale measure normalized to lie in [0, 1]. This image can be represented as a 100-dim column vector. We want to deduce if it is an image of a dog or a cat.
９章3
Published: 2024-04-09 02:11:47

このJavaのコードスニペットは、`Arrays.asList`メソッドを使用して、Integerのリストを作成し、そのリストをソートしてからプリントアウトするものです。しかし、ソートするための具体的な方法が7行目で省略されています。選択肢A, B, C, Dはそれを補うためのラムダ式です。答えはDと指定されていますので、なぜDが正しい答えなのかを説明します。

Dのオプションでは、`list.sort((a, b) -> -a.compareTo(b));`というラムダ式を使っています。この式は2つの要素`a`と`b`を比較し、その結果に負の符号をつけています。`compareTo`メソッドは、`a`が`b`より小さい場合は負の数、等しい場合は0、大きい場合は正の数を返します。その結果に負の符号をつけることで、通常の昇順の代わりに降順の比較を行うことができます。

したがって、このラムダ式をリストに適用すると、リストの要素は降順（大きいものから小さいものへ）にソートされます。つまり、元々のリスト`[1, 2, 3]`は`[3, 2, 1]`としてソートされるため、問題文の「降順にスコアをソートして」という要求を満たします。

それぞれの選択肢にコメントを加えて分かりやすくします：

A. `list.sort((a, b) -> a.compareTo(b));` // 昇順にソートする
B. `list.sort(() -> a.compareTo(b));` // 無効な構文、ラムダ式は2つの引数が必要
C. `list.sort((a) -> a.compareTo(b));` // 無効な構文、ラムダ式は比較のために2つの引数が必要
D. `list.sort((a, b) -> -a.compareTo(b));` // 降順にソートする（これが正解）

コメントを追加したコードスニペットは次のようになります：

```java
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(new Integer[]{1, 2, 3});
        // 以下のラムダ式によってリストを降順にソートする
        list.sort((a, b) -> -a.compareTo(b)); // 正しい降順のソート

        for (Integer num : list) {
            System.out.println(num); // ソートされたリストを出力する
        }
    }
}
```
ここでは、ソートの部分にラムダ式（選択肢D）を追加しています。これによりリストは降順にソートされ、`3, 2, 1`の順で出力されます。
Issue 39 of AWS Cloud Security Weekly
Tags: aws, security, cybersecurity, cloudsec
Published: 2024-04-09 01:55:16

(This is just the summary of Issue 39 of AWS Cloud Security weekly @ https://aws-cloudsec.com/p/issue-39 << Subscribe to receive the full version in your inbox weekly).

**What happened in AWS CloudSecurity & CyberSecurity last week April 2-April 8, 2024?**

- AWS Lambda has introduced support for building serverless applications using Ruby 3.3 (can use as both managed runtime and a container base image). The Lambda Ruby 3.3 runtime is constructed upon the latest Amazon Linux 2023 runtime, which relies on the AL2023 minimal container image. Additionally, it includes updated versions of common libraries like glibc and introduces a new package manager.
- Amazon CloudWatch: Cross-account observability is now enabled and now supports cross-account anomaly detection. Note: To try this, I had to first set cross-account functionality in CloudWatch & set the monitoring account (make sure to copy ARN of the “sink”) & source account.One thing I observed is that the cross-account will have ViewOnly access if you choose “FullAccess” option for the cross-account role. The sink ARN looks something like this: arn:aws:oam:us-east-1:915614547777:sink/77084777-db32-44a3-bf1c-08405aebe
- Amazon AppStream 2.0 has introduced support for initiating the client application for Windows from an Identity Provider (IdP)-initiated SAML 2.0 sign-in flow. End-users can now authenticate to SAML 2.0 IdPs via their system's default web browser before transitioning into the streaming session within the Windows client. This functionality eliminates the need for users to undergo re-authentication as long as their SAML 2.0 session in the browser remains valid, significantly streamlining their overall experience. Moreover, leveraging the browser for authentication enables the enforcement of additional access policies, such as conditional access provided by IdPs, before users commence streaming in the client application.


**Trending on the news & advisories:**

- OWASP foundation had a data breach. 
- Google to Delete Billions of Browsing Records in 'Incognito Mode' Privacy Lawsuit Settlement. 
- HTTP/2 CONTINUATION frames can be utilized for DoS attacks. 
- City of hope data security incident. 
- Home Depot confirms worker data leak after miscreant dumps info online.
- UK CVS Group. Notice of cyber incident. 
- Android- Find My Device network with user security and privacy in mind.
９章２
Published: 2024-04-09 01:43:17

このJavaのコードは、`Sample` オブジェクトのリストを特定の方法でソートするプログラムです。`Sample` クラスには `id` と `name` という2つのプライベート属性があり、`SampleComparator` クラスは `Comparator<Sample>` インターフェースを実装しており、2つの `Sample` オブジェクトを `id` 属性の値で比較しています。`Main` クラスの `main` メソッドでは、3つの `Sample` オブジェクトを含む配列を作成し、それをリストに変換しています。その後、`Collections.sort()` メソッドを使ってこのリストをソートし、ソートされたリストの各 `name` 属性を出力しています。

では、コードにコメントを加えて、各部分の動作を説明していきます。

```java
// Sample クラス定義
public class Sample {
    private int id; // オブジェクトのID
    private String name; // オブジェクトの名前

    // コンストラクタ
    public Sample(int id, String name) {
        this.id = id; // IDの初期化
        this.name = name; // 名前の初期化
    }

    // IDを取得するメソッド
    public int getId() {
        return id;
    }

    // 名前を取得するメソッド
    public String getName() {
        return name;
    }
}

// Sample オブジェクトを比較するためのComparator実装
import java.util.Comparator;

public class SampleComparator implements Comparator<Sample> {
    @Override
    public int compare(Sample s1, Sample s2) {
        if (s1.getId() < s2.getId()) {
            return 1; // s1のIDがs2より小さい場合は1を返す（降順）
        }
        if (s2.getId() < s1.getId()) {
            return -1; // s2のIDがs1より小さい場合は-1を返す（降順）
        }
        return 0; // IDが等しい場合は0を返す
    }
}

// メインクラスとエントリーポイント
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Sample オブジェクトの配列を初期化
        Sample[] samples = {
            new Sample(2, "B"), // IDが2のオブジェクト
            new Sample(3, "C"), // IDが3のオブジェクト
            new Sample(1, "A")  // IDが1のオブジェクト
        };

        // 配列からリストへの変換
        List<Sample> list = new ArrayList<>(Arrays.asList(samples));
        
        // SampleComparatorを使ってリストをソート
        list.sort(new SampleComparator());
        
        // ソートされたリストの各要素の名前を出力
        for (Sample s : list) {
            System.out.println(s.getName());
        }
    }
}
```

`SampleComparator` において、`compare` メソッドはIDが小さい方を後ろにするため、IDが大きいものから小さいものの順にソートされます。つまり、IDが3, 2, 1の順となります。それに対応する名前は "C", "B", "A" の順になりますので、答えはCです。