teleren/devto huggingface dataset:
PHP: memory errors
Tags: php, beginners, programming
Published: 2023-05-24 10:51:57

PHP is beginner-friendly and abstracts complex mechanisms, so you don't have to handle it by yourself.

It's pretty convenient, but, as a beginner, you might encounter errors that are difficult to solve. Memory errors can be tough, indeed, and you won't like the following message:

> Fatal error: Allowed memory size of [...]

While this error can trigger for various reasons, here are the most common ones and how you can solve the problem.

## I/O: Loading large files

If you use built-in helpers like `file_get_contents()` to read/write/search in small files, you might get what you want without raising any error.

It's another story with large files. The server will likely limit memory usage, and even if it doesn't, that's not unlimited.

You may try to increase this limit, but that's not the best approach. Don't get me wrong. Sometimes, you do have to increase that limit, but PHP provides [I/O streams](https://www.php.net/manual/en/features.commandline.io-streams.php) to run common operations on large files.

`fopen` or `fgets` are low-level PHP helpers you can use to fix the problem. Instead of loading the entire file into memory, the data will come in chunks.

It keeps the memory footprint low and "in control."

## The bad loops

PHP provides convenient keywords, like `while`, `for` or `foreach`, but, in practice, it's not uncommon to see bad implementations.

Here are typical situations:

* you're trying to loop over an array that is too big
* you're nesting loops
* you have an infinite loop
* you're running a CLI script that exhausts your server

And here are a few alternatives:

* read about generators and iterable
* read about recursion
* use frameworks to handle large collections or big maths
* split data to process it in chunks

Of course, it does not mean you have to use one of the above approaches for every loop you create, but, in my experience, **the problem is usually the code, not the server capacity**.

## Memory leaks

Leaks happen when your code keeps using memory when it is no longer needed.

While PHP has some garbage collection, it does not cover all cases, which sometimes impacts performance significantly.

It's usually difficult to spot, so you'll likely need to scan you app with various tools.

## How to prevent and fix most memory errors

The best way, to me, is to profile your app:

* use xdebug
* use Xhprof
* use [memprof](https://github.com/arnaud-lb/php-memory-profiler)
* use built-in PHP helpers, like `memory_get_peak_usage()`, `memory_get_usage()`

PHP 8 introduced [WeakMaps](https://www.php.net/manual/en/class.weakmap.php) recently. While it won't be the ultimate solution to all memory issues, it might help garbage collect unused objects that are not unset automatically.
How to encrypt DNS requests using cloudflared
Published: 2023-05-24 10:38:14

[cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation/) has many functions. When it comes to DNS, it can work as an encrypted DNS proxy. By default it listens for DNS requests and forwards them to Cloudflare DNS server over HTTPS.

But cloudflared can work with any upstream DoH server, including your self-hosted servers.

Let's for example see how to forward DNS queries to Google's encrypted DNS server using cloudflared:

```
cloudflared proxy-dns --upstream https://dns.google/dns-query --port 53
```
This command tells cloudflared to listen on local port 53 (127.0.0.1:53) for DNS queries. It then encrypts and forwards DNS requests to https://dns.google/dns-query.

To use this system-wide, you need to either set 127.0.0.1:53 as your default DNS resolver or make your system resolver forward DNS queries to 127.0.0.1:53.

Most modern linux distributions use systemd-resolved as their main resolver. [In my other tutorial](https://dev.to/mfat/how-to-enable-system-wide-dns-over-https-on-fedora-linux-og7) I have explained how you can make systemd-resolved forward DNS requests to any other resolver.
TIL you can trick Mypys typechecker using typing.cast
Tags: python, typechecking, typeannotating, mypy
Published: 2023-05-24 10:29:30

## Problem

You might have something like this:

```python
# models.py
class MyModelQuerySet(QuerySet[MyModel]):
    # ...

# views.py
class MyView():
    def get_queryset(self) -> QuerySet:
        # ...
        qs = self.model.stuff()

        # ...
        qs = need_other_stuff.get_other_stuff(queryset=qs)
```

And when you run Mypy it will spit out the below error:

```bash
Incompatible types in assignment (expression has type "_QuerySet[MyModel, MyModel]", variable has type "MyModelQuerySet[MyModel]")  [assignment]
```

This error points to the following lines:

```python
# ...
qs = self.model.stuff()
# ...
qs = need_other_stuff.get_other_stuff(queryset=qs)
```

You _could_ explicitly type annotate them but then you'll meet another error

```bash
Name "qs" already defined on line x 
```

## The solution

Python 3.10 has the cast function, and you wrap the above examples like this:

```python
from typing import cast
# ...
qs = cast(MyModelQuerySet, self.model.stuff())
# ...
qs = cast(MyModelQuerySet, need_other_stuff.get_other_stuff(queryset=qs))
```

The cast function essentially just takes in a type as the first parameter, your value as the 2nd and simply returns the 2nd one unchanged.

```python
# .../lib/python3.10/typing.py
def cast(typ, val):
    """Cast a value to a type.

    This returns the value unchanged.  To the type checker this
    signals that the return value has the designated type, but at
    runtime we intentionally don't check anything (we want this
    to be as fast as possible).
    """
    return val
```

A word of caution:

Although doing this is a way to inform mypy your intent it doesn't guarantee that the assigned value will be of the correct type at runtime.
HOW TO GET USER'S LOCATION IN REACT.JS
Tags: react, getlocationuser, javascript, beginners
Published: 2023-05-24 09:43:15

To get a user's location in a React.js application, you can make use of the browser's Geolocation API. Here's a step-by-step guide on how to achieve this:
1.**Install the necessary package:** Open your project directory in the terminal and run the following command to install the `geolocation-api` package:

```
npm install geolocation-api
```

**2. Import the package:**
 In your React component file, import the necessary functions from the geolocation-api package:

```
import { getCurrentPosition } from 'geolocation-api';
```

**3. Create a state variable**
: Inside your component, create a state variable to store the user's location. For example:

```
const [userLocation, setUserLocation] = useState(null);
```

**4. Fetch the user's location: **
Create a function that will fetch the user's location using the Geolocation API. You can call this function when your component mounts or when a specific event occurs. Here's an example of a function that fetches the user's location:

```
const fetchUserLocation = () => {
  getCurrentPosition(
    position => {
      const { latitude, longitude } = position.coords;
      setUserLocation({ latitude, longitude });
    },
    error => {
      console.error('Error getting user location:', error);
    }
  );
};
```
The `getCurrentPosition `function takes two arguments: a success callback and an error callback. The success callback receives the position object, from which you can extract the latitude and longitude. The error callback is called if there is an error in retrieving the location.

**4. Render the user's location:**
 In your component's JSX, display the user's location using the `userLocation `state variable. You can conditionally render the location once it is available. For example:

```
return (
  <div>
    {userLocation ? (
      <div>
        Latitude: {userLocation.latitude}, Longitude: {userLocation.longitude}
      </div>
    ) : (
      <div>Loading location...</div>
    )}
    {/* Add a button or an event to trigger fetching the user's location */}
    <button onClick={fetchUserLocation}>Get Location</button>
  </div>
);
```
This code snippet displays the latitude and longitude once they are available. It shows a loading message initially, and you can trigger fetching the location by clicking the "Get Location" button.

That's it! With these steps, you should be able to retrieve the user's location in a React.js application using the Geolocation API. Remember to handle any errors gracefully and consider user privacy implications when using geolocation features.
Understanding the Mind of an Overachieving Software Developer
Published: 2023-05-24 09:40:26

To effectively manage disruptive, ego-driven, overachieving software developers, you really have to know how their minds work. Only when you understand this personality type and the motivations behind their behavior will you be able to manage them in a way that doesn’t cost the company money.

Here are a few insights I’ve learned about overachieving software developers:

1 - They get a high from completing tasks above and beyond expectations. However, the bigger the challenges they seek, the harder it is for them to get that rush of dopamine.

2 - They get bored easily, and when that happens, they tend to leave the company.

3 - They focus on one task at a time and often miss important details or other opportunities to keep feeding their egos.  

4 - They may look unfocused, but trust me - they’re in the zone, too much in the zone!

5 - They are sensitive. They don’t take criticism well.

6 - They’re too forward-focused and want to get to where they want to be in their careers.

7 - Money doesn’t motivate them - projects and experiments do.

8 - Have you ever told an overachieving developer that they were wrong? Exactly.

9 - Have you ever micromanaged an overachieving developer? Exactly.  

10 - They think they don’t need help or mentoring - they think they can mentor the mentor.

To read more about overachieving software developers, you check out the complete post [here](https://blog.howareyou.work/how-to-handle-overachieving-software-developers/)
Parse vs TryParse in C#
Tags: csharp, backend, beginners, webdev
Published: 2023-05-24 09:30:36

We will explore the difference between the Parse and TryParse methods in C#, and when to use each one.

`int.Parse() will throw an exception
int.TryParse() will return false (but not throw an exception)`

## What are Parse and TryParse methods?
The Parse and TryParse methods are used to convert a string representation of a number to a numeric type, such as int, long, double, decimal, etc. For example, if we have a string "123", we can use int.Parse or int.TryParse to convert it to an integer value 123.

The Parse and TryParse methods are defined on each numeric type, such as System.Int32, System.Double, System.Decimal, etc. They have different overloads that accept different parameters, such as the number format, the culture information, and the style of the number.

What is the difference between Parse and TryParse methods?
The main difference between Parse and TryParse methods is how they handle invalid input. If the string cannot be converted to a number, the** Parse** method will throw an exception, while the **TryParse** method will return false and not throw an exception.

For example, parse the string "abc" as an integer, the int.Parse method will throw a FormatException, while the int TryParse method will return false and assign a default value of 0 to the output parameter.

`
string input = "abc";
int result;

// Using Parse method
try
{
result = int.Parse(input); // This will throw an exception
Console.WriteLine(result);
}
catch (FormatException e)
{
Console.WriteLine(e.Message); // This will print "Input string was not in a correct format."
}

// Using TryParse method
if (int.TryParse(input, out result)) // This will return false
{
Console.WriteLine(result); // This will not be executed
}
else
{
Console.WriteLine("String could not be parsed."); // This will print "String could not be parsed."
}
`
The TryParse method does not use try/catch internally. It is implemented without exceptions so that it is faster and more efficient. In fact, it is likely that the Parse method calls the TryParse method internally and then throws an exception if it returns false.

When to use Parse and TryParse methods?
The general rule is to use Parse method if you are sure that the string will be valid and can be converted to a number. Otherwise, use TryParse method to avoid exceptions and handle invalid input gracefully.

For example, if you are reading user input from a console or a text box, you should use TryParse method to validate the input and display an error message if it is not a valid number. On the other hand, if you are parsing a string that is hard-coded or comes from a reliable source, you can use Parse method and assume that it will succeed.

However, you should always use exception handling when calling Parse method to catch any FormatException that may occur due to unexpected or invalid input. You can also use String.IsNullOrEmpty method to check for null or empty strings before attempting to parse them.
LIQUID STAKING: PROS AND CONS
Published: 2023-05-24 09:16:53

Liquid staking is a way to make your staked assets more flexible and accessible. When you stake your assets, like cryptocurrencies, you usually lock them up in a network's protocol to support its security and operations. But this means you can't easily use or trade those assets until the staking period is over.

With liquid staking, things work differently. It involves special platforms or projects that give you tokens representing your staked assets. These tokens can be traded or used for other purposes while still earning staking rewards. The underlying technology behind liquid staking can vary, but the basic idea is to create these tokens on a separate blockchain or layer.

Now let's look at the advantages and disadvantages of liquid staking:

**Advantages**:

1. More Liquidity: Liquid staking gives you the freedom to access and use the value of your staked assets. You can trade or spend them without waiting for the staking period to end, which provides more liquidity.

2. Increased Flexibility: By participating in liquid staking, you can earn staking rewards while actively engaging with your assets. You can explore other investment opportunities, use them for transactions, or take advantage of different DeFi services.

3. Potential for Higher Returns: Some liquid staking platforms offer additional ways to maximize your returns. They provide various DeFi services where you can lend, borrow, yield farm, or provide liquidity, allowing you to earn more on your staked assets.

4. Diversification: Liquid staking allows you to stake multiple assets across different networks or protocols, helping you diversify your holdings and reduce risks associated with a single asset or network.

**Disadvantages**:

1. Trusting Third-Party Platforms: Liquid staking involves trusting a third-party platform with your staked assets. You need to carefully research and choose a reputable platform to minimize the risk of hacks or theft.

2. Potential Lower Rewards: Some liquid staking platforms may charge fees or take a portion of your staking rewards for their services. As a result, the overall rewards you earn may be lower compared to direct staking on the native blockchain.

3. Limited Governance Influence: In certain liquid staking solutions, you may not have direct voting rights or influence over the governance decisions of the underlying blockchain. This is because your staked assets are represented by derivative tokens.

4. Dependency on Third-Party Platforms: Your experience with liquid staking depends on the functionality and stability of the platforms or projects offering the services. Any technical issues or changes to their operations could impact your staked assets.

It's important to carefully consider these factors and choose a liquid staking solution that aligns with your goals, risk tolerance, and trust in the platforms involved.
Liquid Staking
Published: 2023-05-24 09:10:48

Liquid staking, also known as staking derivatives, is a concept that allows users to unlock the value of their staked assets and utilize them in other ways while still participating in the staking process. Traditional staking involves locking up cryptocurrencies in a network's protocol to support network security and consensus mechanisms. However, this process typically restricts the liquidity of the staked assets, making them unavailable for other purposes.

Liquid staking solutions aim to address this liquidity issue by providing a way for users to retain the staking benefits while accessing the value of their staked assets. Various projects and platforms have emerged to offer liquid staking services, and it's important to consider factors such as security, reputation, and token economics when choosing the most suitable option.

One popular liquid staking solution is Ethereum 2.0 staking. Ethereum is transitioning from a proof-of-work (PoW) to a proof-of-stake (PoS) consensus mechanism through the Ethereum 2.0 upgrade. As part of this upgrade, users can stake their Ethereum (ETH) and earn staking rewards while still having access to the value of their staked ETH through specialized platforms and tokens. These platforms issue tokens that represent a user's staked ETH, allowing them to trade or use the tokens for other purposes.

Another example is the Binance Smart Chain (BSC) and its liquid staking mechanism. Binance, a popular cryptocurrency exchange, offers liquid staking services for assets like Binance Coin (BNB) and other tokens on the BSC network. Users can stake their assets on Binance and receive staking rewards while still having the flexibility to trade or utilize the staked assets on the exchange.

When choosing the best liquid staking option, it's essential to assess factors such as the security and reliability of the platform, the reputation of the project or service provider, the token economics (including staking rewards and fees), and the overall ecosystem and community support. It's advisable to conduct thorough research and consider factors that align with your specific goals and risk tolerance before selecting a liquid staking solution.
Creating an animated text gradient with Tailwind CSS (and vanilla CSS)
Tags: react, tailwindcss, css
Published: 2023-05-24 09:02:03

Note: This article was originally published on my personal [blog](https://www.julienthibeaut.xyz/blog/create-animated-text-gradient-with-css). For more updates, follow me on Twitter [@ibelick](https://twitter.com/Ibelick).


<hr/>

Text gradients have become increasingly popular in modern web design, giving websites a fresh and dynamic look. One excellent example of this trend is Apple's iPhone 14 landing page, where they showcase a stunning animated text gradient.


![animated text gradient](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob9msbnt6rjaqco9dkac.gif)



## Vanilla CSS

<div className="flex items-center justify-center rounded-xl border border-slate-600/50 bg-slate-950 px-4 py-12">
  <AnimatedTextGradient />
</div>

```html
<span>hello, animated text gradient</span>
```

```css
span {
  background: radial-gradient(
    circle at 100%,
    #b2a8fd,
    #8678f9 50%,
    #c7d2fe 75%,
    #9a8dfd 75%
  );
  font-weight: 600;
  background-size: 200% auto;
  color: #000;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: animatedTextGradient 1.5s linear infinite;
}

@keyframes animatedTextGradient {
  to {
    background-position: 200% center;
  }
}
```

What we do here is:

- background: radial-gradient(...): Creates a radial gradient with a circle at 100%, using the specified color stops.
- background-size: 200% auto: Sets the background size to 200% width and automatically adjusts the height.
- background-clip: text: Clips the background to the text content.
- -webkit-text-fill-color: transparent: Makes the text fill transparent (for webkit-based browsers).
- animation: animatedTextGradient 1s linear infinite: Applies the animatedTextGradient animation with a duration of 1s, a linear timing function, and infinite repetition.
- @keyframes rule defines the animatedTextGradient animation, which animates the background position from its initial value to 200% center, creating a smooth gradient movement effect.

## Tailwind CSS

If you prefer using Tailwind CSS, here's the equivalent code written with React:

```js
module.exports = {
  theme: {
    extend: {
      animation: {
        "text-gradient": "text 1.5s linear infinite",
      },
      keyframes: {
        text: {
          to: {
            backgroundPosition: "200% center",
          },
        },
      },
    },
  }
```

Then we use our `animate-text-gradient`, we use a background image with a linear gradient with the same color stops as the previous example, and we set the background size to 200% auto, the background clip to text, and the text color to transparent.

```jsx
export const AnimatedTextGradientTW: React.FC = () => {
  return (
    <span
      className="animate-text-gradient bg-gradient-to-r from-[#b2a8fd] via-[#8678f9] to-[#c7d2fe] 
    bg-[200%_auto] bg-clip-text text-transparent"
    >
      hello, animated text gradient
    </span>
  );
};
```

Feel free to experiment and adapt the techniques discussed in this tutorial to fit your specific design needs and preferences.
5 Tips Public Speaking Untuk Menjadi Pembicara Hebat
Tags: pidato, publicspeaking, tips
Published: 2023-05-24 08:23:49

Public speaking atau berbicara di depan umum merupakan keterampilan yang penting untuk dimiliki di dunia kerja maupun kehidupan sehari-hari. Namun, bagi sebagian orang, public speaking dapat menjadi tantangan yang menakutkan dan menimbulkan kecemasan yang besar.

Untuk membantu Anda menjadi pembicara hebat, berikut adalah lima tips public speaking yang dapat diterapkan:

1. Persiapkan Diri Anda dengan Baik
Persiapan adalah kunci sukses dalam public speaking. Mulailah dengan memahami topik yang akan Anda bicarakan dan siapa audiens yang akan Anda hadapi. Buatlah catatan atau outline dari materi presentasi Anda dan praktikkan presentasi Anda beberapa kali sebelum acara. Anda juga dapat merekam presentasi Anda untuk melihat bagaimana Anda tampil dan memperbaiki kekurangan.

2. Buat Kontak Mata dengan Audiens
Membuat kontak mata dengan audiens dapat membantu Anda menjalin koneksi yang lebih baik dan meningkatkan kepercayaan diri Anda. Saat berbicara, pastikan untuk melihat ke arah audiens, bukan pada layar proyektor atau catatan Anda. Jangan takut untuk memandang orang secara individu, ini akan membantu menunjukkan bahwa Anda peduli dan menghargai mereka.

3. Gunakan Bahasa Tubuh yang Positif
Bahasa tubuh yang positif dapat membantu Anda terlihat lebih percaya diri dan terhubung dengan audiens. Pertahankan postur yang tegak, jangan menyilangkan tangan atau kaki Anda, dan jangan bergerak terlalu banyak. Jika Anda merasa cemas, cobalah bernafas dalam-dalam dan berdiri tegak dengan kepala yang diangkat.

4. Jangan Takut untuk Mengalami Kegagalan
Kegagalan adalah bagian dari proses belajar. Jangan terlalu keras pada diri sendiri jika ada kesalahan atau kekeliruan selama presentasi Anda. Alih-alih berfokus pada kesalahan, belajarlah dari mereka dan gunakan pengalaman ini untuk meningkatkan kemampuan public speaking Anda di masa depan.

5. Jadilah Autentik dan Bersemangat
Menjadi diri sendiri dan menunjukkan semangat yang nyata dapat membantu Anda menjadi pembicara yang lebih baik. Jangan mencoba menjadi orang lain atau memaksakan gaya bicara yang tidak cocok dengan Anda. Biarkan kepribadian Anda bersinar dan biarkan audiens melihat bahwa Anda benar-benar memperhatikan topik yang Anda bicarakan.

Dalam kesimpulannya, menjadi pembicara hebat membutuhkan persiapan yang baik, keterampilan kontak mata dan bahasa tubuh, kemampuan belajar dari kegagalan, serta autentisitas dan semangat yang tulus. Dengan menerapkan tips public speaking ini, Anda dapat meningkatkan keterampilan berbicara Anda dan menjadi pembicara yang lebih percaya diri dan efektif di masa depan.

source : https://bangjalinaja.blogspot.com