teleren/devto huggingface dataset:
Dynamic watermarking with imgproxy and Apache APISIX
Tags: webdev, watermarking, imgproxy, apacheapisix
Published: 2024-07-11 09:02:00

Last week, I described [how to add a dynamic watermark to your images on the JVM](https://blog.frankel.ch/dynamic-watermarking/1/). I didn't find any library, so I had to develop the feature, or, more precisely, an embryo of a feature, by myself. Depending on your tech stack, you must search for an existing library or roll up your sleeves. For example, Rust offers such an out-of-the-box library. Worse, this approach might be impossible to implement if you don't have access to the source image.

Another alternative is to use ready-made components, namely [imgproxy](https://imgproxy.net/) and [Apache APISIX](https://apisix.apache.org/). I already combined them to [resize images on-the-fly](https://blog.frankel.ch/resize-images-on-the-fly/).

Here's the general sequence flow of the process:

![Watermark sequence diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/if8anmxwde7oefhzla4p.png)

* When APISIX receives a specific pattern, it calls `imgproxy` with the relevant parameters
* `imgproxy` fetches the original image and the watermark to apply
* It watermarks the original image and returns the result to APISIX

Let's say the pattern is `/watermark/*`.

We can define two routes:

```yaml
routes:
  - uri: "*"                                                                     #1
    upstream:
      nodes:
        "server:3000": 1
  - uri: /watermark/*                                                            #2
    plugins:
      proxy-rewrite:                                                             #3
        regex_uri:
          - /watermark/(.*)
          - /dummy_sig/watermark:0.8:nowe:20:20:0.2/plain/http://server:3000/$1  #4
    upstream:
      nodes:
        "imgproxy:8080": 1                                                       #5
```

1. Catch-all route that forwards to the web server
2. Watermark images route
3. Rewrite the URL...
4. ...with an `imgproxy`-configured route and...
5. ...forward to `imageproxy`

You can find the exact rewritten URL syntax in [imgproxy](https://docs.imgproxy.net/features/watermark) documentation. The watermark itself is configured via a single environment variable. You should buy `imgproxy`'s Pro version if you need different watermarks. As a poor man's alternative, you could also set up different instances, each with its watermark, and configure APISIX to route the request to the desired instance.

In this post, we implemented a watermarking feature with the help of `imgproxy`. The more I think about it, the more I think they make a match made in Heaven.

The complete source code for this post can be found on GitHub:

{% embed https://github.com/ajavageek/watermark-on-the-fly %}

**To go further:**

* [Digital watermarking](https://en.wikipedia.org/wiki/Digital_watermarking)
* [imgproxy documentation](https://docs.imgproxy.net/)
* [imgproxy interactive demo](https://imgproxy.net/)

<hr>

_Originally published at [A Java Geek](https://blog.frankel.ch/dynamic-watermarking/2/) on July 7<sup>th</sup>, 2024_
Going Further with Styling
Tags: html, css, beginners, webdev
Published: 2024-07-08 14:00:00

Hey there, welcome back to **Learn As You Code: HTML & CSS**! Today, we’re diving deeper into the world of styling. Up until now, we’ve been styling elements directly. But what if you have two `<h2>` elements and want each to look different? Enter CSS selectors!

## Element Selectors

You’re already familiar with these, but let’s recap:

```css
h1 {
  font-size: 32px;
  font-family: Arial;
  font-weight: 500;
}
```

This ruleset targets all `<h1>` elements, setting their font size, family, and weight. Element selectors are great for broad strokes, like setting a style guide for your whole page. But let’s face it, not all `<p>` tags should look the same. For more specific styling, we need to up our game!

## Class Selectors

Classes to the rescue! Want two `<p>` tags to look different? Add classes:

```html
<p class="big red">This text is BIG and red.</p>
<p class="small blue">This text is small and blue.</p>
```

Each `<p>` tag has two classes. In your CSS, target these classes with a `.`:

```css
.big {
  font-size: 100px;
}

.small {
  font-size: 9px;
}

.red {
  color: red;
}

.blue {
  color: blue;
}
```

Boom! Styles applied. You might ask, “Why not combine styles into fewer classes?” Good question! I like to keep classes flexible. You never know when you might want to reuse `small` without `blue`.

## Id Selectors

For unique elements, use IDs. Check this out:

```html
<p id="name">My Name is Nolan!</p>
```

Use IDs sparingly, only once per page. Target them in CSS with `#`:

```css
#name {
  text-decoration: underline;
}
```

Simple, right?

## Conflicting Styles

Now, what if an element has both a class and an ID? Like this:

```html
<p id="red" class="blue">Will I be red or blue?</p>
```

It’ll be red! Why? Because IDs are more specific than classes. Here’s a quick example:

```html
<p id="red" class="underline">I’m styled by three rulesets!</p>
```

```css
p {
  font-size: 12px;
  color: black;
  text-decoration: none;
}

.underline {
  text-decoration: underline;
}

#red {
  color: red;
}
```

The text turns red and gets underlined, with a font size of 12px. IDs trump classes, which in turn override element selectors. This cascade of styles makes your page look polished without repeated code.

## Challenge

Time to level up your About Me page! Here’s your mission:

- Set default styles for `<h1>`, `<h2>`, and `<p>` using element selectors.
- Add a tagline under your name with a `<p>` tag and style it using an ID.
- Jazz up other text using class selectors.

Play around with conflicting styles and see which rules win. Can you figure out why?

Thanks for reading! Let me know if there are any other topics you’d like me explore in this series in the comments, or just let me know how you’re enjoying the series!
nth-child ninja power
Tags: frontend, webdev, css, tutorial
Published: 2024-07-08 16:07:05

In this article, I will share a small example of the `:nth-child()` pseudo-class usage that allows one to efficiently work with dynamic lists.

## Problem

Let's first look at the problem I had. My task was to render a tree with different types of nodes. One of the node types presents a list, and I wanted to add alternating zebra-like backgrounds to them. Below is the visual representation of the UI I've been aiming for.

![Tree fragment diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vp7rw2hhkfojxwnsysx4.png)

Ok, it seems that I should use a common pattern to match even nodes with an offset - `2n + 4` works for this example.

However, the difficulty is that this list of nodes is dynamic and the nodes can be different. For instance, not every node has a description, and, in this case, offset changes. If a user has permission to edit nodes, there will be an additional node after the description to select all node items for bulk editing. All of this makes offset of node items unpredictable.

According to its definition the pseudo-class `:nth-child()` matches elements based on the indexes of the elements in the child list of their parents. It means that the selector `.nodeItem:nth-child(even)` will not work as might be expected. It will highlight only `.nodeItem` nodes but analyse whether the element is even or not among all siblings.

![:nth-child(even) applied in the lists with different structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0xqluvygc657pdv1u6h.png)

## Solution

`:nth-child()` has syntax to match selectors though. The `:nth-child()` argument can not only describe the function to calculate indices but also restrict them by any selector. For the node example, it looks the following way:

```
.nodeItem:nth-child(even of .nodeItem) {}
```

Now it truly scans only `.nodeItem` nodes and applies styles to even nodes among them!

![:nth-child(even of) applied in the lists with different structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/saenvcuzsbo67btq0hhb.png)

While it is very useful major browsers have supported this syntax only since the spring of 2023 so please still be careful and consider JavaScript solutions if you need to apply a similar approach to styling your dynamic lists with support for older browsers.
Basic Git and GitHub commands
Tags: webdev, github, git, beginners
Published: 2024-07-09 09:57:13

Learning about version control system is an important part of your developer journey. As I started to code, one of the first things that I learnt was about Git and GitHub. Straight from the horse’s mouth, “Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.” It was created by Linus Torvalds in 2005 and has become the standard for version control in software development due to its efficiency and flexibility.
On the other hand, GitHub is a web-based hosting service for Git repositories. It provides a platform where developers can store their Git repositories in the cloud, making it easier to collaborate with others. GitHub adds features on top of Git, such as issue tracking, pull requests, code review, and project management tools. Open-source projects and teams widely use it for managing and sharing code.

Here are some of the basic commands of git that would help you get started using it:

1. git init
   - Initializes a new Git repository in the current directory.

2.  git clone [repository_url]
   - Clones a remote repository from GitHub or another Git hosting service to your local machine.

3.  git add [file(s)]
   - Adds file(s) to the staging area to prepare them for a commit.

4.  git commit -m "commit message"
   - Commits the staged changes to the repository with a descriptive message.

5.  git status
   - Shows the current state of the working directory and staging area.

6.  git pull
   - Fetches changes from the remote repository and merges them into the current branch.

7.  git push
   - Pushes your commits to the remote repository.

8.  git branch
   - Lists all local branches in the repository.

9.  git checkout [branch_name]
   - Switches to the specified branch.

10.  git merge [branch_name]
    - Merges the specified branch into the current branch.

11.  git remote -v
    - Lists the remote repositories associated with the local repository.

Now let’s learn about some of the GitHub Commands:

1.  git remote add origin [repository_url]
   - Sets up a remote repository on GitHub as the origin for your local repository.

2.  git push -u origin [branch_name]
   - Pushes the specified branch to GitHub and sets it as the upstream branch.

3.  git pull origin [branch_name]
   - Fetches changes from GitHub and merges them into the current branch.

4.  git clone [repository_url]
   - Clones a repository from GitHub to your local machine.

5.  git fork
   - Creates a copy of a repository on GitHub under your GitHub account.

6.  git pull-request
   - Opens a pull request on GitHub for merging changes from a branch.

7.  git fetch --all
   - Fetches all branches from the remote repository to your local machine.

These commands cover the basic operations you'll perform when using Git and GitHub for version control and collaboration in software development.
What is the Difference between "sequel" and "SQL"?
Tags: webdev, beginners, programming, tutorial
Published: 2024-07-08 02:50:00


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

As you talk to different people, you will hear two different pronunciations of SQL. SQUEL or SQL.

What is the correct way? Well, it depends on who you ask, and of course, everybody thinks that their way of pronouncing this word is the right way. But, here is a little history about this language.

SQL was originally developed at IBM in the 1970s and back then it was initially called SQUEL, short for Structured English Query Language. But, they changed the acronym to SQL, because SQUEL was a trademark of an airplane company.

So, to this date, there has been an argument about what is the right way to pronounce this language.

Generally speaking, people in non-English speaking countries call it SQL. I'm used to calling it SQUEL because it is shorter and sweeter than SQL. But, if you prefer to call it SQL, that's fine with me, I'm not going to get mad at you.

So, that's the history behind this language.

Happy Coding!
Karl 🤛

P.S. If you want me to help you personally, get [the 2 hour web developer course](https://karlgusta.gumroad.com/l/eofdr) and I'll guide you when you are stuck to become a web expert and apply for web jobs.
Part 2: Learning HTML
Tags: html
Published: 2024-07-12 03:54:37

July 6, 2024

I am working on Codeacademy's HTML Fundamentals Lesson and have learned a few HTML concepts:

- Start an HTML file with the `<!DOCTYPE html>` declaration. This allows the browser to interpret the file as containing html content and works with the correct version of HTML.

- The next line should contain the `<html>` element. Add all of the code between the html open and closing tags.

- Information which will not be shown/rendered on the web page is contained inside between the `<head>` open and closing tags.

- Use the `<title>` element inside of the head to display the web page name on the browser's tab.

- Use `<a>` anchor elements to add links to internal/external pages.

- You can organize your code (spacing/indentation) however you like and it won't reflect on the web page (unless you are nesting incorrectly, which is why indenting and spacing to create readable code is important!).

- Use the following syntax to comment out code or information from the html file: `<!-- content -->"` . The content inside of this code will not be visible on the web page.
Understanding the Monad Design Pattern
Tags: javascript, architecture, designpatterns
Published: 2024-07-11 02:11:27

Monads are a powerful concept in functional programming that help manage side effects and maintain clean, composable code.

In this post, we'll explore the `Maybe` monad design pattern using JavaScript, which is used to handle operations that might fail or return null/undefined.

### What is a Monad?

In simple terms, a monad is a design pattern that allows you to wrap values, chain operations, and handle side effects in a consistent way.

The `Maybe` monad is particularly useful for dealing with null or undefined values without littering your code with null checks.

### Implementing the Maybe Monad

This monad will wrap a value and provide methods to apply functions to that value if it exists.

```javascript
// Maybe Monad Implementation
class Maybe {
    constructor(value) {
        this.value = value;
    }

    static of(value) {
        return new Maybe(value);
    }

    isNothing() {
        return this.value === null || this.value === undefined;
    }

    map(fn) {
        return this.isNothing() ? Maybe.of(null) : Maybe.of(fn(this.value));
    }

    getOrElse(defaultValue) {
        return this.isNothing() ? defaultValue : this.value;
    }
}

```

### Using the Maybe Monad

Let's consider a function that performs division but needs to handle division by zero.

```javascript
const safeDivide = (numerator, denominator) => {
    return denominator === 0 ? Maybe.of(null) : Maybe.of(numerator / denominator);
};

const result = Maybe.of(10)
    .map(x => x * 2) // 20
    .map(x => x + 1) // 21
    .map(x => safeDivide(x, 0)) // Maybe(null)
    .getOrElse('Division by zero');

console.log(result); // Output: Division by zero

```

The `Maybe` monad wraps each intermediate value, applying transformations only if the value is not null or undefined.

The `safeDivide` function returns a `Maybe` monad, ensuring safe handling of division by zero.

### Benefits of Using the Maybe Monad

1. **Composability:** Chain multiple operations cleanly without worrying about null checks.
2. **Readability:** Simplify code by avoiding repetitive null checks.
3. **Safety:** Handle potential null or undefined values gracefully, reducing runtime errors.

### Conclusion

The `Maybe` monad is a powerful tool for managing null or undefined values in JavaScript. By wrapping values in a monad, you can chain operations safely and maintain cleaner, more readable code. This straightforward approach to monads can greatly enhance your functional programming toolkit in JavaScript.

For more technical insights and hands-on tutorials, visit [rmauro.dev](https://rmauro.dev/). Happy coding!
Destiny or Coincidence: Based on Shannon Perry s Experiment.
Tags: python, javascript, replit, codepen
Published: 2024-07-11 00:50:12

**TL;DR:** I developed a project to determine if you have ever crossed paths with ‘that’ person before meeting them in your life based on your mobile.

## Background
I often read [Xataka](https://www.xataka.com/privacidad/cuantas-veces-coincidiste-tu-pareja-antes-conocerla-asi-se-pueden-usar-datos-google-maps-para-descubrirlo) to stay updated on the latest technological developments and news. One thing that i readed and has intrigued me the most is [Shannon Perry](https://twitter.com/Channon_Perry)’s experiment — a data analyst who used location data from her and her boyfriend’s histories to determine if they had ever been close before meeting each other.

## How did she do it?
She exported her and her boyfriend’s data from _Google Takeout_. For more information, you can visit her website. The approach is simple yet fascinating: finding all instances where two people were close within a specific distance, on the same day, and at the same time.

## Now it’s my turn
Considering the approach is straightforward, I was intrigued to develop a similar tool — easy to use and accessible for anyone interested in experimenting with it

Although Shannon explains the procedures to obtain results, as a programmer, I set myself the challenge of doing it on my own, using my own logic.

## Tools Used:
- **Google Takeout**: Used Google Takeout to export my location history data. Once the export process was completed, Google provided a download link.

- **Repli**t: Opted to run the code in the cloud to avoid overloading my laptop. While other options like Google Colab exist, I found Replit worked best for me with the free account. It’s important to interact with the page regularly to prevent the session from timing out.

- **Firebase**: Since my JSON location records file was approximately 400 MB, I uploaded it to Firebase. I chose to process the JSON files via a URL instead of downloading the file directly.

- **CodePen**: Used CodePen to visualize the information obtained from Replit. I decided to use a heatmap to visualize most of the matches, along with options like lists and checkboxes to examine the positions of the two individuals in detail.

Let’s get to work.
1. Go to...

Visit my Medium [post](https://chriisduran.medium.com/destiny-or-coincidence-based-on-shannon-perry-s-experiment-d43da0ac5529) to keep reading... 😊
Browser locally uses AI to remove image backgrounds
Tags: browser, ai
Published: 2024-07-08 08:56:11

---
title: Browser locally uses AI to remove image backgrounds
published: true
date: 2024-07-07 13:28:51 UTC
tags: Browser,AI
canonical_url: https://chi.miantiao.me/posts/ai-remove-image-background/
---

Yo, so I've been digging into this whole AI thing for front-end development lately, and stumbled upon this cool Transformers.js example.  Turned it into a sweet little tool, check it out!

Basically, it uses Transformers.js in a WebWorker to tap into WebGPU and run this RMBG-1.4 model.  Long story short, you can now use AI to nuke image backgrounds right in your browser. And get this, it only takes half a second to process a 4K image on my M1 PRO!

Here's the link to the tool: [https://html.zone/background-remover](https://html.zone/background-remover)

[![AI background remover](https://og-image.html.zone/https://html.zone/background-remover)](https://html.zone/background-remover)

* * *

Wanna build it yourself?  Head over to [https://github.com/xenova/transformers.js/tree/main/examples/remove-background-client](https://github.com/xenova/transformers.js/tree/main/examples/remove-background-client) for the source code.  Oh, and heads up, you gotta be on Transformers.js V3 to mess with WebGPU. 

 ![stat](https://c.statcounter.com/9823304/0/92a1d06c/1/)
Exploring Advanced Features of TypeScript
Published: 2024-07-08 00:34:52

Introduction:

TypeScript is a superset of JavaScript that offers advanced features and advantages to enhance the development experience. It provides static typing, interfaces, classes, and other features to help developers write more robust and error-free code. In this article, we will explore some of the advanced features of TypeScript and the benefits they offer.

Advantages:

1. Static Typing: TypeScript allows developers to define types for variables, parameters, and return values, providing better code predictability and reducing runtime errors.

2. Code Organization: Using interfaces and classes, TypeScript provides a more structured approach for organizing code, making it easier to maintain and understand.

3. Tool Support: TypeScript integrates with popular code editors, providing features like code completion, refactoring, and error highlighting, making development more efficient.

Disadvantages:

1. Steep Learning Curve: TypeScript has a steeper learning curve compared to JavaScript, as it adds new syntax and concepts.

2. Complex Configurations: Setting up and configuring TypeScript projects can be more complex and time-consuming.

Features:

1. Decorators: TypeScript offers decorators, a language feature for iterating over class declarations, allowing developers to add extra functionality to a class without changing its implementation.

2. Generics: Generics allow developers to write reusable code for different types, similar to templates in other programming languages.

Conclusion:

In conclusion, TypeScript offers powerful features, such as static typing, interfaces, classes, and decorators, providing developers with a more structured and efficient approach to building applications. While it may have a steeper learning curve and require more complex configurations, the benefits it offers make it a valuable tool for developers to explore and utilize.
Invalid Date in Safari
Tags: safari, webdev, javascript, programming
Published: 2024-07-08 01:43:13

Hello everyone,

Today, I encountered a weird bug that only appears in the Safari browser. It works fine in other browsers. After debugging the code in Safari, I found that filtering data by date was resulting in an empty array. I have been using dayjs as my date library for formatting and filtering.

Here is the source date I use: "2024-7-1,6:0:0".

After some research, I discovered that Safari requires dates to be in ISO 8601 format. To handle this, I created a function formatDateForSafari that converts a date string into the ISO 8601 format. Here is the code:

```
function dateStringToISO(dateString) {
  const date = new Date(dateString);

  // Check if the date is valid
  if (isNaN(date.getTime())) {
    throw new Error("Invalid date");
  }

  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');

  return `${year}-${month}-${day}`;
}

// Example usage:
const date = "2024-7-1,6:0:0";
console.log(dateStringToISO(date)); // Output: 2024-07-01
```

By using this function, you can ensure that your date strings are properly formatted for Safari, avoiding issues with invalid dates.

This version maintains your original points while improving readability and coherence.

Update function name regarding @jayantbh suggestions. Thanks for your suggestion