teleren/devto huggingface dataset:
Handling 404 Error in SPA Deployed on GitHub Pages
Tags: webdev, react, github, frontend
Published: 2024-05-02 17:37:36

If you deployed a SPA - Single Page Application - with Github pages. It may work well when you open your app from the root path, which is `/`.

But you will see the 404 error page when you open the other path even though it should be handled by the router library you use, in my case, the React Router library.

It is because once you open the root path, the javascript code of the app is downloaded on your web browser and when the location is changed, it will be handled by javascript code, which means it does not request a file to the server.

However, if you start by opening the other root, which is not '/', it throws the 404 error as it couldn't find an HTML file corresponding to the route you entered. You will see only one HTML file in the deployed directory, `index.html`.

![dist](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/53brwuqyrz03qrr1i2pg.png)

If you build a React app using Vite, the built files will be located in the `dist` directory like the image.

Then, how could we show our app to display the 404 page?
We can solve this problem by simply creating the `404.html` file under the root directory. 
The `404.html` file located in the root directory will be sent when users open the app with a non-root path, which is not '/'.

```json
  "scripts": {
    "dev": "vite --host 0.0.0.0",
    "build": "tsc && vite build --mode production && cp ./dist/index.html ./dist/404.html",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "test": "vitest run",
    "test:coverage": "vitest run --coverage",
    "test:watch": "vitest"
  },
```

I added the copy command after the build command.

Note: The script may be different if you're working with a framework other than React with Vite. The point is to create the `404.html` file under the build folder by copying your main file.

```
tsc && vite build --mode production && cp ./dist/index.html ./dist/404.html
```

Then you will see the `404.html` file is created by copying the `index.html` file.
Your build directory may look like this.

![dist directory with the 404.html file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tfb641qwmemaskj82nx.png)

Now, let's start the app with a non-root path.

![handled 404 page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6edeflj0drtfp2v25ze.png)

It didn't find the file corresponding to the path and sent the 404.html file located in the root directory, which we created by copying the index.html.

As a result, all the path is handled by our javascript code. The only problem is that it responds with the status code 404.

I hope you found it helpful!
Happy Coding!
Enhancing Java Web Development Skills: @WebServlet Annotation, JSP, Servlet vs. JSP, and Exception Handling
Tags: java
Published: 2024-05-02 17:36:51

Hey Dev.to community! Today, I deepened my understanding of Java web development by exploring several key topics:

@WebServlet Annotation: Explored the usage of @WebServlet annotation in Java Servlets, understanding its role in simplifying servlet configuration and mapping in web applications.
The Role of JSP: Discussed the importance of JSP (JavaServer Pages) in web development, understanding how JSP enables the creation of dynamic web pages with embedded Java code.
Servlet vs. JSP: Compared and contrasted Servlets and JSP, exploring their strengths, weaknesses, and typical use cases in building web applications.
Exception Handling in JSP: Explored exception handling strategies in JSP, learning how to effectively handle errors and exceptions in JSP pages.
Overall, my exploration of these topics has enriched my Java web development skills and provided me with valuable insights into building dynamic and interactive web applications. Excited to incorporate these learnings into my projects! #Java #Servlet #JSP #LearningJourney
Day 32/366
Tags: 1percentplusplus, 100daysofcode
Published: 2024-05-02 17:34:43

🚀 Today's Learning:
🌟 DSA

- Check whether two Strings are anagram of each other
- Print all anagrams together

🌟 Dev

- Redux Persist

🔍 **Some Key Highlights:**

DSA

To check whether two strings are anagrams of each other, iterate through each character of both strings, counting the frequency of each character in each string using a hashmap. Then, compare the frequency maps of both strings. If the maps are identical, the strings are anagrams; otherwise, they are not.

To print all anagrams together, create a hashmap where the keys are sorted versions of each word in the input list, and the values are lists of words that are anagrams of each other. Iterate through the input list of words, sorting each word and using the sorted word as a key to group anagrams together in the hashmap. Finally, iterate through the hashmap and print each list of anagrams together.

DEV

Redux Persist is a library used in Redux-based applications to persist the Redux state to storage, typically AsyncStorage in React Native or localStorage in web applications. It allows the state to be saved across browser or app restarts, ensuring a seamless user experience. Redux Persist works by integrating with the Redux store and providing middleware that automatically saves the state to storage whenever it changes. Upon app or browser restart, the persisted state is retrieved from storage and rehydrated into the Redux store, allowing the application to resume from where it left off. This library simplifies the process of implementing persistence in Redux applications, enhancing reliability and user satisfaction.

 #100daysofcode #1percentplusplus #coding #dsa
Data Encryption
Tags: cybersecurity, security, programming, development
Published: 2024-05-02 17:23:56


Unlocking the Mystery: What is Data Encryption and How Does it Work? 🔐

Ever wondered how your sensitive information stays safe online? Let's dive into the world of data encryption and understand its inner workings, along with when to use each method and which algorithms to choose.

Data encryption is like turning readable data into a secret code, ensuring security, authenticity, and integrity. But why do we need it?

Three main reasons:

- Security: Protecting important data from exposure
- Authenticity: Ensuring only authorized individuals can access the data
- Integrity: Guaranteeing that important data hasn't been tampered with
So, what are the types of data encryption?

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

Firstly, Symmetric Encryption:
This method uses a single key to both encrypt and decrypt data. While algorithms like Blowfish and RC4 are outdated, AES stands as today's best practice.

How does it work?
These algorithms encrypt data bit by bit, with AES dividing data into blocks and adding an Initialization Vector (IV) to generate a unique random value for each block.

But what if the key is compromised? Enter Asymmetric Encryption:
This approach involves a public key to encrypt data and a private key to decrypt it. RSA and Diffie-Hellman are popular examples, safeguarding sensitive communications like SSH connections.

But what about data modification?

Enter the third type: Hashing Functions:
These one-way encryption methods, like SHA and MD5, ensure data integrity. For example, passwords are stored as hashed values, and during login, the hashed input is compared to the stored hashed password.

So, the next time you send a sensitive message or log into your bank account, remember the invisible fortress of encryption standing guard, keeping your information safe and sound.
Learn SwiftUI (Day 14/100)
Tags: swift
Published: 2024-05-02 17:14:59

## Swift

* optionals
* if let
* guard let ... else
* ?? and chaining ?.
* try?

```swift
import Cocoa

// ## optionals
/*
 Optionals are like a box that may or may not have something inside.
 var number: Int? = nil
 var name: String? = "hello world"
 */
// 3 ways to unwrap optionals
// 1) if let
var opposites = ["Mario": "Wario", "Luigi":"Waluigi"]
if let marioOpposite = opposites["Mario"] {
    print("Mario's opposite is \(marioOpposite)")
}

var name: String? = "hello world"
if let name = name {
    print("name is \(name)")
}

// 2). guard let ... else
func printSquare(of number: Int?) {
    guard let number = number else {
        print("Missing input")
        return
    }
    print("\(number) x \(number) is \(number * number)")
}
printSquare(of: 4)
// a more general version of guard is:
// guard someArray.isEmpty else { return }.

// 3) ??
let new = opposites["Peach"] ?? "N/A"

let input = ""
let number = Int(input) ?? 0
print(number)

// chaining
/*
 Optional chains can go as long as you want, and as soon as any part sends
 back nil the rest of the line of code is ignored and sends back nil.
 */
// example 1
let names = [String]()
let chosen = names.randomElement()?.uppercased() ?? "No one"
print("Next in line: \(chosen)")

// example 2
struct Book {
    let title: String
    let author: String?
}

var book: Book? = nil
let author = book?.author?.first?.uppercased() ?? "A"
print(author)

// ## use `try?`
/*
 If the function ran without throwing any errors then the optional will
 contain the return value, but if any error was thrown the function will
 return nil.
 */
enum UserError: Error {
    case badID, networkFailed
}

func getUser(id: Int) throws -> String {
    throw UserError.networkFailed
}

if let user = try? getUser(id: 23) {
    print("User: \(user)")
}
// or
let user = (try? getUser(id: 23)) ?? "Anonymous"


// ## checkpoint

/*
 write a function that accepts an optional array of integers, and returns one randomly. If the array is missing or empty, return a random number in the range 1 through 100.
 */

func randomPick(nums: [Int]?) -> Int {
    return nums?.randomElement() ?? Int.random(in: 1...100)
}
print(randomPick(nums: []))
```
Boiled down: Getters/setters in JavaScript
Tags: webdev, javascript, beginners, learning
Published: 2024-05-02 17:11:28

## Security and flexibility with getters and setters

In JavaScript, there are two kinds of object properties:

1. Data properties:

```javascript
let myObj = {name: "Joseph", surname: "Joestar"}
// name and surname are data properties

myObj.name // Joseph
```

2. Accessor properties

```javascript
let myObj = {
  get name() {
    return this._name;
  },
  set name(value) {
    this._name = value;
  },
  get surname() {
    return this._surname;
  },
  set surname(value) {
    this._surname = value;
  },
  get fullName() {
    return `${this._name} ${this._surname}`
  }
}
// properties starting with an underscore are internal
// and should not be touched outside the object

// get name and set name are accessor properties
myObj.name = "Jolene"
myObj.name // Jolene
```

You can see how data properties allow us to directly access an object's properties, whereas accessor properties provide us _getters_ and _setters_ to retrieve and manipulate an object's properties.

We can even keep the actual value under a different variable name. But why should we use accessor properties? They allow us more control over operations with our objects and safeguard data that we don't want to be directly accessed or manipulated.

Within our _setter_, we can manipulate the data before storing it in our object's property such as validation.

## Compatability using getters and settters

If we introduce new properties in the future for an object that may affect other properties, we can modify the accessor properties to make it compatible with our current needs.
Learning AWS Day by Day - Day 53 - Differences between SQS, SNS and Amazon MQ
Tags: aws, cloud, cloudcomputing, beginners
Published: 2024-05-02 17:09:38

Exploring AWS !!

Day 53

Differences between SQS, SNS and Amazon MQ
SQS, SNS and Amazon MQ are all scalable and highly available messaging services.

SQS - decoupling of distributed software systems. Messages in queue are processed by a single subscriber. Fanout applications - created using SNS and SQS together.

SNS - pub-sub model that provides message delivery from producers to multiple subscribers. Asynchronous communication between publisher and subscriber by sending messages to a topic. Subscribers can subscribe to SNS topic and receive published messages using Data Firehose, SQS, Lambda, HTTP, email, text messages or push notifications. SNS acts as a messenger and delivers messages to subscribers timely. if the subscriber is not available, the message won't be stored.

Amazon MQ - managed broker service which is compatible with industry standard messaging protocols like AMQP, MQTT. Supported engines - Apache ActiveMQ, RabbitMQ.


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

SNS and SQS both are recommended for using with new applications that can help in scalability and simple APIs. Amazon MQ would be recommended for migrating applications from existing message brokers relying on compatibility with APIs such as JMS.
Lineage 2: Игра на Java платформе и особенности серверной архитектуры
Tags: games, lineage
Published: 2024-05-02 17:06:31

Lineage 2 — это популярная онлайн-игра, которая завоевала сердца миллионов игроков по всему миру. Одной из ключевых особенностей Lineage 2 является её разработка на Java платформе, что оказывает значительное влияние как на качество игрового процесса, так и на возможности модификации и поддержки игровых серверов.

Java в основе Lineage 2
Java — это высокоуровневый, объектно-ориентированный язык программирования, который славится своей переносимостью и эффективностью в сетевых приложениях. Использование Java в качестве основы для серверной части [Lineage 2](https://ru.wikipedia.org/wiki/Lineage_II) обеспечивает несколько важных преимуществ:

Переносимость: Java-программы легко запускаются на различных платформах без необходимости изменения кода. Это облегчает разработчикам задачу поддержки игры на разнообразном оборудовании.
Безопасность: Java предлагает встроенные механизмы безопасности, которые защищают серверы игры от различных угроз и атак.
Масштабируемость: Java позволяет легко масштабировать игровые проекты, что критически важно для MMORPG, где одновременно могут участвовать тысячи игроков.
Управление памятью: Автоматическое управление памятью с помощью сборщика мусора уменьшает риск утечек памяти и ошибок, связанных с динамическим распределением памяти.
Архитектура сервера и клиента
Игра Lineage 2 состоит из двух основных компонентов: серверной части, написанной на Java, и игрового клиента, который устанавливается на компьютер игрока. Серверная часть отвечает за обработку данных всех подключенных игроков, управление игровым миром и обеспечение синхронизации событий в игре. Клиентская часть занимается отображением графики, обработкой пользовательских вводов и взаимодействием с сервером.

Преимущества и вызовы
Основное преимущество использования Java для серверной части Lineage 2 — это высокий уровень абстракции и обширный набор доступных инструментов и библиотек, которые упрощают разработку и поддержку сложных сетевых приложений. Однако это также влечёт за собой определённые вызовы, включая необходимость оптимизации производительности и памяти, что может быть критично для игр с большим количеством одновременных пользователей.

Заключение
Lineage 2 является ярким примером успешного применения Java в крупномасштабных онлайн-играх. Несмотря на некоторые трудности, связанные с управлением ресурсами, Java предоставляет разработчикам мощные инструменты для создания надёжных, безопасных и масштабируемых онлайн-игр, что делает её идеальной платформой для современных MMORPG. Основная информация и мысли автора на его сайте: [https://l2-top.ru/](https://l2-top.ru/)
Why Choose Holysmoke Shishabar?
Published: 2024-05-02 17:05:35



- Free shipping to Paphos, Limassol, Nicosia, Larnaca, and Paralimni within Cyprus

- Over 55 genuine [hookah](https://holysmokeshishabar.com.cy) and [shisha tobacco](https://holysmokeshishabar.com.cy) brands

- Flexible worldwide shipping options with tracking (your order will arrive promptly & securely with DHL Express, UPS, EMS or National Post)

- Premium shisha tobacco brands, including FUMARI, SEBERO, ALOHA Exclusive JENT, KEFI, SATYR, Trofimoff’s, Blackburn, Tangiers and more

- Extensive selection of hookah bowls from renowned brands (Ceramister, ST, Oblako, MoonRave, UPG, Tortuga, Smokah, More Bowls, DON, Gusto, KONG, Target, Hookain, Hooligan, KS Original)

- Modern German and Russian hookahs from top-of-the-line manufacturers (Conceptic Design, Hoob, DSH, Y4, Aladin, NaGrani, MattPear, Loco, CWP, Karma, IronRose, SoftSmoke)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ctywemfm4p9sp2jgsts2.jpg)
Showcase your open source project at top developer conferences in Berlin this summer 🇩🇪
Tags: opensource, github, berlin, germany
Published: 2024-05-02 16:55:16

This June and July, we are thrilled to partner with our friends at [GitButler](https://gitbutler.com/) and [WeAreDevelopers](https://www.wearedevelopers.com/) to offer open source maintainers two unique and exciting opportunities to present their projects at major developer events in Berlin.

* [Open Source Fair at The Merge](https://merge.berlin/): June 13 – 14
* [Open Source Spotlight at WeAreDevelopers World Congress](https://www.wearedevelopers.com/world-congress/github-open-source-spotlight): July 17 – 19

Whether you're looking to showcase your latest innovations, network with fellow developers and potential users, or attract new contributors, these events provide the ideal platform. Each conference offers complimentary passes, access to presentations from industry leaders, and numerous opportunities to engage with the broader developer community. 

You’ll also experience an impressive lineup of speakers <sup><a href="https://www.wearedevelopers.com/world-congress/speakers">1</a>, <a href="https://merge.berlin/">2</a></sup>, including John Romero—where you might even get a chance to challenge him in a game of Doom—and key figures from GitHub, such as our CEO, their Chief of Staff, COO, and VP of Communities (that’s a lot of acronyms)! The speaker lineup for both events is shaping up to be truly exceptional.

**Event Layout**

Imagine a setup reminiscent of our old [Open Source Alley at OSCON](https://github.blog/2016-03-14-open-source-alley-at-oscon-call-for-projects/) (see photo below)—only bigger and better.

![View of Open Source at OSCON in 2015, a space for open source maintainers to showcase their work](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oqv7txdzp9yku2wrwlni.png)

We've crafted a space specifically designed to enhance interactions and spotlight the finest in open source projects. And the most crucial element? You!

**Ready to Join Us?**

 Don’t miss out on the chance to be a part of these extraordinary events. For more information and to apply, please visit the individual conference websites:

##### June 13 – 14 [Open Source Fair at The Merge](https://merge.berlin/)

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

##### July 17 – 19 [Open Source Spotlight at WeAreDevelopers World Congress](https://www.wearedevelopers.com/world-congress/github-open-source-spotlight)

[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p3cxpk1kdrtmtel17kmd.png)](https://www.wearedevelopers.com/world-congress/github-open-source-spotlight)

**Please Note:** Check the conference websites for detailed information on application deadlines and participation details.

Good luck and we look forward to seeing you in Berlin!

Prost! :beers:
I am lost in a maze help me !
Tags: development, webdev, developers, javascript
Published: 2024-05-02 16:46:54

Hey everyone, thanks for stopping by. I started learning web development a few months ago and am now comfortable with the MERN stack. I would like to make tech my career option. However, I've suddenly found myself lost in the maze of software development. Even though I find web development worth pursuing, I don't want to limit myself to just being a developer who creates and deploys websites. Can any of you suggest something related to web development but a bit more challenging?
Laravel Error Fix: How to Handle "Attempt property on null"
Tags: laravel, webdev, tutorial, beginners
Published: 2024-05-02 16:16:19

Hello everyone! If you’ve ever encountered the frustrating "Attempt to access property on null" error while working with Laravel, you’re not alone. In this guide, we’ll dive into what causes this error and, more importantly, how to effectively handle it.

**Understanding the Error:**
Before we jump into solutions, let’s understand why this error occurs. In Laravel, this error typically arises when trying to access a property or method on a null value, often resulting from a database query that didn’t return any results.

**Strategies for Handling the Error:**
When faced with this error, the first step is to identify where it’s happening in your code. Laravel’s detailed error messages and stack traces can help pinpoint the exact line causing the issue.

**1. Nullsafe Operator (?->):**
The `"?->"` null safe operator lets you safely access properties or methods of potentially null variables without throwing errors. If the variable is null, the expression returns null.

```php
{{ $blog->author?->name }}
```

**2. optional():**
The `optional()` helper function is available in Laravel starting from version 5.5. It allows you to gracefully access properties or methods of potentially null variables by returning either null or the value if the variable is not null.

```php
{{ optional($blog->author)->name }}
```

**3. Null Coalescing Operator (??):**
The null coalescing operator `"??"` returns the left-hand side if it's not null, otherwise, it returns the right-hand side default value.

```php
{{ $blog->author->name ?? 'Unknown' }}
```

**4. withDefault()**
The `withDefault()` method in Laravel's Eloquent ORM creates a related model with default values if it doesn't exist.

```php
use App\Models\Author;

class Blog extends Model {
    public function author() {
        return $this->belongsTo(Author::class)->withDefault([
            'name' => 'Anonymous',
        ]);
    }
}
```
In this example, if the blog's author is null when accessed, Laravel will automatically create a new "Author" model with the name set to 'Anonymous'.

**Conclusion:**
Encountering the "Attempt to access property on null" error in Laravel can be challenging, but employing strategies like the null safe operator, optional() function, null coalescing operator, and withDefault() method provides effective solutions. By gracefully handling null values, developers can enhance application reliability and user experience. Combining these techniques with robust error logging ensures comprehensive error management, fostering stability and maintainability in Laravel projects.

Thanks for reading🤝