teleren/devto huggingface dataset:
Thread synchronization in python's threading module
Tags: python, programming, computerscience, aync
Published: 2024-03-01 14:18:04

As we saw 👁️👁️ in our previous blogs, threading is susceptible to race conditions. To tackle race conditions, we may use locks and semaphores to manage synchronization and data consistency while using threads

> There are 3 major techniques for thread synchronization
 - Lock 🔒
 - Rlock ®️🔒
 - Semaphore, BoundedSemaphore

### Lock

- A Lock is a basic `synchronization primitive` that provides exclusive access to a shared resource.
- It has two states: `locked` and `unlocked`.
- Only one thread can acquire the lock at a time. If another thread tries to acquire a locked lock, it will be blocked until the lock is released.
- It is not reentrant, meaning that a thread holding the lock cannot acquire it again without releasing it first.

> `with` context manager, manages acquiring and releasing lock for us, other wise we can use lock.acquire() and lock.release() methods as well

```javascript
from threading import Lock

lock = Lock()

def example_function():
    with lock:
        # critical section
        pass

```
### RLock (Reentrant Lock):
 
- An RLock is an extension of the basic Lock that allows a thread to acquire the `lock multiple times` (reentrant).
- A thread that already holds the lock can acquire it again without blocking, but it must release the lock the same number of times it acquired it.
- Useful in situations where a function might need to acquire the same lock recursively.

```javascript
from threading import RLock

rlock = RLock()

def example_function():
    with rlock:
        # critical section
        pass

```
### Semaphore 

- A Semaphore is a more `generalized synchronization primitive` that allows a specified number of threads to access a shared resource concurrently.
- It maintains a counter that is decremented each time a thread acquires it and incremented when the thread releases it.
- Useful for controlling access to a resource with limited capacity.

```javascript
from threading import Semaphore

semaphore = Semaphore(3)  # Allow up to 3 threads to access the resource concurrently

def example_function():
    with semaphore:
        # critical section
        pass

```
### BoundedSemaphore
- A BoundedSemaphore is similar to Semaphore but has an `upper limit` on its counter.
- It raises a ValueError if the counter exceeds the specified bound when incremented.

```javascript
from threading import BoundedSemaphore

bounded_semaphore = BoundedSemaphore(3)  # Bound the semaphore to allow up to 3 threads

def example_function():
    with bounded_semaphore:
        # critical section
        pass

```
## conclusion
- In summary, Lock and RLock provide exclusive access to a shared resource, while Semaphore and BoundedSemaphore allow a specified number of threads to access a shared resource concurrently. The choice between them depends on the synchronization requirements of your multithreaded application
Time conversion
Tags: javascript, beginners, programming, tutorial
Published: 2024-03-01 14:10:36

*Prepare your favorite cup of coffee* because we are about to enter the fantastic world of **Time conversion**.

## What is a time conversion?

A time is represented in the format 12 hours, of **hh:mm:ssAM/PM**. We must convert to 24-hour format. If the time is **12:00:00AM**, it will be represented as **00:00:00**. If the time is **12:00:00PM**, it will be represented as **12:00:00**.

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

Let's learn how to convert a time from **hh:mm:ssAM/PM** to **hh:mm:ss**.

If we have the time **07:05:45PM**, we should return **19:05:45**

```js
const s = '07:05:45PM';
```

The first step is to divide the time into parts, for this we will use the slice method which will limit the time string to 8 positions, so as not to consider the suffix **AM** or **PM**.

```js
s.slice(0,8) // '07:05:45'
```

Now we must obtain the hour, minute and second, for this we will use the split method and pass the **:** parameter so that the positions of the hours, minutes and seconds are separated.

```js
s.slice(0,8).split(':') // ['07', '05', '45']
```

Since we already have the hour, minute and second, we will assign constants to collect each value

```js
const [hour, minute, second] = s.slice(0,8).split(':');
// hour = '07'
// minute = '05'
// second = '45'
```

In this problem, it will only be necessary to modify the hour value to convert AM/PM to 24-hour format. So let's check if the time string has **PM** in its structure

```js
s.includes('PM') // true
```

The includes method will return **true** if the value is contained in the string and **false** if the value is not contained in the string

If the hour string has the **PM** we will convert the format from 12 hours to 24 hours as follows:

```js
hour == 12 ? '12' : Number(hour) + 12
```

If the time is 12PM, it will continue with the number 12. For other cases we will add 12 units to the hour.

When the time is AM, we will have the following validation:

```js
hour == 12 ? '00' : hour
```

For 12AM we will consider the value 00. For other values the time will remain the same.

Finally, we simply return a string concatenating the converted hour, minute and second

```js
return `${hour}:${minute}:${second}`
```

Our final resolution to the problem is:

```js
const s = '07:05:45PM';

const [hour, minute, second] = s.slice(0,8).split(':');

hour = s.includes('PM') ?
    (hour == 12 ? '12' : Number(hour) + 12) :
    (hour == 12 ? '00' : hour);

return `${hour}:${minute}:${second}`;
```

*Share the code, spread knowledge and build the future!* 😉

> Image generated by **DALL·E 3**
5 LAYER DOUBLE COATED NATURAL PEARL MALA - Aakarshan
Tags: naturalpearlmala, 5layerbeadspearlmala, pearlmala, naturalperalmalaonline
Published: 2024-03-01 14:09:43

Explore the allure of our **[5-layer Double Coated Natural Pearl Mala](https://medium.com/@riyasinghhhh88/5-layer-double-coated-natural-pearl-mala-in-uttrakhand-14021c42c32f)**, a truly exquisite jewelry piece that arise social grace and dignity. This exceptional Mala features freshwater pearls in warm white tones, effortlessly elevating the overall aesthetic of any ensemble.Hurry up Additional 10% OFF at Checkout
Material: Pearl
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1yfwxszz1w7t4l0dnhkv.jpg)
Metal Type: No Metal
Chain Type: Ball
Gem Type: Created Pearl, Beads
Occasion Type: Casual & Party wear
Item Type Name: Fashion Jewellery


Link - https://medium.com/@riyasinghhhh88/5-layer-double-coated-natural-pearl-mala-in-uttrakhand-14021c42c32f
Phone - +91-9839397111
Email - sales@akarshans.com
Day 10: Lifecycle Methods in React
Tags: react, reactnative, reactjsdevelopment, javascript
Published: 2024-03-01 14:03:44

**Introduction**
Welcome back to Day 10 of our 30-day blog series on React.js! Today, we'll explore lifecycle methods in React and learn how to perform actions at different stages of a component's lifecycle. Lifecycle methods allow us to hook into specific points in a component's lifecycle, such as when it is mounted, updated, or unmounted.

**Component Lifecycle Phases**
React components go through several lifecycle phases, divided into three main categories:

1. **Mounting**: These methods are called when an instance of a component is being created and inserted into the DOM.

2. **Updating**: These methods are called when a component is being re-rendered due to changes in props or state.

3. **Unmounting**: These methods are called when a component is being removed from the DOM.

**Mounting Lifecycle Methods**
- **constructor**: The constructor method is called before a component is mounted. It's used for initializing state and binding event handlers.

- **render**: The render method is required and is responsible for rendering the component's UI.

- **componentDidMount**: This method is called after the component is mounted into the DOM. It's commonly used for performing initialization that requires DOM nodes, such as fetching data from an API.

**Updating Lifecycle Methods**
- **componentDidUpdate**: This method is called after a component is updated in the DOM. It's useful for performing side effects after a component's state or props change.

- **shouldComponentUpdate**: This method determines whether a component should re-render after state or props change. It's used for optimizing performance by preventing unnecessary re-renders.

**Unmounting Lifecycle Methods**
- **componentWillUnmount**: This method is called just before a component is unmounted and destroyed. It's used for cleanup tasks such as removing event listeners or canceling API requests.

Example Usage
```jsx
class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
  }

  componentDidMount() {
    this.timerID = setInterval(() => {
      this.setState(prevState => ({ seconds: prevState.seconds + 1 }));
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  render() {
    return <div>Seconds: {this.state.seconds}</div>;
  }
}

```
In the above example, the `Timer` component updates the seconds count every second using `setInterval`. We clear the interval in `componentWillUnmount` to prevent memory leaks when the component is unmounted.

Lifecycle methods in React allow us to perform actions at different stages of a component's lifecycle, such as initialization, rendering, updating, and unmounting. Understanding and using lifecycle methods effectively is crucial for building well-structured and performant React applications.

Stay tuned for tomorrow's post, where we'll explore React Hooks, a powerful feature introduced in React 16.8 for adding state and other React features to functional components.
What is your weekend plan?
Tags: weekend, productivity, goal
Published: 2024-03-01 13:51:33

It's Friday

What is your weekend plan?

1. Go for a long walk
2. Spend some time with your family 
3. Work on your side hustle or start one
4. Take some time off to rest and re-energize
5. Reflect on last week and plan for next week
6. Read and watch videos to keep up with trends
7. Do something for your professional development

Share what is one thing you will do this weekend.
Dive into Quixy's Release 4.1
Tags: discuss, news, tutorial, nocode
Published: 2024-03-01 13:51:30

Hey No-Code Community! 

Have you heard about the latest release from Quixy? 
🌟 Release 4.1 is here, and it's packed with game-changing features that will revolutionize the way you work. Check out our teaser video for a sneak peek: [**Release 4.1**](https://bit.ly/3Tid6dH)

Get ready to unlock new possibilities with:
🔥 Multilingual Magic
🔍 The Solution View
✍️ Digital Signatures for Secure Collaboration

Don't miss out on the innovation journey! Click on the link above to witness the Teaser of Release 4.1
**Stay Tuned** for more information and resources to get a good hold on these unique features. 
#NoCode #Innovation #QuixyRelease4.1
Summary - Section 2
Tags: webdev, javascript, beginners, summary
Published: 2024-03-01 13:45:48

## Fundamentals Part 1
[Jonas Schmedtmann Course](https://www.udemy.com/course/the-complete-javascript-course/)
### Primitive Data Types
- Number = Floating point numbers and integers
- String = Sequence of characters between single quotes (''), double quotes ("") or backticks (``)
- Boolean = Logical, true or false
- Undefined = Value of a variable that wasn't yet defined
- Null = Empty value
- Symbol = Unique value and cannot be changed
- BigInt = Larger integer numbers

JavaScript has dynamic typing, which means that we don't define which type of value a variable will hold. Furthermore, variables don't have types, values do.

### let, const and var
- let = block-scoped, defines variables that can be mutated
- const = defines variables that cannot be mutated
- var = function-scoped, defines variables that can be mutated (legacy)

### Expressions and Operators

Source: [Expressions and Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators)

### Operator Precedence

Source: [Operator Precedence table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#table)

### Strings and Template Literals

As said before, we can use single quotes ('') and double quotes ("") to delimit a string, but we can also use backticks (``), and they define template literals.

Usage example: 
```
console.log(`Hello! My name is ${user.name} and I am a ${user.job}.
How can I help you?`); // Output: 'Hello! My name is Raul and I am a Software Developer.
                                   How Can I help you?'
```

### If-Else Statements

Usage example:
```
if (expression) {
} else if (expression) {
} else {
}
```

## Type Conversion and Type Coercion

- Type Conversion = When you manually convert a value from a type to another type.
- Type Coercion = When JavaScript automatically converts a type to another type.

Example Type Conversion:
```
console.log(Number('2024')); // Output: 2024
```

Example Type Coercion:
```
console.log('20' + 24); // Output: '2024'
```

### Truthy and Falsy Values

- There are 5 falsy values, them being:
- - 0
- - ''
- - undefined
- - null
- - NaN

Everything else is a truthy value, it means that if converted to boolean, they will be converted to the truth value ```true```.

### Equality Operators (== vs. ===)

- === Strict Equality Operator. Does not perform type coercion
- == Loose Equality Operator. Does perform type coercion (avoid using it)

### Basic Binary Logical Operators

- && - AND
- || - OR
- ! - NOT

### Switch Statement

Example usage:
```
const foo = 1;

switch (foo) {
    case 0:
        console.log('That is zero.');
        break;
    case 1:
        console.log('Got it!");
        break;
    default:
        console.log('You failed.');
}
```

## Statements and Expressions

- Expressions are pieces of code that produces a value
Example: ```3 + 4 or 1991 or true && false```

- Statements are bigger pieces of code that translate actions
If-Else statement is an example

## Ternary Operator

```[expression] ? [if true] : [if false]```
Day 8: Lists and Keys in React
Tags: react, reactjsdevelopment, reactnative, javascript
Published: 2024-03-01 13:28:12

**Introduction**
Welcome back to Day 8 of our 30-day blog series on React.js! Today, we'll delve into working with lists and keys in React. Lists are a common feature in web development, and React provides powerful tools for efficiently rendering lists of data.

**Rendering Lists in React**
In React, we can render lists of elements by using the map() method to iterate over an array of data and return a list of React elements.

```jsx
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

```

- The `TodoList `component renders an unordered list `(<ul>)` containing list items `(<li>)`.

- The `map()` method is used to iterate over the `todos `array and return a list item for each todo.

- Each list item has a unique `key` prop set to the `id` of the todo item to help React identify which items have changed, added, or removed.

**The Importance of Keys**
Keys are essential when rendering lists in React. They help React identify which items have changed, added, or removed. Keys should be unique among siblings but can be reused across different lists if the items are independent.

**Extracting Components with Keys**
Sometimes, it's beneficial to extract list items into separate components, especially if each item requires more complex rendering or behavior.

```jsx
function TodoItem({ todo }) {
  return <li>{todo.text}</li>;
}

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <TodoItem key={todo.id} todo={todo} />
      ))}
    </ul>
  );
}

```
In the above example, the `TodoItem` component is responsible for rendering each todo item, while the `TodoList` component is responsible for rendering the list of todos.

Lists are a fundamental aspect of web development, and React provides powerful tools for efficiently rendering lists of data. By leveraging the map() method and keys, we can create dynamic and responsive lists in React applications.

Stay tuned for tomorrow's post, where we'll explore forms in React and how to handle user input and form submission effectively.
San Diego Seo Service
Tags: seo
Published: 2024-03-01 13:18:48

If getting the [San Diego SEO service](https://www.seoexpertinindia.com/san-diego-seo-expert/) is your preference then you can get the dedicated SEO services at SEO Expert in India. At SEO experts in India, we are proud to serve our clients beyond the borders with dedicated expertise in the SEO and marketing aspects. No matter whether you have a business operating in San Diego or elsewhere, we can reach you in any part of the world and meet the service requirements. Our SEO experts come with global SEO campaigns to take your online business and blogs beyond the borders. With SEO experts in India, you can grow your business and blogs globally without spending anything extra on fat SEO campaigns.
Little Little
Published: 2024-03-01 13:17:42

Days have past sleeping on the park bench seems like sleeping on rocks, the money i earned last night will be enough to buy a night tent but thinking of it , is it worth it. I mean i have already spent more than a few days on the bench and it isn't that bad making me think i cant waste the bills i earned with hardship on not of worth brands.
Will have to think of something else than selling water on beach takes lot of time to earn a few bucks plus you have to slay your ass under sunset for literally half a day. Maybe selling ice creams will be worth a chance will have to buy ice and bucket to keep them cold , fine if God wants me to suffer like this then why not suffer?
The world doesn't seems like a helpful place after all this heaven has devils walking around everywhere dressed like a human. Have you ever thought these people slaying there ass to get some dollars will help you , don't get angry are you slaying your ass off so that your boss can take all of your work credits. It is what it is after all am not the one depending on others look around yourself note that its not the wings that the devil is hiding its the horn he doesn't wants you to notice. 
Sometimes a beggar is more helpful than the king at least the differences between you and the beggar are less than the mountain of differences between you and the king. Think before choosing.
Day 7: Conditional Rendering in React
Tags: react, reactjsdevelopment, reactnative
Published: 2024-03-01 13:10:02

**Introduction**
Welcome to Day 7 of our 30-day blog series on React.js! Today, we'll explore conditional rendering in React, which allows us to render different components or UI elements based on certain conditions. Conditional rendering is a powerful feature that enables us to create dynamic and interactive user interfaces.

**Conditional Rendering with if Statements**
In React, we can use traditional JavaScript **if** statements to conditionally render components or elements. Here's an example:

```jsx
function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <p>Welcome back!</p>;
  } else {
    return <p>Please sign in.</p>;
  }
}

```

- The `Greeting ` component renders a welcome message if the user is logged in, or a sign-in message if the user is not logged in.

- The condition isLoggedIn determines which message to render.

**Conditional Rendering with Ternary Operator**
We can also use the ternary operator `('condition ? trueValue : falseValue')` for more concise conditional rendering:

```jsx
function Greeting({ isLoggedIn }) {
  return isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>;
}

```
**Conditional Rendering with Logical && Operator**
Another approach for conditional rendering is using the logical `&&` operator, especially for rendering elements based on a single condition:

```jsx
function Greeting({ isLoggedIn }) {
  return isLoggedIn && <p>Welcome back!</p>;
}

```
In the above example, the paragraph element is rendered only if `isLoggedIn `is `true`.

**Conditional Rendering with Switch Statement**
For more complex conditional rendering, we can use a `switch `statement:

```jsx
function StatusBadge({ status }) {
  switch (status) {
    case 'active':
      return <span className="badge badge-success">Active</span>;
    case 'inactive':
      return <span className="badge badge-danger">Inactive</span>;
    default:
      return null;
  }
}

```
In the above example, the `StatusBadge` component renders different badge styles based on the `status `prop.

Conditional rendering is a powerful feature in React that allows us to render different components or elements based on certain conditions. Whether using `if `statements, ternary operators, logical `&&` operators, or `switch` statements, understanding how to conditionally render components is essential for building dynamic and interactive user interfaces.

Stay tuned for tomorrow's post, where we'll dive deeper into working with lists and keys in React and how to efficiently render lists of data.
"Day 37 of My Learning Journey: Setting Sail into Data Excellence! Today's Focus: Maths for Data Analysis (Stats Day -16)
Tags: data, engineering, datascience, statistics
Published: 2024-03-01 13:04:15

STATISTICS FOR DATA ANALYTICS - 16

Confidence Interval and Margin of Error.


Confidence intervals and margin of error in statistical analysis?
 These two concepts play crucial roles in quantifying the uncertainty associated with estimates derived from sample data. Let's delve into what they mean and why they are essential in decision-making processes.
Confidence Interval (CI):
A confidence interval is a range of values that likely contains the true value of a population parameter. It provides a measure of the precision or reliability of an estimate derived from sample data. For instance, if we estimate that the average height of a population is 65 inches with a 95% confidence interval of 60 to 70 inches, it means we are 95% confident that the true population average falls within this range.
Margin of Error:
The margin of error quantifies the amount of uncertainty or variability inherent in a sample estimate. It represents the range within which the true population parameter is likely to lie, given the variability in the sample data and the chosen level of confidence. A smaller margin of error indicates a more precise estimate, while a larger margin implies greater uncertainty.


Why are they important?
Precision in Estimates: Confidence intervals provide a measure of precision, helping researchers and decision-makers assess the reliability of estimates derived from sample data.


Informed Decision-Making: Understanding the margin of error allows decision-makers to make informed choices based on the level of uncertainty associated with a particular estimate.


Comparison of Results: Confidence intervals facilitate comparisons between different estimates, allowing for a better understanding of the variability in the data and the robustness of conclusions drawn from them.
confidence intervals and margin of error are indispensable tools in statistical analysis, providing insights into the reliability and precision of estimates derived from sample data. By incorporating these concepts into our decision-making processes, we can make more informed choices and draw more reliable conclusions from data analysis.


Feel free to share this post to enhance awareness and understanding of these fundamental concepts in statistical analysis!



🙏 Thank you all for your time and support! 🙏
Don't forget to catch me daily at 6:30 Pm for the latest updates on my programming journey! Let's continue to learn, grow, and inspire together! 💻✨