Posted by: xSicKxBot - 10 hours ago - Forum: Python
- No Replies
[Tut] ChatGPT 5.1 vs Gemini Banana Pro – Which Creates the Best Fake Monet?
I just finished this video comparing which AI model is better in building a Monet clone image:
This is the first image generated by ChatGPT 5.1:
This one nails the sunny summer vibe with those bright colors, but it’s honestly way too orange and saturated to pass for a real Monet. The generic ‘ART’ and ‘CAFFE’ signs look kind of fake, like something you’d find on a jigsaw puzzle rather than in a museum. It’s a pretty picture, but it feels more like modern home decor than a 19th-century masterpiece.
This is the second image generated by Google Gemini Banana Pro:
This one is much closer to the real deal, capturing that classic hazy look and the specific blue shadows that Monet actually used. It falls apart a bit when you zoom in on the weird, gibberish text and the blurry faces, which are dead giveaways for AI. Still, if you squint, this one definitely wins for feeling the most like an actual historical painting.
The React TanStack table is a great tool for displaying an elegant view of data table. It provides enriched features to build list with impressive user experience.
This tutorial uses Server-side data fetching and rendering, searching and sorting features.
A shopping cart product table is created in the backend. It has basic details to be listed in a tabular form. The React app connects to the PHP API to connect this database to fetch the rows.
If you are going to run this example in your environment, follow the below steps to set up. It has all the build required for the React TanStack data table rendering.
Download and extract the React project bundle.
Go to the React project directory by cd react-data-table-server-side-pagination-sorting-search
Run npm install to create node_modules.
Copy /api/react-product-table-api/ to your PHP root and configure in React JSX.
Create database db_shopping_cart and import sql/database.sql
Then, start the dev server by using npm run dev.
How to initiate React TanStack data table?
This is to initiate React TabStack library using useReactTable. It adds the raw data reference to the TanStack library row column object to render data.
This is the place to configure the server-side API URL to connect to the database for displaying dynamic grid. It sets the data array for the TanStack initiation.
This example has a single endpoint that receives all the search, sort and pagination inputs. The following React useCallback() passes these parameters to the API.
The React callback hook sets the raw data for the TanStack’s getCoreRowModel block to build a table row instance.
Below PHP script shows how to process a request from the allowed React origin. This PHP service prepares the SELECT query based on the search keyword, current page and sorting column & order passed from the React frontend.
react-product-table-api/products.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
require_once "db.php"; $page = $_GET['page'] ?? 1;
$limit = $_GET['limit'] ?? 5;
$search = $_GET['search'] ?? '';
$sortBy = $_GET['sortBy'] ?? 'id';
$order = $_GET['order'] ?? 'asc';
$offset = ($page - 1) * $limit; $allowedSort = ['id', 'title', 'price', 'category'];
$allowedOrder = ['asc', 'desc']; if (!in_array($sortBy, $allowedSort)) $sortBy = 'id';
if (!in_array(strtolower($order), $allowedOrder)) $order = 'asc'; $sql = "SELECT * FROM products WHERE title LIKE ? ORDER BY $sortBy $order LIMIT ?, ?";
$stmt = $conn->prepare($sql);
$searchParam = "%$search%";
$stmt->bind_param("sii", $searchParam, $offset, $limit);
$stmt->execute();
$result = $stmt->get_result(); $data = [];
while ($row = $result->fetch_assoc()) { $data[] = $row;
} $countSql = "SELECT COUNT(*) AS total FROM products WHERE title LIKE ?";
$countStmt = $conn->prepare($countSql);
$countStmt->bind_param("s", $searchParam);
$countStmt->execute();
$countResult = $countStmt->get_result()->fetch_assoc(); echo json_encode([ "products" => $data, "total" => $countResult["total"]
]);
?>
Conclusion
This example built a front end React data table with search, sort and pagination features. The TanStack table library provides more features apart these three features. For example, it has column ordering, row selection, resizing and more. But, we covered the prime features of this library that are need in majority of the frontend tables.
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.
EmailJS is a cloud service that supports to enable the frontend to send email without any backend. All we need is to create an EmailJS account and configure it to the frontend application.
This tutorial shows the step-by-step procedure to learn how to enable email sending in a React application using EmialJS.
2. Choose service provider via Add New Service -> Select Service
It supports various services like Gmail, Yahoo and etc. It also have settings to configure custom SMTP server with this online solution.
3. Design mail template by Email Templates -> Create New Template -> Select Template
There are various built-in templates in the EmailJS dashboard. I selected the “Contact Us” template for this example.
Template edit interface has the option to change the design and the content. It allows to add dynamic variables as part of the mail content.
When calling the EmailJS service, the request will have values to replace this variables. This feature will help to send a personalized email content.
Copy the Template ID once created an email template.
4. Get EmailJS API Public Key
Added Service ID, Template ID the EmailJS Public Key is also need to initiate the library class from the frontend React App.
Navigate via Account using the left menu to open the API keys section. Copy Public Key from the EmailJS dashboard.
Initiate EmailJS library to React App
Create a React app and install the EmailJS library to it using this command.
npm install emailjs-com
This example code contains this library installed. So, just run npm install to bring the dependancies into your node_modules.
Then, import the emailjs-com to the React JSX and initiate the EmailJS service as shown below. This script shows how the emailjs instance is used in the form handle submit.
This example provides component for the email sending form fields. The fields UI code is moved to a separate file and made as a component. It is imported into the parent container in the EmailForm component.
It renders Name, Email and Message fields. Each fields is validated with a handleChange hook.
React JSX to load EmailJS and EmailFormFields Component
This JSX defines the handleChange and handleSubmithooks for validation and mail sending respectively.
The form container includes the <EmailFormFields />, Submit button and a <ToastContainer />.
After sending email via emailjs, the handleSubmit action resets the form and make it ready for the next submit.
When submitting the form, the handleSubmit function sends the formData with the API keys and IDs. Configure your EmailJS keys and IDs to this React script to make this example to send email.
Note: Form data is in an associate array format, where the array keys matches the email template variables. For example, if the email template body in the EmailJS dashboard contains Hi {{name}}, then the form data will have the key-value as name: submitted-name to replace the variable.
The receive email signature and the mail body design will be as configured in the EmailJS dashboard. The following diagram shows the received email output.
Conclusion
Thus, we have created a frontend in React for sending email without any backend set up. I hope, you find EmailJS very simple to integrate into an application. And its registration process is very simple. And, the features to customize the email body is very useful to have a thematic email template for different applications.
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.
Posted by: xSicKxBot - 12-07-2025, 06:46 AM - Forum: Python
- No Replies
[Tut] Best Free Books for Distributed Systems PhD Students (Must Read!)
Distributed systems form the backbone of modern large-scale computing, from cloud platforms to distributed databases and large clusters.
As a PhD student, you need resources that go beyond the basics, combining strong theoretical foundations with practical insights. And ideally, they should be freely accessible.
The following five books are all legally available online at no cost and are well-suited to accompany you through graduate-level research in distributed systems.
Distributed Systems (4th Edition) — Maarten van Steen & Andrew S. Tanenbaum
This modern classic offers a broad and rigorous introduction to distributed systems, covering architectures, communication, naming, coordination, replication, fault tolerance, and security. The 4th edition updates many examples to reflect today’s large-scale systems and is widely used in advanced undergraduate and graduate courses. A personalized digital copy is available for free from the authors’ website.
Distributed Systems for Fun and Profit — Mikito Takada
Short, opinionated, and surprisingly deep, this book is great when you want to quickly grasp the core concepts behind real-world distributed systems. It walks through consistency models, time and ordering, replication strategies, and the design of systems like Dynamo and Bigtable, always with an eye toward what matters in practice. Its informal style makes it perfect as a first pass or as a companion to more formal texts.
The Datacenter as a Computer: Designing Warehouse-Scale Machines (3rd Edition) — Luiz André Barroso, Urs Hölzle, Parthasarathy Ranganathan
If you’re doing a PhD, you’ll likely care about how your algorithms and systems behave at data-center scale. This open-access book treats an entire datacenter as a single “warehouse-scale computer” and explains how to design, operate, and optimize such systems. It’s particularly valuable for understanding the hardware, energy, and reliability constraints behind large distributed services such as those run by major cloud providers.
Operating Systems: Three Easy Pieces — Remzi H. Arpaci-Dusseau & Andrea C. Arpaci-Dusseau
While technically an operating-systems book, OSTEP is essential background for anyone doing serious work in distributed systems. Its deep treatment of concurrency, synchronization, and persistence provides the building blocks that distributed algorithms and storage systems rely on. The clear structure, numerous exercises, and freely available PDFs make it ideal for self-study alongside more specialized distributed-systems material.
These lecture notes form a full-fledged graduate-level textbook on distributed algorithms, focusing on rigorous models and proofs. Topics include locality, symmetry breaking, graph problems, and complexity in distributed settings, making it an excellent bridge between theory and the systems-oriented books above. If your PhD work touches consensus, graph algorithms on networks, or lower bounds in distributed computing, this text is a highly relevant free resource.
The JWT authentication is a secure way of implementing a web login process without session management. This tutorial is for implementing React JWT authentication with PHP. It has the following steps to understand the process easily.
Additionally, this example code provides a user registration code to create new user to the database. With the registration and login code you are getting a base for your websites authentication module from this tutorial.
React login form submits the registered username and password.
PHP backend script validates the login details with the database.
PHP login success case generates JWT signed encoded user profile data.
React frontend receives the JWT token and stores to localStorage.
React validates the existence of the token with the ProtectedRoutes component.
If the ProtectedRoutes failed to find the JWT token, it denies the access.
React User Registration
This registration code helps to create data for your login process. Also, with registration this authentication example will be a more complete version to deploy in your application.
This example has a registration form with very few fields. React builds the formData state when the user enters the data. On submit, it passes the entered data to the PHP page register-action.php. It stores the user login name, email and the password to the database.
In the below JSX script, the formData, success/error state variables are managed. The handleSubmit hook handles the client-side form validation. This hook posts the data to the server once the validation returns true.
Part of RegisterForm.jsx with React states and hooks
import axios from "axios";
import { useNavigate } from "react-router-dom";
import SERVER_SIDE_API_ROOT from "../config";
import "../styles/style.css";
const RegisterForm = () => { const [formData, setFormData] = useState({ username: "", email: "", password: "", confirmPassword: "", }); const [errorMessage, setErrorMessage] = useState(""); const [successMessage, setSuccessMessage] = useState(""); const navigate = useNavigate(); const handleSubmit = async (e) => { e.preventDefault(); const { username, email, password, confirmPassword } = formData; if (!username || !email || !password || !confirmPassword) { setErrorMessage("Please fill in all fields"); setSuccessMessage(""); return; } const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(email)) { setErrorMessage("Please enter a valid email address"); return; } if (password.length < 6) { setErrorMessage("Password must be at least 6 characters"); return; } if (password !== confirmPassword) { setErrorMessage("Passwords do not match"); setSuccessMessage(""); return; } try { const res = await axios.post( `${SERVER_SIDE_API_ROOT}/registration-action.php`, { username, email, password }, { headers: { "Content-Type": "application/json" } } ); console.log("Server response:", res.data); if (res.data.status === "success") { setSuccessMessage(res.data.message); setErrorMessage(""); setFormData({ username: "", email: "", password: "", confirmPassword: "", }); setTimeout(() => { navigate("/login"); }, 2000); } else { setErrorMessage(res.data.message || "Registration failed"); setSuccessMessage(""); } } catch (err) { console.error("Axios Error:", err); setErrorMessage("Server error or CORS issue"); setSuccessMessage(""); }
};
PHP backend handles the registration request and stores the entered password in an encrypted form. It validates the user email uniqueness. If the entered email is already in the database, then this code rejects the user’s insertion.
If the user submits the correct username and password, the client receives success response from the server. The response will contain a JWT signed user profile data array.
In the client-side, the jwt-decode is used to decode the JWT response. The jwt-decode is the JavaScript library which can read and decode the JWT encoded string.
Run the following command to install this library into the application repository.
npm install jwt-decode [OR] yarn add jwt-decode
In the below script, if the response status is success it sets the JWT authentication token to a JavaScript localStorage. Then, it redirects to the dashboard. The dashboard is a protected page that can be accessed if a user is JWT-authenticated.
In PHP the firebase/php-jwt library is installed by using this composer command. Once the logged-in details matched, this library is used to generate the JWT token with the profile array.
Protected Route Component that validates JWT token to permit
This component validates if the localStorage has the JWT token. If not, then it will stop the user from accessing a requested page. Instead, it redirects to the login page.
The React main App component imports the ProtectedRoutes to bring the validation process at the top layer. This ProtectedRoutes wrapper around the Dashboard will help to permit only a JWT-authenticated user to the dashboard.
This React dashboard script gets the user details from the decoded JWT token. Then, those details are rendered to the UI as shown below.
A simple header is created for this dashboard view with a logout option. On clicking logout, it clears the localStorage and redirects to the login page.
With this login authentication base, you can have a good start to create a React JWT login. The user registration involves PHP and MySQL connection to generate backend data for this login. It can be enhanced by adding server-side JWT validation to improve the security. The concept of securing application pages with protected routes helps to reuse the wrapper for more components.
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.
Posted by: xSicKxBot - 12-07-2025, 05:14 AM - Forum: Lounge
- No Replies
News - Fallout Creator Rejoins Obsidian, Has A New Squirrel Friend
Fallout creator Tim Cain has returned to Obsidian, but what is he working on? He's not allowed to say, and says you shouldn't even try to guess. Cain also shared an update about his personal life and a new friendship with a squirrel.
In a YouTube video, Cain said he recently relocated from Seattle to southern California, and one of the first things that happened was a squirrel ran up to him with no fear. "She just sat there and looked at me, and I shrugged and I'm like, 'What do you want from me? I don't know you.'" Cain fed the critter some walnuts and continues to feed the creature every day when he leaves and comes back home.
This is how Cain started the video, before getting into his return to Obsidian. He said he's now back at the studio, in-person and full-time. While he has returned to Obsidian, you'll also see his name appear in the credits of an upcoming unspecified game that he did contract work for before coming back to Obsidian, he said.
[Tut] Best Ways to Remove Unicode from List in Python
5/5 – (1 vote)
When working with lists that contain Unicode strings, you may encounter characters that make it difficult to process or manipulate the data or handle internationalized content or content with emojis . In this article, we will explore the best ways to remove Unicode characters from a list using Python.
You’ll learn several strategies for handling Unicode characters in your lists, ranging from simple encoding techniques to more advanced methods using list comprehensions and regular expressions.
Understanding Unicode and Lists in Python
Combining Unicode strings and lists in Python is common when handling different data types. You might encounter situations where you need to remove Unicode characters from a list, for instance, when cleaning or normalizing textual data.
Unicode is a universal character encoding standard that represents text in almost every writing system used today. It assigns a unique identifier to each character, enabling the seamless exchange and manipulation of text across various platforms and languages. In Python 2, Unicode strings are represented with the u prefix, like u'Hello, World!'. However, in Python 3, all strings are Unicode by default, making the u prefix unnecessary.
Lists are a built-in Python data structure used to store and manipulate collections of items. They are mutable, ordered, and can contain elements of different types, including Unicode strings.
For example:
my_list = ['Hello', u'世界', 42]
While working with Unicode and lists in Python, you may discover challenges related to encoding and decoding strings, especially when transitioning between Python 2 and Python 3. Several methods can help you overcome these challenges, such as encode(), decode(), and using various libraries.
Method 1: ord() for Unicode Character Identification
One common method to identify Unicode characters is by using the isalnum() function. This built-in Python function checks if all characters in a string are alphanumeric (letters and numbers) and returns True if that’s the case, otherwise False. When working with a list, you can simply iterate through each string item and use isalnum() to determine if any Unicode characters are present.
The isalnum() function in Python checks whether all the characters in a text are alphanumeric (i.e., either letters or numbers) and does not specifically identify Unicode characters. Unicode characters can also be alphanumeric, so isalnum() would return True for many Unicode characters.
To identify or work with Unicode characters in Python, you might use the ord() function to get the Unicode code of a character, or \u followed by the Unicode code to represent a character. Here’s a brief example:
# Using \u to represent a Unicode character
unicode_char = '\u03B1' # This represents the Greek letter alpha (α) # Using ord() to get the Unicode code of a character
unicode_code = ord('α') print(f"The Unicode character for code 03B1 is: {unicode_char}")
print(f"The Unicode code for character α is: {unicode_code}")
In this example:
\u03B1 is used to represent the Greek letter alpha (α) using its Unicode code.
ord('α') returns the Unicode code for the Greek letter alpha, which is 945.
If you want to identify whether a string contains non-ASCII characters (which might be what you’re interested in when you talk about identifying Unicode characters), you might use something like the following code:
def contains_non_ascii(s): return any(ord(char) >= 128 for char in s) # Example usage:
s = "Hello α"
print(contains_non_ascii(s)) # Output: True print(contains_non_ascii('Hello World')) # Output: False
In this function, contains_non_ascii(s), it checks each character in the string s to see if it has a Unicode code greater than or equal to 128 (i.e., it is not an ASCII character). If any such character is found, it returns True; otherwise, it returns False.
Method 2: Regex for Unicode Identification
Using regular expressions (regex) is a powerful way to identify Unicode characters in a string. Python’s re module can be utilized to create patterns that can match Unicode characters. Below is an example method that uses a regular expression to identify whether a string contains any Unicode characters:
import re def contains_unicode(input_string): """ This function checks if the input string contains any Unicode characters. Parameters: input_string (str): The string to check for Unicode characters. Returns: bool: True if Unicode characters are found, False otherwise. """ # The pattern \u0080-\uFFFF matches any Unicode character with a code point # from 128 to 65535, which includes characters from various scripts # (Latin Extended, Greek, Cyrillic, etc.) and various symbols. unicode_pattern = re.compile(r'[\u0080-\uFFFF]') # Search for the pattern in the input string if re.search(unicode_pattern, input_string): return True else: return False # Example usage:
s1 = "Hello, World!"
s2 = "Hello, 世界!" print(contains_unicode(s1)) # Output: False
print(contains_unicode(s2)) # Output: True
Explanation:
[\u0080-\uFFFF]: This pattern matches any character with a Unicode code point from U+0080 to U+FFFF, which includes various non-ASCII characters.
re.search(unicode_pattern, input_string): This function searches the input string for the defined Unicode pattern.
If the pattern is found in the string, the function returns True; otherwise, it returns False.
This method will help you identify strings containing Unicode characters from various scripts and symbols. This pattern does not match ASCII characters (code points U+0000 to U+007F) or non-BMP characters (code points above U+FFFF).
If you want to learn about Python’s search() function in regular expressions, check out my tutorial and tutorial video:
Method 3: Encoding and Decoding for Unicode Removal
When dealing with Python lists containing Unicode characters, you might find it necessary to remove them. One effective method to achieve this is by using the built-in string encoding and decoding functions. This section will guide you through the process of Unicode removal in lists by employing the encode() and decode() methods.
First, you will need to encode the Unicode string into the ASCII format. It is essential because the ASCII encoding only supports ASCII characters, and any Unicode characters that are outside the ASCII range will be automatically removed. For this, you can utilize the encode() function with its parameters set to the ASCII encoding option and error handling set to 'ignore'.
After encoding the string to ASCII, it is time to decode it back to a UTF-8 format. This step is essential to ensure the list items retain their original text data and stay readable. You can use the decode() function to achieve this conversion. Here’s an example:
string_utf8 = string_ascii.decode('utf-8')
Now that you have successfully removed the Unicode characters, your Python list will only contain ASCII characters, making it easier to process further. Let’s take a look at a practical example with a list of strings.
list_unicode = ["? ?? ???????!", "This is an ASCII string", "???? ?? ???????"]
list_ascii = [item.encode('ascii', 'ignore').decode('utf-8') for item in list_unicode] print(list_unicode)
# ['? ?? ???????!', 'This is an ASCII string', '???? ?? ???????'] print(list_ascii)
# [' !', 'This is an ASCII string', ' ']
In this example, the list_unicode variable comprises three different strings, two with Unicode characters and one with only ASCII characters. By employing a list comprehension, you can apply the encoding and decoding process to each string in the list.
Remember always to be careful when working with Unicode texts. If the string with Unicode characters contains crucial information or an essential part of the data you are processing, you should consider keeping the Unicode characters and using proper Unicode-compatible solutions.
Method 4: The Replace Function for Unicode Removal
When working with lists in Python, it is common to come across Unicode characters that need to be removed or replaced. One technique to achieve this is by using Python’s replace() function.
The replace() function is a built-in method in Python strings, which allows you to replace occurrences of a substring within a given string. To remove specific Unicode characters from a list, you can first convert the list elements into strings, then use the replace() function to handle the specific Unicode characters.
When dealing with a larger set of Unicode characters, you can use a dictionary to map each character to be replaced with its replacement. For example:
unicode_replacements = { "ó": "o", "ö": "o", "é": "e", # Add more replacements as needed.
} original_list = ["Róisín", "Björk", "Héctor"]
new_list = [] for item in original_list: for key, value in unicode_replacements.items(): item = item.replace(key, value) new_list.append(item) print(new_list) # ['Roisin', 'Bjork', 'Hector']
Of course, this is only useful if you have specific Unicode characters to remove. Otherwise, use the previous Method 3.
Method 5: Regex Substituion for Replacing Non-ASCII Characters
When working with text data in Python, non-ASCII characters can often cause issues, especially when parsing or processing data. To maintain a clean and uniform text format, you might need to deal with these characters and remove or replace them as necessary.
One common technique is to use list comprehension coupled with a character encoding method such as .encode('ascii', 'ignore'). You can loop through the items in your list, encode them to ASCII, and ignore any non-ASCII characters during the encoding process. Here’s a simple example:
data_list = ["? ?? ???????!", "Hello, World!", "你好!"]
clean_data_list = [item.encode("ascii", "ignore").decode("ascii") for item in data_list]
print(clean_data_list)
# Output: [' m mn!', 'Hello, World!', '']
In this example, you’ll notice that non-ASCII characters are removed from the text, leaving the ASCII characters intact. This method is both clear and easy to implement, which makes it a reliable choice for most situations.
Another approach is to use regular expressions to search for and remove all non-ASCII characters. The Python re module provides powerful pattern matching capabilities, making it an excellent tool for this purpose. Here’s an example that shows how you can use the re module to remove non-ASCII characters from a list:
import re data_list = ["? ?? ???????!", "Hello, World!", "你好!"]
ascii_only_pattern = re.compile(r"[^\x00-\x7F]")
clean_data_list = [re.sub(ascii_only_pattern, "", item) for item in data_list]
print(clean_data_list) # Output: [' !', 'Hello, World!', '']
In this example, we define a regular expression pattern that matches any character outside the ASCII range ([^\x00-\x7F]). We then use the re.sub() function to replace any matching characters with an empty string.
Frequently Asked Questions
How can I efficiently replace Unicode characters with ASCII in Python?
To efficiently replace Unicode characters with ASCII in Python, you can use the unicodedata library. This library provides the normalize() function which can convert Unicode strings to their closest ASCII equivalent. For example:
This function will replace Unicode characters with their ASCII equivalents, making your Python list easier to work with.
What are the best methods to remove Unicode characters in Pandas?
Pandas has a built-in method that helps you remove Unicode characters in a DataFrame. You can use the applymap() function in conjunction with the lambda function to remove any non-ASCII character from your DataFrame. For example:
import pandas as pd data = {'col1': [u'こんにちは', 'Pandas', 'DataFrames']}
df = pd.DataFrame(data) df = df.applymap(lambda x: x.encode('ascii', 'ignore').decode('ascii'))
This will remove all non-ASCII characters from the DataFrame, making it easier to process and analyze.
How do I get rid of all non-English characters in a Python list?
To remove all non-English characters in a Python list, you can use list comprehension and the isalnum() function from the str class. For example:
This approach filters out any character that isn’t alphanumeric or has an ASCII value greater than 127.
What is the most effective way to eliminate Unicode characters from an SQL string?
To eliminate Unicode characters from an SQL string, you should first clean the data in your programming language (e.g., Python) before inserting it into the SQL database. In Python, you can use the re library to remove Unicode characters:
import re def clean_sql_string(s): return re.sub(r'[^\x00-\x7F]+', '', s)
This function will remove any non-ASCII characters from the string, ensuring that your SQL query is free of Unicode characters.
How can I detect and handle Unicode characters in a Python script?
To detect and handle Unicode characters in a Python script, you can use the ord() function to check if a character’s Unicode code point is outside the ASCII range. This allows you to filter out any Unicode characters in a string. For example:
You can then handle the detected Unicode characters accordingly, such as using replace() to substitute them with appropriate ASCII characters or removing them entirely.
What techniques can be employed to remove non-UTF-8 characters from a text file using Python?
To remove non-UTF-8 characters from a text file using Python, you can use the following method:
Open the file in binary mode.
Decode the file’s content with the ‘UTF-8’ encoding, using the ‘ignore’ or ‘replace’ error handling mode.
Write the decoded content back to the file.
with open('file.txt', 'rb') as file: content = file.read() cleaned_content = content.decode('utf-8', 'ignore') with open('cleaned_file.txt', 'w', encoding='utf-8') as file: file.write(cleaned_content)
This will create a new text file without non-UTF-8 characters, making your data more accessible and usable.
This tutorial has a React NodeJS example for building a full-stack CRUD application. It gives easy guidelines to design the frontend and backend. The frontend React connects the NodeJS API controllers to interact for creating, reading, updating, and deleting. This will provide persistent storage with a MySQL database connected via API DAOs.
Add form design and user creation with NodeJS and MySQL
The user-create form contains only two fields to simplify the example. So, the React frontend assets manages states and props to carry these inputs’ data to post.
The addUser() props triggers the add action request to post the form data to the server.
It executes the insert query on clicking the ‘Add User’ button. The response will have the auto-generated key created on successful insert action of the CRUD functionality.
Updating current user by ID using update API in NodeJS
The add and edit forms are exactly same except that this edit form populated the existing user data. The currentUser props contains the exiting user details read by id.
On clicking the ‘Edit’ button the user id is passed to send the read request with the id.
Once the enduser edits the detail and submit, it request the NodeJS API to perform the update operation of the CRUD module.
Both add and edit button clicks prevents the default submit and requests the API via network call.
The edit form is used to view or edit the user details. When clicking cancel the editing directive is set to false to switch to the view mode.
export const deleteUser = (req, res) => { const { id } = req.params; db.query("DELETE FROM users WHERE id=?", [id], (err) => { if (err) return res.status(500).json({ error: err.message }); res.json({ message: "User deleted" }); });
};
How to run the React + NodeJS example?
Set up the MySQL database:
First find the /api/sql/users.sql file from the downloadable source code given in this React + NodeJS CRUD example.
Create a database and import that SQL script into that. Then Configure the database details to the db.js file in the NodeJS API root. Start the backend NodeJS server:
Go to the NodeJS api path and start the server via npm. It will return the server running path http://localhost:5000/
In this example this backend api URL is configured with a specific constant for convenience. It avoid the overhead of changing in multiple places based on the environment.
cd /path/api npm install npm start node server.js
Start the frontend React dev:
Go to the app location path and start the dev server. This will start the dev server http://localhost:5173/
cd react-node-mysql-crud-full-stack-tutorial npm install npm run dev
Conclusion
This tutorial built a simple code for React + Node.js + MySQL CRUD. The code for designing frontend and connecting the NodeJS API together gives a full stack execution sample. I hope, you learned how to read and display dynamic data from backend to React components and also how to manipulate them. The server controller is with appropriate cases to handle the CRUD with MySQL to store, retrieve, update, and delete data. With this base, it is easy to add more features to this CRUD utility.
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.
(Indie Deal) FREE Die Young, IG Anniversary, Star Forge Bundle
FREE Die Young
[freebies.indiegala.com]
IndieGala Anniversary
[www.indiegala.com] Another year has passed & we once again celebrate our time together with a ton of surprises. Thank you for being part of the community & for being here with us now.
Star Forge Bundle | 6 Steam Games | 93% OFF
[www.indiegala.com] Blast off into creativity, adventure, and puzzle-packed fun with the Star Forge Bundle — a curated collection of 6 vibrant indie games spanning action, strategy, arcade shooting, simulation, and dreamlike exploration. Featuring: Suika Shapes, Movie Cinema Simulator, Rob Riches, Star Hunter DX, Puzzle Forge Dungeon, Onirike