teleren/devto huggingface dataset:
How to check if a tab is active in React
Tags: typescript, javascript, webdev, web3
Published: 2023-07-06 17:07:10

Before diving into the specifics of how to detect active tab engagement, I'd like to share a real-world web3 scenario where this was a use case. Imagine a user toggling between two different tabs, each operating on the same wallet but different networks. For instance, one decentralized finance (DeFi) application could be running on Arbitrum while the other functions on Ethereum. In such cases, a casual alert indicating a network mismatch from MetaMask could lead to users prematurely closing your website. Therefore, it's crucial to discern whether the user is actively viewing your tab before deploying any alert regarding network discrepancies.

To address this challenge, we turn our attention to one particularly handy DOM event: visibilitychange. This event allows us to detect changes in the visibility state of the tab, i.e., whether it's in focus or in the background.

So, how do we implement this in a React application?

It is as straightforward as it gets. To ensure the user is actively viewing the tab when an alert is initiated, you can listen to the visibilitychange event and check the document.visibilityState property.

The following demonstrates a simplified example:

```ts
import { useCallback, useEffect, useState } from 'react';

const useIsTabActive = () => {
  const [isTabVisible, setIsTabVisible] = useState(true);

  const handleVisibilityChange = useCallback(() => {
    setIsTabVisible(document.visibilityState === 'visible');
  }, []);

  useEffect(() => {
    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  return isTabVisible;
};

export default useIsTabActive;
```

By incorporating this simple check into your web3 applications, you can significantly improve your user experience. Not only does it prevent unnecessary alerts when a user is not actively engaging with your application, but it also respects their attention and focus, leading to a more professional and user-centric application.

Stay tuned for further discussions on improving user experience in web3 applications in upcoming posts.
Chrome Driver for Selenium Python
Tags: selenium, python
Published: 2023-07-06 17:05:58

Install chrome driver in selenium python.
This will download and install chrome driver every time you run the project. You don't have to manually download and locate the file in the script:
```
pip install selenium
```
```
pip install webdriver_manager
```
in the editor paste these lines:

```
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://dev.to/")
```
Javascript Currying #1
Tags: javascript, programming, webdev, react
Published: 2023-07-06 16:49:30

**Currying** is a useful technique used in JavaScript applications.

Please implement a curry() function, which accepts a function and return a curried one.

Good morning! Here's your coding interview problem for today.

This problem was asked by Google.

Currying is a useful technique used in JavaScript applications.

Please implement a curry() function, which accepts a function and return a curried one.

Example

```
const multiplyThree = (a, b, c) => {
   return a * b * c;
};
  
const curriedMultiplyThree = curry(multiplyThree);

console.log(curriedMultiplyThree(1, 3, 5)); // 15
console.log(curriedMultiplyThree(1, 2)(5)); // 10
console.log(curriedMultiplyThree(1)(2)(3)); // 6

```

**Note**: The implementation of curry() is not provided and needs to be completed.

**Solution**

```
function curry(fn) {
  return function curried(...args) {
    if (fn.length === args.length) {
      return fn.apply(this, args);
    }
    return (...args2) => curried.apply(this, args.concat(args2));
  };
}
```

**Explanation**

- When you call curry() and pass it a function, it returns a new curried() function.
- The first time you call curried() and pass it some arguments, it checks if the number of arguments matches the required arguments for the original function.
- If it does match, it calls the original function with those arguments.
- If it doesn't match, it returns a new function that will accumulate more arguments and call curried() again.
- This continues until enough arguments have been accumulated to call the original function.
The Road Trip Analogy - Agile vs Waterfall
Tags: agile
Published: 2023-07-06 16:36:00

Recently I’ve seen a lot of confusion around Waterfall and Agile. I wanted to provide a high-level analogy to help people understand the difference.

> Imagine you’re planning a cross-country road trip with friends. You carefully select your destination, listing all the exciting places to stop and see. You map out the entire route, including where you’ll sleep each night.

This is Waterfall.

> Now, picture the same road trip, but this time, you only decide the first stop. Each morning, you and your friends discuss where to head next, based on what you enjoyed the day before and the new opportunities that arose. If everyone agrees they’ve had enough at any point, you end the trip and head home.

This is Agile.

The Waterfall approach is excellent when you know exactly what you want and how to get there. It works very well with a fixed budget and/or timeline. The Agile approach is great when you’re unsure of what you want or want to discover new things along the way.

Mixing the two approaches is where things get messy and where most people go wrong. Understanding which method best fits your problem and sticking to it is essential. Agile is not a panacea and does not magically make your team more productive - it’s a different way of working that can be more effective in certain situations.

Original post: https://www.orochena.net/blog/roadtrip-waterfall-agile
Pybit v5 how to subscribe to websocket topics
Tags: bybit, pybit, python
Published: 2023-07-06 16:24:56

Well, in one of my previous post, I talked about Pybit's v2 API, and we are now at v5!

Quite some breaking updates we are expecting especially the parameters' format change for most APIs, basically it is changed from under_score to snakeCase. Upgrading it would make life easier down the road since the [v5 documentations](https://bybit-exchange.github.io/docs/v5) that are being maintained are much readable and informed. And of course, good amount of improvements come with it. See [change log](https://github.com/bybit-exchange/pybit/releases)

Below is an example of using Pybit API to subscribe to account's [order stream](https://bybit-exchange.github.io/docs/v5/websocket/private/order), so that we can trigger callback handler base on its socket events:


```python
from pybit.unified_trading import HTTP
from pybit.unified_trading import WebSocket

api_key = os.environ.get("BYBIT_API_KEY")
api_secret = os.environ.get("BYBIT_API_SECRET")

class AlgoOrderStream:
    def __init__(self, trading_pair):
        self.trading_pair = trading_pair
        self.session = HTTP(testnet=True, api_key=api_key, api_secret=api_secret)
        print("Initialized ORDER_WEBSOCKET_STREAM")

    # callback handler when socket event triggers
    def handle_order_stream(self, message):
        data = message["data"]
        print(data)
        # You can see the changed order data here and perform action, below is just a example action
        # If Long position filled, place a conditional Short order
        if data[0]['side'] == 'Buy' and data[0]['orderStatus'] == 'Filled' :
            self.session.place_order(
                category="linear",
                symbol=self.trading_pair,
                side="Sell",
                orderType="Market",
                qty=0.01, # quantity
                triggerDirection=1, #triggered when market price rises to triggerPrice
                triggerPrice="YourPriceTarget",
                triggerBy="LastPrice",
                positionIdx=0,
                stopLoss="CutLossPrice",
                slTriggerBy="LastPrice",
            )
                
class AlgoBot:
    def __init__(self, trading_pair):
        self.trading_pair = trading_pair
        # initialize websocket instance and point to private topic -> your order stream
        self.ws = WebSocket(
            testnet=True,
            channel_type="private",
            api_key=api_key,
            api_secret=api_secret,
            trace_logging=True,
            restart_on_error=True
        )

    def start():
        orderStream = AlgoOrderStream(trading_pair=self.trading_pair)
        self.ws.order_stream(
            callback=orderStream.handle_order_stream
        )
```

```python
algoBot = AlgoBot(trading_pair="BTCUSDT")
algoBot.start()

```
** Notice that the callback will only fire when there's updates to your order stream, do trigger order change manually for testing purpose.
🚀 Calling all Web3 Developers!
Tags: blockchain, web3, testnet, faucet
Published: 2023-07-06 16:20:12

⚡ Don't waste your precious time accumulating test tokens! 😱

Use http://BuildBear.io 🐻 
The ultimate solution for instant access to a vast reserve of Native and Popular ERC20 Testnet tokens! 💪💰

Start using http://BuildBear.io Now!
[PostgreSQL] Get values from arrays that do not exist in the database
Tags: postgres
Published: 2023-07-06 16:14:25

## Motivations
I have two array values like below now.
If there are some values that are not registered in my database, I want to know them.

### Arrays
#### Array1
```sql
[1, 2, 30, 100]
```

#### Array2
```sql
['hello', 'world', 'sample']
```

#### [Database] sample_tables
|id|name|
|----|----|
|1|hello world|
|2|good morning|

## Getting existed values
I can get values that are registered in the database.

#### Array1
```sql
SELECT * FROM sample_tables WHERE id IN (1, 2, 30, 100);
```

#### Results1
```
1
2
```

#### Array2
```sql
SELECT * FROM sample_tables WHERE REGEXP_LIKE(name, '(hello)|(world)|(sample)')
```

#### Results2
```
hello world
```

* [9.7. Pattern Matching - PostgreSQL: Documentation](https://www.postgresql.org/docs/current/functions-matching.html)

## Getting not existed values
Conversely, how can I get the values that are not registered in the database?

I can use subquery to do that.

#### Array1
```sql
SELECT t1.keyword FROM (SELECT UNNEST(ARRAY[1, 2, 30, 100]) as keyword) as t1
LEFT JOIN sample_tables as t2 ON t2.id = t1.keyword
WHERE t2.ID IS NULL;
```

#### Result1
```
30
100
```

#### Array2
```sql
SELECT t1.keyword FROM (SELECT UNNEST(ARRAY['hello', 'world', 'sample']) as keyword) as t1
LEFT JOIN sample_tables as t2 ON t2.name LIKE '%' || t1.keyword || '%'
WHERE t2.ID IS NULL;
```

#### Results2
```
sample
```

* [SQL WHEREで存在しなかったものだけを抽出 - teratail](https://teratail.com/questions/355873#reply-486182)
* [9.19. Array Functions and Operators - PostgreSQL: Documentation](https://www.postgresql.org/docs/current/functions-array.html)
Top 5 Tips for Creating Effective Data Visualizations 📊
Tags: datascience, learning, design, ux
Published: 2023-07-06 16:11:20

Data visualization is a powerful way to communicate complex information and insights to your audience. But how do we create effective and engaging data visualizations that stand out and get noticed?
<br>
**These are my Top 5 tips for creating ✨beautiful✨ and effective📈 data visualizations:**

**1. Choose the right visualization for the job ✅**
Different types of visualizations are better for different contexts. For example, bar charts are good for comparing categories, line graphs are good for showing trends over time, and maps are good for showing geographic data. Choose the format that best suits your data and your message.

**2. Use predictable patterns 📐**
For the most part, we are all visual learners. We tend to look for familiar patterns and cues when we see a visualization. We are visual, pattern seeking creatures after all! Use common conventions such as placing the most important information at the top left, using consistent fonts and colors, and aligning elements neatly. Make sure to follow the Web Content Accessibility Guidelines (WCAG) 2 as well when creating data visualizations. Remember, designing for accessibility is designing for all.

**3. Use color with purpose 🌈**
Color is one of the most effective ways to draw attention and convey meaning in a visualization. Color can also be used to highlight important information, differentiate or compare groups, or show relationships. However, avoid using too many colors, as this might take away from the point you are trying to get across. Ensure that when you use color, it has a purpose and isn't just for aesthetic reasons.

**4. Keep it simple 💯**
Sometimes less is more. Keeping complexity of individual pages to a minimum will ensure that users don't feel overwhelmed with information. Try to keep the number of total visualizations on any individual page no more than five.

**5. Let your visualizations breathe 🧘**
We all need our personal space, and so do your visualizations! White space is your friend when it comes to data visualization. It helps you organize your charts and graphs, and it makes them easier to read and understand. White space also gives your data visualizations a clean and professional look. So don't be afraid to leave some blank areas around your data. Trust me, your audience will appreciate it!

<br>
⭐**Like + Follow if you found this intersting**⭐

More blog posts like this over on [my website](https://jakecupani.github.io/blog) and my [LinkedIn](https://linkedin.com/in/jakecupani) page.


![Top 5 Data Visualization Tips by Jake Cupani](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jw0j9by4sbp9pnepwms.jpeg)
SV388 Website Đá Gà Cựa Sắt Thomo -✔️ Link Chính Thức SV38.COM
Published: 2023-07-06 15:42:31

https://sv38.com/ SV388 là nhà cái đá gà uy tín và có thâm niên hoạt động lâu năm nhất tại thị trường châu Á✔️ Chuyên gà cựa sắt thomo và cựa sắt thái và các loại đá gà cựa dao✔️✔️✔️
0372868890
dagasv67@gmail.com
284-332 Đ. Âu Cơ, Phường 10, Tân Bình, Thành phố Hồ Chí Minh 70000, Việt Nam
#sv388 #dangkysv388 #dangnhapsv388 #dagacuasatthomo
https://www.youtube.com/@sv388com/about
https://sv388com.tumblr.com/
https://getpocket.com/@290dRpy7T1875gby96A58e3A52g4T7646b2PhYg369x9e6W512by2ie2Y2dfN9b0
https://sv38com.blogspot.com/
https://www.blogger.com/profile/10176306868031970854
How a Content Editable Element Works
Tags: html, contenteditable, webdesign
Published: 2023-07-06 15:36:02

## Focus on Content Editable Element
You can use a ce(content editable) element as a text editor or a content management system. These articles are going to be using a ce as a text editor. Ce elements can be focused on like a input or text area element. Once you focus on a ce, you can start typing.

## The Elements Within a Ce Text Editor
When you make a ce text editor, you want to start with an element such as a paragraph or a div with some text content in it. You can press the enter key & the text editor will start a new line with a new element in it. If you press enter while there is text after the cursor, you will move the text after the cursor to the new element. The element you start the te with will be created every time you press enter.

## The `<br>` tag
The `<br>` tag inside the text editor is important. When you focus in on the te, the cursor needs an element or a text node to start at. So, when I press enter it creates a new `<div>` with a `<br>` tag inside of it. The `<br>` tag is what the cursor is selecting so I can type in it. Once I start typing the `<br>` tag disappears because it’s just a line break, there is no elements or content inside of it. If I delete all the text the `<br>` will reappear, if I hit delete again the element will be deleted.

My name is Chris. You can find more articles about html/css & javascript on the [webplayground](www.webplayground777.com).
photos and videos important react native NPM librarys
Published: 2023-07-06 15:18:22

[https://github.com/gre/react-native-view-shot](https://github.com/gre/react-native-view-shot
)



[https://shopify.github.io/react-native-skia/docs/getting-started/hello-world](https://shopify.github.io/react-native-skia/docs/getting-started/hello-world
)




[https://docs.deepar.ai/](https://docs.deepar.ai/) **<-- PAID**


[https://www.react-native-vision-camera.com/docs/guides/frame-processor-plugin-list](https://www.react-native-vision-camera.com/docs/guides/frame-processor-plugin-list)
A Novice's Introduction to Postgres Enterprise Manager (PEM)
Published: 2023-07-06 15:17:49

Greetings, tech enthusiasts! Today, presenting a robust tool that simplifies the management of PostgreSQL databases: the Postgres Enterprise Manager (PEM). Developed by EnterpriseDB, PEM offers a comprehensive management interface for PostgreSQL databases, irrespective of whether hosted on-premise or in the cloud.

## Unraveling Postgres Enterprise Manager (PEM)

PEM is a database management solution that offers a user-friendly graphical interface for the administration and monitoring of PostgreSQL and EDB Postgres Advanced Server databases. It's engineered to handle a wide range of tasks, from routine administrative duties to performance tuning and system monitoring.

## PEM's Core Features

1. **Monitoring and Administration**: PEM features a comprehensive dashboard that provides a real-time snapshot of your database's performance. It incorporates various charts and graphs that showcase key performance indicators, assisting you in spotting potential issues before they escalate.

2. **Alert and Notifications**: PEM is capable of triggering alerts when specific conditions are met, such as when a database exceeds a certain size or when performance metrics surpass predefined thresholds. This enables you to swiftly react to potential issues.

3. **Performance Diagnostics**: PEM comes equipped with tools for diagnosing performance issues, including query analyzers and performance profilers. These tools aid in pinpointing inefficient queries and other performance bottlenecks.

4. **Backup and Restoration**: PEM incorporates tools for backing up and restoring your databases. You can schedule backups, execute point-in-time recovery, and manage backup files, all from within the PEM interface.

5. **Tuning and Optimization**: PEM offers a range of tools for fine-tuning your databases, including a configuration editor, an index advisor, and a partition manager. These tools assist you in optimizing your databases for peak performance.

## Kickstarting Your Journey with PEM

To begin with PEM, install the PEM server and the PEM agent. The PEM server offers a web-based interface for managing your databases, while the PEM agent interacts with databases and gathers performance data.

After installing PEM, add databases to the PEM interface and commence managing them by creating users, managing permissions, executing SQL queries, monitoring performance, and more.

In conclusion, Postgres Enterprise Manager (PEM) is a potent tool for managing and monitoring PostgreSQL databases. Whether you're a DB experienced or a developer just starting with PostgreSQL, PEM can simplify your tasks and help you extract the maximum potential from your databases.

Stay tuned for more posts where we'll delve into deeper the features of PEM and demonstrate how to effectively use them to manage your databases.

Happy coding!
Sloan's Inbox: How Do You Find a Mentor That Is Right for You?
Tags: discuss
Published: 2023-07-06 15:00:00

Hey there!

I'm Sloan, your friendly neighborhood DEV Moderator, and I am back again with another Sloan's Inbox! 🦥

Think of this as your go-to place for tech advice and sharing observations. Whether it's career development, office politics, industry trends, or improving technical skills, we've got you covered. As you try to level up your skills, you can always come to us for support!

This week I found a question from a new developer that I wanted to share.

### Today's question is:

> Hi! I am pretty new to coding and would like to learn more from folks who have been in tech for a long time. I am struggling to find folks in my community to talk to and am thinking a mentorship program may be a good choice for me! Do you have any tips on how to find a mentor that's right for you? 
> 

Calling all mentees and mentors— do you have any expertise? Tell us your thoughts! Share your comments and questions below and let's help a fellow DEV member out.

---


*Want to submit a question for discussion or ask for advice? [Visit Sloan's Inbox](https://docs.google.com/forms/d/e/1FAIpQLSc6wgzJ1hh2OR4WsWlJN9WHUJ8jV4dFkRDF2TUP32urHSAsQg/viewform)! You can choose to remain anonymous.*
Debugging C/C++ project in VScode
Published: 2023-07-06 14:59:14

Hello, I can't debugging my project. Especially, I can't find class "PassiveElement.cpp". I don't know, what is wrong.

launch.json

```

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "C/C++: g++ build and debug active file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${workspaceFolder}/main", //dont write suffix
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "miDebuggerPath": "/usr/bin/gdb",
      "preLaunchTask": "Open include and source folders"
    }
  ],
  "tasks": [
    {
      "label": "Open include and source folders",
      "type": "shell",
      "command": "code -r ${workspaceFolder}/include ${workspaceFolder}/source",
      "group": "build"
    }
  ]
}

```
main.cpp

```
#include <iostream>

int main() {

     std::cout << "SPICE_NOVAK_TEST_VERSION - ZKOUSKA" << std::endl;

    PassiveElement paselem;

    while (true){}//infinity cycle

    return 0;
}
```
c_cpp_properties.json

```

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "${workspaceFolder}/source",
                "${workspaceFolder}/include"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c17",
            "cppStandard": "c++20",
            "intelliSenseMode": "linux-gcc-x64",
            "configurationProvider": "BartmanAbyss.amiga-debug",
            "forcedInclude": [],
            "browse": {
                "path": [
                    "${workspaceFolder}/include",
                    "${workspaceFolder}/source"
                ],
                "limitSymbolsToIncludedHeaders": true
            }
        }
    ],
    "version": 4
}

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


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h8pomtl8btr4wik7tgi1.png)
Boost your web development game with FREE web components! 🎉
Tags: webdev, coding, tailwindcss, webcomponents
Published: 2023-07-06 12:44:30

🚀 Attention Developers! 🚀

Boost your web development game with FREE web components! 🎉

Are you tired of spending hours coding the same elements over and over again? Say goodbye to repetitive tasks and hello
to effortless development! 😎

Introducing our game-changing web components that streamline your coding process. With our extensive library, you'll
have access to a wide range of pre-built components that can be easily integrated into your projects. 🌐

No matter if you're a beginner or an experienced pro, our components are designed to enhance your workflow, save time,
and deliver outstanding results. 💪

Don't miss out on this opportunity! Click below to get started and supercharge your development speed, Many Tailwind CSS and Bootstrap Components ⚡️

👉 Visit [builtbybuilder.com/components](https://www.builtbybuilder.com/components) now! 👈

#webdevelopment #coding #developers #webcomponents #productivity