teleren/devto huggingface dataset:
How to Focus an Input Field with a Hotkey in React
Tags: javascript, typescript, react, webdev
Published: 2024-05-01 17:11:47

Have you ever wondered how to set a hotkey to focus an input field in your React application? Follow along to learn how. We'll even handle showing different hotkeys based on whether the user is on a Mac or Windows system.

## Implementation

```tsx
const SearchInput: FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);
  const [actionKey, setActionKey] = useState<string>('');

  useEffect(() => {
    // check if navigator is defined to prevent unexpected errors if browser does not support
    if (typeof navigator !== 'undefined') {
      if (/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
        setActionKey('⌘K');
      } else {
        setActionKey('CtrlK');
      }
    }

    const handleKeyPress = (event: KeyboardEvent) => {
      let hotkey = false;
      if (typeof navigator !== 'undefined') {
        if (/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform)) {
          hotkey = event.metaKey && event.key === 'k';
        } else {
          hotkey = event.ctrlKey && event.key === 'k';
        }
      }

      if (hotkey && inputRef.current) {
        inputRef.current.focus();
      }
    };

    // Add event listener when the component mounts
    document.addEventListener('keydown', handleKeyPress);

    // Clean up the event listener when the component unmounts
    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

  return (
    <div className="relative">
      <input
        ref={inputRef}
        type="text"
        className="peer block w-full border-0 px-0 py-3 text-xl focus:ring-0  sm:leading-6"
      />
      {actionKey && (
        <div className="absolute inset-y-0 right-0 flex py-3 pr-1.5">
          <kbd className="inline-flex items-center rounded border border-zinc-300 px-1 font-sans text-xs text-zinc-400">
            {actionKey}
          </kbd>
        </div>
      )}
    </div>
  );
};
```

- We use the `useRef` hook to create a reference to the input element.
- We use the `useEffect` hook to add an event listener for the specified hotkey.
- `navigator.platform` is used to determine if the user is using a mac or windows machine so we know what hotkey to display and listen to.
- calling `inputRef.current.focus()` will focus the input if the hotkey is pressed
- `<kbd />` html element is used to denote textual user input from a keyboard [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd)
- `navigator.platform` is technically deprecated and you could use `navigator.userAgent` as an alternative.
Learn SwiftUI (Day 9/100)
Tags: swift
Published: 2024-05-01 17:11:38

## Swift

* closure
* trailing closure
* shorthand param

```swift
import Cocoa

// ## Function Closure

// The parameters have moved inside the braces, and the in keyword is there to mark the end of the parameter list and the start of the closure’s body itself
// example 1, closure that takes no parameter, return boolean
let demo = { () -> Bool in
    print("Paying an anonymous person…")
    return true
}

// example 2, closure that takes 2 params, return string

let payment = { (user: String, amount: Int) -> String in
    if user == "john" && amount == 10 {
        return "yes"
    }
    return "no"
}
print(payment("john", 8))

// Notice: We don't use parameter names when calling a closure.
// payment(user: "john", amount: 8) --> incorrect

// :warning: Closures cannot use external parameter labels.
/*
 var cutGrass = { (length currentLength: Double) in
    // this is an invalid closure
}
 */

// example 3, pass closure as function type parameter
let team = ["Gloria", "Suzanne", "Piper", "Tiffany", "Tasha"]
let captainFirstTeam = team.sorted(by: { (name1: String, name2: String) -> Bool in
    if name1 == "Suzanne" {
        return true
    } else if name2 == "Suzanne" {
        return false
    }

    return name1 < name2
})
print(captainFirstTeam)

// ## Trailing closure
// 1, swift can infer parameter and return types in closure when pass as func parameter
// 2, remove `(by:`, start the closure directly
let captainFirstTeam2 = team.sorted { name1, name2 in
    if name1 == "Suzanne" {
        return true
    } else if name2 == "Suzanne" {
        return false
    }

    return name1 < name2
}

// ## shorthand syntax with $0, $1, etc.
let captainFirstTeam3 = team.sorted {
    if $0 == "Suzanne" {
        return true
    } else if $1 == "Suzanne" {
        return false
    }
    return $0 < $1
}

// ## Take function as parameter
func makeArray(size: Int, using generator: () -> Int) -> [Int] {
    var numbers = [Int]()
    for _ in 0..<size {
        let newNumber = generator()
        numbers.append(newNumber)
    }
    return numbers
}

// ## Check point

/*
 Your input is this:
 let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]
 
 Your job is to:
 Filter out any numbers that are even
 Sort the array in ascending order
 Map them to strings in the format “7 is a lucky number”
 Print the resulting array, one item per line
 */

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]
let result = luckyNumbers.filter({!$0.isMultiple(of: 2)}).sorted() .map({"\($0) is a luck number"})
for ele in result {
    print(ele)
}
```
Learning AWS Day by Day — Day 52 — Amazon Simple Queue Service (SQS)
Tags: aws, cloud, cloudcomputing, beginners
Published: 2024-05-01 17:10:10

Exploring AWS !!

Day 52

Amazon Simple Queue Service (SQS)

Helps in integration and decoupling of software systems and components. It offers dead-letter queues and cost allocation tags.

Benefits:
Security: you can control sending and receiving of messages from SQS. Can use default SQS server-side-encryption (SSE) or custom SSE keys managed in KMS for transmitting sensitive data.
Durability: SQS stores your data on multiple servers. Standard queues support at-least-once delivery message and FIFO queues support exactly once support message processing and high throughput mode.
Availability: SQS provides high availability for production and consumption of messages.
Scalability: buffered requests can be processed, scaling for handling any load increases or spikes.
Reliability: SQS locks the messages while processing, so that multiple producers can send messages and multiple consumers can receive it.
Customization: Your SQS queue need not be exactly same, you can set some default delay on the queue. Storage of message contents can be increased using S3 or DynamoDB, with SQS pointing to S3 or splitting larger messages into smaller.

SQS Architecture:
Three main parts of a distributed system: components, queue, messages in queue.
Lets say in this scenario, your system has several producers (components that send messages to queue) and several consumers, which receive messages from the queue, the messages (blue and green in color) are stored across multiple SQS servers.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tmoyhrayvcg9142097so.png)
Message Lifecycle:
1. A producer sends message ‘blue’ to a queue, which is stored across multiple servers.
2. When consumer needs to process a message, it consumes them from queue, and returns the message ‘blue’. Till the time ‘blue’ message is being processed, it remains in the queue and isn’t returned to the requests till the visibility timeout.
3. The consumer then deletes the message from the queue to avoid processing and receiving again when the visibility timeout expires.
Array vs ArrayList
Tags: datastructures, array, arraylist
Published: 2024-05-01 17:06:56

The decision between using an ArrayList and a traditional array depends on various factors, including flexibility, ease of use, performance, and memory management.

**Flexibility:** ArrayLists offer more flexibility than arrays because they can dynamically resize themselves. You don't need to specify the size of an ArrayList upfront, unlike arrays where you must declare the size when you initialize them.
**Ease of use:** ArrayLists provide convenient methods for adding, removing, and accessing elements. They have built-in methods like add(), remove(), get(), etc., which makes manipulating data easier compared to arrays, where you have to manually manage resizing and shifting elements.
**Performance:** Arrays typically offer better performance in terms of accessing elements since they provide direct access to any element based on its index. ArrayLists, on the other hand, have some overhead associated with dynamic resizing and object wrapping, which might affect performance in performance-critical applications.
**Memory management:** Arrays tend to be more memory-efficient than ArrayLists because ArrayLists use an underlying array to store elements along with additional metadata to manage resizing and other operations. However, this difference might not be significant unless you're dealing with very large datasets or memory-constrained environments.

Here are some scenarios where you might prefer one over the other:
- Use an array when you know the size of the data structure beforehand and need direct access to elements with minimal overhead.
- Use an ArrayList when you need a dynamically resizable data structure, especially if you're dealing with a collection of objects whose size might change frequently.
- In performance-sensitive applications, such as low-level system programming or high-frequency trading systems, where every CPU cycle counts, you might opt for arrays to minimize overhead.

In most other cases, where ease of use and flexibility are more important than absolute performance, ArrayLists provide a more convenient option.
Ultimately, the choice between an ArrayList and an array depends on the specific requirements and constraints of your application.
Stay Updated with Python/FastAPI/Django: Weekly News Summary (22/04/2024–28/04/2024)
Tags: python, django, fastapi, flask
Published: 2024-05-01 17:00:28

Dive into the latest tech buzz with this weekly news summary, focusing on Python, FastAPI, and Django updates from April 22nd to April 28th, 2024. Stay ahead in the tech game with insights curated just for you!

- Python 3.11 alpha 4 released, showcasing new features like pattern matching improvements and changes in library modules.
- FastAPI 1.0 beta 1 was unveiled, introducing significant enhancements such as WebSocket support and automatic OpenAPI documentation generation.
- Django 4.0 alpha 1 launched, offering enhancements like asynchronous views and support for Python 3.10.
- Catch up on community highlights, including new packages and tools gaining traction within the Python ecosystem.
- Keep abreast of tutorials and articles covering diverse topics like performance optimisation, best practices, and upcoming trends in Python development.

This summary offers a concise overview of recent advancements in the Python/FastAPI/Django framework, providing valuable insights for developers and enthusiasts alike. Explore the full post for more in-depth coverage and stay updated on the latest in Python/FastAPI/Django development.

Check out the complete article here [https://poovarasu.dev/python-fastapi-django-weekly-news-summary-22-04-2024-to-28-04-2024](https://poovarasu.dev/python-fastapi-django-weekly-news-summary-22-04-2024-to-28-04-2024)
4 ways to retrieve your OrgID/groupID from Anypoint Platform
Tags: mulesoft, tips
Published: 2024-05-01 16:43:58

> _Note: the ids and credentials in this article are no longer available._

## From Access Management

In Anypoint Platform, head to **Access Management** > **Business Groups** and select the Business Group you want to retrieve the ID from. You will see the **Business Group ID** in the **Settings** tab.

![Screenshot from Access Management](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/27nqdr9vc0lphp1wjn1o.png)

In this screen, you will also find more information like
- **organization's client id/secret** - which are normally used from Anypoint Studio to test API Autodiscovery
- **organization domain** - useful to access your Exchange public portal

Plus, if you go to the **Environments** tab, you will be able to retrieve each **environment's client id/secret**, which are useful for API Autodiscovery and other features.

## From API Manager's URL

In Anypoint Platform, head to **API Manager**. Take a look at the URL in your browser. Your organization ID is the one after the `organizations/` part.

![Screenshot of the URL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v9hc1rew5zylg0ol7c4m.png)

Here's my URL as example:

```
https://anypoint.mulesoft.com/apimanager/sf-7743/#/organizations/4500658a-7637-4fcf-bc7d-51d1feb28edb/environments/f2346118-f56d-4a11-8009-491e6f9ed6d9/apis
```

In this URL, you will also find more information like
- **organization domain** - in this example it would be `sf-7743`
- **environment ID** - in this example it would be `f2346118-f56d-4a11-8009-491e6f9ed6d9`

## From API Manager's UI

In Anypoint Platform, head to **API Manager** and click on the **Environment information** (ℹ️) button, next to the **Add API** button. You will see the **Business Group ID** in this prompt.

![Environment information from API Manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ab7356uyxt6k51hw1ilx.png)

In this prompt, you will also find more information like
- **environment id**
- **environment's** client id/secret
- **organization's** client id/secret

## Using the Anypoint Platform Chrome Extension

You can download this chrome extension [here](https://chromewebstore.google.com/detail/gofndnflkobgljnjjalmehnlamoifmhc). It was created by [Edgar Moran](https://www.linkedin.com/in/yucemoran/), MuleSoft Ambassador. I cannot recommend this extension enough!

![Screenshot of the Anypoint Platform Chrome Extension to retrieve the organization id](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nr6qsu2ppyffj16vzap4.png)

Besides helping you retrieve the organization id, you can also find the environment id and the token to connect Anypoint Platform :) ...and more!!
Unleash Your Inner Gambler: Conquer Situs Slot Gacor
Published: 2024-05-01 16:34:55

Introduction

Welcome to "Unleash Your Inner Gambler," your guide to conquering Situs Slot Gacor and embracing the thrill of online slot gaming. In this guide, we'll explore how to tap into your instincts, harness your courage, and navigate the world of Situs Slot Gacor with confidence. Whether you're a cautious player or a bold risk-taker, this guide will help you unlock your full potential and emerge victorious on Situs Slot Gacor.

Embracing Your Instincts

At the heart of every successful gambler is a keen sense of intuition. Trust your instincts and follow your gut when making decisions on Situs Slot Gacor. Whether it's choosing which game to play, deciding when to increase your bets, or knowing when to cash out, your instincts can be a valuable guide. Embrace your intuition and let it lead you to success on Situs Slot Gacor.

Harnessing Your Courage
Courage is another essential trait for conquering Situs Slot Gacor. Don't be afraid to take calculated risks and step outside your comfort zone. Whether it's betting big on a high-stakes game or trying a new strategy, courage can open doors to new opportunities and bigger rewards. Embrace your inner gambler, be bold in your choices, and watch as fortune smiles [slot gacor](https://live-thehills.com/) upon you on Situs Slot Gacor.

Mastering Risk Management
While courage is essential, so too is prudent risk management. Set clear limits for yourself and stick to them, even in the heat of the moment. Avoid chasing losses or betting more than you can afford to lose. By mastering risk management, you'll ensure that your gaming sessions remain enjoyable and sustainable over the long term, allowing you to thrive on Situs Slot Gacor.
Adapting to Challenges
In the world of online slot gaming, adaptability is key to success. Situs Slot Gacor is a dynamic platform that's constantly evolving, with new games, features, and challenges emerging all the [slot mahjong ways](https://live-thehills.com/) time. Be prepared to adapt your strategies and tactics in response to changing circumstances and opportunities. Stay flexible, keep an open mind, and embrace the challenges that come your way on Situs Slot Gacor.
Celebrating Your Victories
Finally, don't forget to celebrate your victories, no matter how big or small. Whether it's hitting a jackpot, unlocking a bonus round, or simply enjoying a winning streak, take the time to savor your successes and acknowledge your accomplishments on Situs Slot Gacor. Celebrate your victories with pride, and let them fuel your motivation to continue conquering Situs Slot Gacor in the future.
Conclusion
In conclusion, Situs Slot Gacor offers an exciting and rewarding gaming experience for players of all skill levels. By embracing your instincts, harnessing your courage, mastering risk management, adapting to challenges, and celebrating your victories, you can conquer Situs Slot Gacor and emerge victorious. So, unleash your inner gambler, embrace the thrill of the game, server thailand and let the journey begin on Situs Slot Gacor.
JavaScript Proposal: Signals API
Tags: javascript, webdev, beginners, programming
Published: 2024-05-01 16:34:50

{%youtube sV71S2Hkk0Q %}

---

##### Must Read If you haven't

{% link https://dev.to/devsmitra/maximizing-performance-how-to-memoize-async-functions-in-javascript-4on8 %}

{% link https://dev.to/devsmitra/what-why-and-how-javascript-static-initialization-blocks-4n41 %}

{% link https://dev.to/devsmitra/simplify-javascripts-async-concepts-with-one-gif-3c6a %}

---

###### More content at [Dev.to](https://dev.to/devsmitra "Rahul Sharma(DevsMitra)").

{% user devsmitra %}

###### Catch me on
<p>
{% cta https://www.youtube.com/@bit-buddy?sub_confirmation=1 %} Youtube {% endcta %}
{% cta https://github.com/devsmitra %} Github {% endcta %}
{% cta https://www.linkedin.com/in/rahul-sharma-18b8b374 %} LinkedIn {% endcta %}
{% cta https://devsmitra.medium.com %} Medium {% endcta %}
{% cta https://stackblitz.com/@devsmitra %} Stackblitz {% endcta %} 
{% cta https://devsmitra.hashnode.dev %} Hashnode {% endcta %}
{% cta https://hackernoon.com/u/devsmitra %} HackerNoon {% endcta %}
</p>
How to Heroku: Launch Your First App Webinar
Tags: heroku, webinar
Published: 2024-05-01 16:32:25

THURSDAY MAY 9, 2024 
10:30AM–11:30AM PDT

## **How to Heroku: Launch Your First App**
Discover what Heroku is and why businesses choose our NoOps, pro-code environment to surface information that makes their business more efficient while delighting customers.

[Register now](https://invite.salesforce.com/howtoherokulaunchyourfirstapp)

**Event Details**

Businesses of all sizes create web applications to surface data, join information, and deliver insights. When built in traditional virtual environments, these apps require extensive devops and infrastructure management. These essential tasks keep the business running seamlessly and securely, but they also consume valuable time that could be used to develop applications. Heroku has dominated the PaaS market since its inception because it removes the burden of devops and infrastructure management. With Heroku, developers can focus on building applications that drive business value.


Join Ben Rust, Heroku Senior Technical Architect, to learn more about Heroku and to experience a live demo. In this session we will cover:



- Heroku’s container approach built on AWS and commitment to Cloud Native
- The available programming languages and data stores leveraged by Heroku customers
- Nuanced controls and managing application fleets from the Heroku CI/CD
- Leveraging Heroku Connect for a bi-directional sync between Salesforce and other data stores
- Private Spaces and compliance controls
- A live demo showing how easy it is to launch your first app
- Live Q&A


**Speakers**

Ben Rust
Heroku Technical Architect

Gillian Hinkle
Director, Product Marketing
ERROR 1130 (HY000): Host '123.32.23.12' is not allowed to connect to this MySQL server
Tags: mariadb, mysql, webdev
Published: 2024-05-01 16:19:03

### My Problem
I want to connect to mysql server using my personal computer but I have this error.
```bash
ERROR 1130 (HY000): Host '123.32.23.12' is not allowed to connect to this MySQL server
```

### My Solution
Make sure your IP have access to database server

```bash
SELECT host FROM mysql.user WHERE User = 'root';
```

If you only see results with localhost and 127.0.0.1, you cannot connect from an external source. If you see other IP addresses, but not the one you're connecting from - that's also an indication.

You will need to add the IP address of each system that you want to grant access to, and then grant privileges:

```bash
CREATE USER 'root'@'ip_address' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'ip_address';
```

If you see %, well then, there's another problem altogether as that is "any remote source". If however you do want any/all systems to connect via root, use the % wildcard to grant access:

```bash
CREATE USER 'root'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';
```

Finally, reload the permissions, and you should be able to have remote access:

```bash
FLUSH PRIVILEGES;
```

### Reference
- https://stackoverflow.com/questions/19101243/error-1130-hy000-host-is-not-allowed-to-connect-to-this-mysql-server
Visualize your JSON data instantly
Tags: webdev, nextjs, javascript, json
Published: 2024-05-01 16:14:30

Experience the future of JSON viewing with the best JSON Visualizer. From real-time updates to customizable layouts, we've got everything you need to ease your workflow. Try it now and accelerate your data game! 
#JSON #DataVisualization #TechTools

https://www.jsonviewer.tools/
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3xo6394a4dgy9er50rn.gif)
React Connection with V380 Pro
Tags: help
Published: 2024-05-01 16:11:40

let me explain my problem. I am developing an application that uses a drone to show a live video from the camera. In our case I bought this v380 pro wireless camera for this purpose. My problem is that I am developing the application on a local server ad using React js and MERN stack. I have a screen where I am supposed to show the video from the camera. Now as far as I have seen, the v380 pro comes with an application that connects with a local wifi to get the video from the camera. now my question is how do i stream the video from that camera into my react app?