teleren/devto huggingface dataset:
DEV Mods' Favorites of 2023
Tags: bestofdev, meta, community, devimpact2023
Published: 2023-12-22 14:00:00

This past year we saw so many wonderful posts being shared in our community on DEV! 

Thankfully, behind the scenes, we have a crew of [DEV Community Mods](https://dev.to/community-moderation) taking action to uplift the best content we have to offer. With their mod abilities, these folks are regularly upvoting the good stuff (👍), downvoting the less-than-good stuff (👎), and reporting any spam to us admins (🧐) so we can take action to remove it. These moderator actions are invisible to the average DEV community member, and our mods are the unsung heroes volunteering their time to help make DEV a better place for all.

---

## Mod Faves

On that note, about a week ago, I sent a survey to our 5,000+ mods to collect their favorite picks of the year and these were the top picks in each category.

---

### Favorite Post of the Year

The most highly voted post of the year by mods goes to @tbroyer's "[How I teach Git](tbroyer)." 👏

{% embed https://dev.to/tbroyer/how-i-teach-git-3nj3 %}

---

### Favorite Discussion of the Year

The discussion with the most votes is @mcharytoniuk's "[Money or Passion?](https://dev.to/mcharytoniuk/money-or-passion-3h51)" 💰❤️

{% embed https://dev.to/mcharytoniuk/money-or-passion-3h51 %}

---

### Favorite Series of the Year

As voted by DEV mods, @bekahhw's [New Maintainer Resources](https://dev.to/bekahhw/series/25520) takes the cake for most voted-on series. 🎂 

The following is the first post in the series:

{% embed https://dev.to/opensauced/so-youre-interested-in-being-an-open-source-maintainer-5bb2 %}

---

### Favorite Author of the Year

Lastly, the votes are in, and the mods' favorite author of the year is...

🥁🥁🥁🥁🥁🥁🥁

the amazing @yuridevat!!!! 🙌

{% embed https://dev.to/yuridevat %}

---

## That's a Wrap! 🎁

And that's all of this year's favorites as chosen by the awesome team of DEV Mods.
Methods of Handling Asynchronous Code
Tags: abdulrhmanjs
Published: 2023-12-22 13:59:58

JavaScript provides three methods of handling asynchronous code: callbacks, promises, and async/await. Let's discuss each.

### Callbacks
Asynchronous callbacks are functions that are passed to another function so that the internal function can begin running code in the background. As soon as we need to handle multiple asynchronous operations, Callback Functions nest into one another, which leads to callback hell. This makes callbacks an old-fashioned method of writing asynchronous Javascript.

This is the basic syntax of the callback function:
```
function demoFunction(callback){
  callback();
}
```

### Promises
[Promises](https://dev.to/abdomohamed785/promises-in-js-i87) are used to track asynchronous operations, whether the asynchronous event has been executed or not. Promises have four states:
**Pending**: The initial state of promise before the event happens not fulfilled or rejected yet.
**Fulfilled**: Action/Operation related to the promise completed successfully.
**Rejected**: Action/Operation related to the promise failed
**Settled**: Promise has been fulfilled or rejected

```
let promise = new Promise (function(resolve, reject) {
  ... code
})
```


### Async/Await
Async/await works with promises in asynchronous functions, making asynchronous code appear more like synchronous or procedural code. A promise is returned by an asynchronous function.

The syntax of an async function is as follows:
```
async function name(parameter1, parameter2, ...paramaterN) {
  // statements
}
``` 

Await can only be used in async functions, and it is used for calling async functions. Await blocks the execution of the code inside the async function in which it is contained until the async function has either resolved or been rejected.

Here is the syntax of the await function:

```
let result = await promise;
```
Promises in Js
Tags: abdulrhmanjs
Published: 2023-12-22 13:37:56

JavaScript Promise are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. 

Prior to promises **events** and **callback** functions were used but they had limited functionalities and created unmanageable code. 

Multiple callback functions would create callback hell (a chain of limitless callbacks inside each other) that leads to unmanageable code. 

Promises are used to handle asynchronous operations in JavaScript.

Promises are objects that have four states :
1) **Pending**: The initial state which means not rejected nor resolved. 
2) **Fulfilled**: This term refers to successful completion. 
3) **Rejected**:  means the promise cannot be fulfilled due to an error or some exceptional situations in asynchronous operations. 
4) **Settled**: Promise has been fulfilled or rejected

You can decide what to do upon this promise either in the happy way or the errors way, so there are 2 methods to do so 
then() and catch()

```
let promise = new Promise(function (resolve, reject) {
	const x = "test";
	const y = "test"
	if (x === y) {
		resolve();
	} else {
		reject();
	}
});

promise
	.then(function () {
		console.log('Success');
	})
	.catch(function () {
		console.log('Some error has occurred');
	});

```

then() method can take 2nd argument, so you ignore catch()
 The second argument is executed if the promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method

```
let promise = new Promise(function (resolve, reject) {
	resolve('test again');
})

promise
	.then(function (successMessage) {
		//success handler function is invoked 
		console.log(successMessage);
	}, function (errorMessage) {
		console.log(errorMessage);
	});
```
Lazy Query in RTK Query
Published: 2023-12-22 13:30:12

`useLazyGetCustomerNameListQuery` is a hook generated by Redux Toolkit Query for the `getCustomerNameList` query endpoint in your API. This hook provides a function that you can call to execute the query lazily. It's part of the `useQuery` hooks provided by Redux Toolkit Query for making API requests.

Here's an explanation of the `useLazyGetCustomerNameListQuery` hook:

1. **Usage:**
   ```jsx
   const {
     data,       // The result of the query
     error,      // Any error that occurred during the query
     isLoading,  // Boolean indicating if the query is currently loading
     refetch,    // Function to manually trigger a refetch of the query
   } = useLazyGetCustomerNameListQuery(queryParams);
   ```

2. **Parameters:**
   - `queryParams`: An object containing parameters to be sent with the query. These parameters are used to customize the API request, and they depend on the specific requirements of your API endpoint.

3. **Result:**
   - `data`: The result of the query if it's successful.
   - `error`: Any error that occurred during the query.
   - `isLoading`: A boolean indicating if the query is currently loading.
   - `refetch`: A function that you can call to manually trigger a refetch of the query.

4. **Example:**
   ```jsx
   const { data, error, isLoading, refetch } = useLazyGetCustomerNameListQuery({
     // Query parameters specific to your API endpoint
     // ...
   });

   if (isLoading) {
     return <p>Loading...</p>;
   }

   if (error) {
     return <p>Error: {error.message}</p>;
   }

   // Use the data obtained from the query
   ```

This hook follows the convention of other `useQuery` hooks in Redux Toolkit Query. It abstracts away the complexity of handling API requests and provides a convenient way to interact with the results of those requests in your React components. The `refetch` function allows you to manually trigger a re-execution of the query when needed.
Alpha-Beta Pruning in AI
Tags: ai, beginners, tutorial, programming
Published: 2023-12-22 12:12:38

Alpha-Beta pruning is a fundamental optimization technique in the realm of artificial intelligence (AI) algorithms, often discussed in AI tutorials. Specifically applied to game-playing algorithms, Alpha-Beta pruning helps enhance the efficiency of search algorithms, such as the minimax algorithm, by reducing the number of nodes that need to be evaluated.

In the context of [AI tutorial](https://www.almabetter.com/bytes/tutorials/artificial-intelligence), understanding Alpha-Beta pruning is crucial for those delving into the intricacies of game-playing algorithms. The minimax algorithm is a common approach used in AI for decision-making in two-player games. However, as the search space grows exponentially with the depth of the game tree, it becomes computationally expensive to explore all possible moves.

This is where [Alpha-Beta pruning in AI](https://www.almabetter.com/bytes/tutorials/artificial-intelligence/alpha-beta-pruning) comes into play. It is a clever algorithmic optimization that allows the pruning of branches in the game tree that need not be explored further, significantly reducing the computational burden. The algorithm maintains two values, alpha and beta, representing the minimum score that the maximizing player is assured of and the maximum score that the minimizing player is assured of, respectively.

During the search process, if it is determined that a node's score is outside the range defined by alpha and beta, the algorithm can prune the remaining sub-tree under that node, as it won't affect the final decision. This pruning mechanism helps in discarding irrelevant portions of the game tree, resulting in a more efficient search.

In AI tutorials, students and enthusiasts learn how to implement Alpha-Beta pruning in various programming languages, typically using examples from board games like chess or tic-tac-toe. This practical application aids in grasping the nuances of the algorithm and its impact on optimizing the search process in game-playing scenarios.

In conclusion, Alpha-Beta pruning is a valuable concept in AI tutorials, providing learners with insights into optimizing decision-making algorithms, especially in the context of two-player games. Its ability to trim down the search space while maintaining the correctness of the solution makes it an essential tool in the toolkit of AI practitioners and game developers.
69. Not sticking to my plan (Day 67)
Published: 2023-12-22 12:43:34

I could've achieved more today with my assignment but then these came along:

Catching up on world news and social media (1 hour), A long fitness session (2 hours), grocery shopping (30 mins), new suitcase purchase (30 mins), travel back home (15 mins), dinner (45 mins), and finally my evening meditation (30 mins). Total time spent = about 6 hrs.

So, I managed to squeeze in only about 2 hours of work on my assignment. I focused primarily on my PowerPoint presentation - taking screenshots of my code and explaining it on the slides. I have another 2-3 slides pending and I am done with that!

Tomorrow, I MUST complete the following:

- The Presentation: 1 hour
- The Video Walk-through: 2 hours
- The QA test document: 1 hour
- Readme.md file cleanup: 1 hour
- 2 Test cases: 1 hour
- Final run-through of everything: 1 hour

That's 7 hours of work! That's my goal.
Visualize and Inspect Workflows Executions
Tags: workflows, google, cloud, orchestration
Published: 2023-12-22 12:32:36

When using a service like Google Cloud [Workflows](https://cloud.google.com/workflows/), in particular as your workflows get bigger, it can be difficult to understand what's going on under the hood. With multiple branches, step jumps, iterations, and also parallel branches and iterations, if your workflow fails during an execution, until now, you had to check the execution status, or go deep through the logs to find more details about the failed step.

I have good news for you! Workflows recently added some deeper introspection capability: you can now [view the history of execution steps](https://cloud.google.com/workflows/docs/debug-steps). From the Google Cloud console, you can see the lists of steps, and see the logical flow between them. The usual workflow visualisation will also highlight in green the successful steps, and in red the failed one. Of course, it is also possible to make a curl call to get the JSON of the [list of executed steps](https://cloud.google.com/workflows/docs/debug-steps#list-entries).

Let's have a look!

In the console, when you click on an execution, in the `summary` tab, you'll see not only the failed step, but also the nice workflow graph colored green and red:

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

That way, you know which path the execution followed, in a visual manner. But you can also see the actual list of steps executed, with more details, by clicking on the `steps` tab:

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

From this table, the filter will let you further refine  particular type of steps you'd like to investigate, or visualise the steps of a subworkflow only, etc.

This is a nice improvement to the developer experience, and for your ops team, to better understand what happens during your workflow executions! Feel free to read more about this new capabability in the documentation about [viewing the history of execution steps](https://cloud.google.com/workflows/docs/debug-steps).
How send transaction emails in Laravel using Brevo (ex Sendinblue)
Tags: laravel, brevo, php
Published: 2023-12-22 12:26:32

First, lets install Mailer driver:
```bash
"symfony/brevo-mailer": "^7.0"
```

Now lets configure our Mailer. First put this code inside `boot()` method in your `AppServiceProvider.php`:
```php
public function boot(): void
{
    //...

    $this->app['mail.manager']->extend('brevo', function ($config) {
        $configuration = $this->app->make('config');

        return (new BrevoTransportFactory())->create(
            Dsn::fromString($configuration->get('services.brevo.dsn'))
        );
    });
}
```

Here you can see `services.brevo.dsn` config. I created file `config/services` and there the following code:
```php
return [
    'brevo' => [
        'dsn' => env('MAILER_DSN'),
    ],
];
```

Now lets go to `config/mail.php` and setup our mailer:
```php
'mailers' => [
    // ...
    'brevo' => [
        'transport' => 'brevo',
    ],
]
```

Then we should create our Email:
```php
class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public readonly string $username
    ) {
    }

    public function build(): self
    {
        $this->withSymfonyMessage(function (Email $message) {
            $message->getHeaders()
                ->addHeader('templateId', 1)
                ->addParameterizedHeader('params', 'params', [
                    'customerName' => $this->username,
                ]);
        });

        return $this;
    }
}
```

Here we add headers with `templateId` and custom data. Brevo uses custom data to fill your variables inside your templates.

Feel free to ask any questions in comments 👇

Follow me on [X (prev Twitter)](https://twitter.com/iamkirillart)
IoT Architecture - A Detailed Guide
Tags: iot, tutorial
Published: 2023-12-22 12:16:42

IoT (Internet of Things) architecture is a crucial aspect of modern technological landscapes, and understanding it is highly relevant in the context of data science courses and Masters in Data Science programs. As the IoT ecosystem continues to expand, the architecture plays a pivotal role in enabling efficient data collection, processing, and analysis.

In a [data science course](https://www.almabetter.com/courses/full-stack-data-science) or a [Masters in Data Science](https://www.almabetter.com/degrees/masters-in-computer-science-data-science-ai) program, students often explore the intricate components of IoT architecture. This architecture is designed to facilitate seamless communication and interaction among a myriad of devices, sensors, and systems that constitute the IoT network. Here are key components of [IoT architecture](https://www.almabetter.com/bytes/articles/iot-architecture):

Sensors and Devices:

Devices equipped with sensors collect data from the physical world. These sensors could measure various parameters such as temperature, humidity, or motion.
Connectivity:

The connectivity layer involves the means by which devices communicate with each other and with central systems. This can include wired connections, wireless protocols like Wi-Fi or Bluetooth, and IoT-specific protocols.
Data Processing:

Once data is collected, it needs to be processed efficiently. Edge computing and fog computing are often part of IoT architectures, allowing for data processing closer to the source rather than relying solely on centralized cloud servers.
IoT Gateway:

Gateways act as intermediaries between IoT devices and the cloud. They aggregate data, perform initial processing, and ensure secure communication between devices and the central system.
Cloud Computing:

Cloud platforms play a crucial role in storing and processing massive amounts of IoT data. Data science courses often emphasize cloud-based analytics and machine learning techniques for extracting valuable insights from IoT-generated data.
Security:

Given the sensitivity of IoT data, security is a paramount concern. Encryption, authentication, and secure protocols are integral components of IoT architecture covered in both data science courses and Masters in Data Science programs.
Data Storage:

Data generated by IoT devices needs proper storage. This involves databases and data warehouses capable of handling large volumes of diverse data types.
Understanding IoT architecture is pertinent for individuals pursuing data science courses, especially those with a focus on IoT analytics. The integration of IoT data into the broader landscape of data science presents unique challenges and opportunities, making it a valuable area of study for those seeking mastery in data science. In Masters in Data Science programs, students often delve deeper into advanced topics such as real-time analytics, anomaly detection, and predictive modeling using IoT data, further solidifying their expertise in this evolving field.
Selenium Webdriver - how to bypass server's basic authentication popup
Tags: selenium, seleniumwebdriver, node, e2e
Published: 2023-12-22 12:09:28


Are you entering on E2E/Automated test world with selenium-webdriver and had faced this issue: 

> You need to access a page which has basic authentication popup, a secure server.

![Basic auth popup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/11hmppt4vwyl1yju8e5c.png)

Well research and found how to do this was a little harsh, so this is a quick guide for you to don't suffer like i did.

The secret is the `createCDPConnection`. With selenium-webdriver we need to get to the browser api and perform a register

```js

const { Builder, By } = require('selenium-webdriver');
const Chrome = require('selenium-webdriver/chrome');
const assert = require("assert");
const url = `https://my.server.com/`

describe('Server with basic auth', function () {

  before(async function () {
    driver = await new Builder().forBrowser('chrome').build();
  });

  beforeEach(async () => {
// this is what does the trick
    const connection = await driver.createCDPConnection('page');
    await driver.register("username", "password", connection);
// now you can go the url safety
    await driver.get(url);
  })


  it('Bypass the popup', async function () {
    const message = await driver.findElement(By.className("heading")).getText();
    assert.equal('Welcome!', message);
  })
  after(function () {
   await driver.quit()
  })
})

```
Techies, It's Time to Talk About Work-Life Balance: Take the Survey!
Tags: discuss
Published: 2023-12-22 12:03:20

**Introduction**

Are you a techie who often finds yourself working late into the night, juggling deadlines, and pushing through stress? You're not alone. The tech industry is notorious for its demanding work hours, but at what cost to our health and well-being?

**The Stark Reality**

A startling study by WHO in 2016 revealed the harsh consequences of prolonged work hours: **398,000 people died from stroke** and **347,000 from heart disease**, all linked to **working 55 hours or more per week.**

**Onsurity & KCCI: Understanding Your Challenges**

_Onsurity_, India's leading employee healthcare benefits platform, in partnership with the _Knowledge Chamber of Commerce and Industry_ (KCCI), is stepping up to address this critical issue. We aim to understand the unique challenges and coping mechanisms of tech professionals like you.

**The Survey: Your Voice Matters**

We are inviting you to participate in a brief survey, taking only 3-5 minutes of your time. Your insights are invaluable in helping us grasp how the imbalance between work and life is impacting the well-being of techies.

**Why Should You Participate?**

- **Voice Your Experience**: Share your personal challenges and experiences with work-life balance.
- **Drive Change**: Your input can help shape policies and practices that promote healthier work environments.
- **Community Support**: Encourage your fellow techies to participate, fostering a community-driven approach to this issue.

**How to Participate**

Simply [click on the survey link](https://forms.office.com/pages/responsepage.aspx?id=nNUjj-DjbUu6h3mc5yJrIs9MH6O8c2JArpjAyFsNdV1UNUQ1MFMxQ1JEUFNYRjE5OTBITVVQOUk5Ni4u) and share your thoughts. It's quick, easy, and can make a significant difference.

**Conclusion**

Your participation in this survey is a step toward understanding and improving the work-life balance in the tech industry. Let's work together to ensure that our careers do not compromise our health and well-being.

**Share and Spread the Word!**

After taking the survey, please share it with your techie friends and colleagues. Together, we can bring about meaningful change.