teleren/devto huggingface dataset:
How to use @Lazy annotation in case of Circular Dependency
Tags: spring
Published: 2023-12-18 15:45:42

Using the `@Lazy` annotation in Spring is a common technique to resolve circular dependencies. Circular dependencies occur when two beans are dependent on each other, leading to a situation where neither bean can be instantiated without the other already existing.

To understand how `@Lazy` helps, let's first look at what a circular dependency might look like and then how to resolve it with `@Lazy`.

### Circular Dependency Example

Suppose you have two classes, `ClassA` and `ClassB`, and they depend on each other.

```java
@Component
public class ClassA {
    private final ClassB classB;

    @Autowired
    public ClassA(ClassB classB) {
        this.classB = classB;
    }
}

@Component
public class ClassB {
    private final ClassA classA;

    @Autowired
    public ClassB(ClassA classA) {
        this.classA = classA;
    }
}
```

In this scenario, Spring cannot instantiate `ClassA` without first instantiating `ClassB` and vice versa, leading to a circular dependency problem.

### Resolving with `@Lazy`

You can resolve this by using the `@Lazy` annotation. `@Lazy` defers the initialization of a bean until it is actually needed. This can break the circular dependency as one of the beans will not be fully initialized (i.e., its dependencies won't be injected) until it's first used.

```java
@Component
public class ClassA {
    private final ClassB classB;

    @Autowired
    public ClassA(@Lazy ClassB classB) {
        this.classB = classB;
    }
}

@Component
public class ClassB {
    private final ClassA classA;

    @Autowired
    public ClassB(ClassA classA) {
        this.classA = classA;
    }
}
```

In this modified example, `ClassA`'s dependency on `ClassB` is marked as `@Lazy`. When Spring creates an instance of `ClassA`, it injects a lazy proxy for `ClassB` instead of an actual instance of `ClassB`. The actual `ClassB` instance is not created until a method on the `ClassB` proxy is called. This delay breaks the circular dependency chain and allows Spring to successfully create both beans.

### Things to Note

1. **Design Smell**: Circular dependencies often indicate a potential flaw in the design of your application. It's generally a good idea to revisit your design and consider refactoring to eliminate circular dependencies altogether.

2. **Proxy Behavior**: With `@Lazy`, Spring creates a proxy to inject as the dependency. This means that the actual bean will be created when the proxy is first accessed. Be aware of this lazy behavior as it might have implications for your application logic.

3. **Alternative Solutions**: Other than using `@Lazy`, you can also resolve circular dependencies by using setter injection or method injection, which allows one of the beans to be constructed without needing the other to be fully initialized.

Using `@Lazy` is a quick workaround for circular dependencies, but it's important to consider whether a redesign of the application's components and their relationships might be a more sustainable solution.
What is GIGO?
Tags: career, cloud, startup, developer
Published: 2023-12-18 15:39:53


GIGO Dev is an online social programming platform containing a vast array of projects for programmers of all levels to compete and complete. A gamified learning experience, if you feel like you're in a weird tech casino fever dream, you're in the right place. GIGO was designed with the average video game experience in mind, users can earn XP, level up and increase rank - the experience is supposed to be equally fun as it is useful.

We support catalogues of projects for majority of the common industry used languages including but not limited to: Javascript, Python, Go, C++, C#, Rust, Kotlin, Typescript, and so on.

The platform is free to use, though there are some benefits that come with a pro membership. Pro users can run 3 concurrent DevSpaces, each of which have 6 CPU cores, 8GB of memory (RAM), and 50GB of disk space. Immense value stems from your own personal guide, Code teacher, the Magic programming tutor. Code teacher understands the code base of the GIGO Dev platform itself as well as each individual project, allowing users to ask direct questions related to their task at hand from inside the development environment. 

All programmers know Google search is their best friend whether they admit it or not, having a teacher built into the IDE to help guide you thru the knowledge gaps leads to an enriching educational experience.

When a user decides they want to try a project in GIGO Dev, with the click of a button we spin up a fully configured in browser IDE **VScode**, allowing them to execute code almost immediately with low-to-no setup.

If you fit into one of the following categories you'll likely resonate with GIGO's mission and function:

- **A)** You are a brand-new programmer, fresh out of online guided courses and looking for ideas/guidance for your very first post-course project.

- **B)** You are an intermediate programmer with some reasonable accomplishments under your belt, you are gaining steam in your knowledge base and like what you do, and would be happy to find a place where you can express your skillset in a fun and friendly, yet competitive environment.

- **C)** You are an expert programmer with decades of experience looking to showcase your vast expertise, maybe giving back to the community somewhere along the line by creating projects/challenges for the younger community to bang their heads on their monitor at.


Wherever you find yourself in your programming journey, there is a spot for you at GIGO Dev to create, learn, and share experiences with like-minded individuals.

Discord: https://discord.gg/MdKmqBzRqX
Twitter: https://twitter.com/gigo_dev
Reddit: https://www.reddit.com/r/gigodev/
GitHub repository: https://github.com/Gage-Technologies/gigo.dev

Get started on your first project at [gigo.dev](https://gigo.dev)
Sharkio to the Rescue: Streamline Your API Development
Published: 2023-12-18 15:32:50

Hello beloved members of Maakaf!

Debugging your backend? debugging microservices?
Searching for hours through logs?
Spending hours on building mocks?
Spending hours on building integration tests?
Manually creating requests in Postman for hours?

I'm the co-founder of Sharkio 🦈 😁 
An open-source project that is a long-standing member of Maakaf.
We are now booking short 30-minute demo calls. And would love to hear all about your daily struggles with API development and third-party API integrations.
We provide our specialized knowledge to address your problems.

No more! Sharkio is here to save you and your team 😇 
Book a call with us now:
Send me a DM and we can discuss
Book a meeting using Calendly: [Calendly: 30 min call](https://calendly.com/sharkio-dev/sharkio-demo?month=2023-12)
Setting up Express Backend API to use Docker
Tags: docker, kubernetes, express, api
Published: 2023-12-18 15:31:56

To set up a Dockerfile for your Clarek CRM backend using Express.js with port 8000, follow the steps below:

1. **Create a Dockerfile:**

Create a file named `Dockerfile` in the root directory of your Clarek CRM backend project.

```Dockerfile
# Use an official Node.js runtime as a base image
FROM node:20

# Set the working directory in the container
WORKDIR /usr/src/app

# Copy package.json and package-lock.json to the container
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the rest of the application code to the container
COPY . .

# Expose port 8000
EXPOSE 8000

# Define the command to run your application
CMD ["node", "app.js"]
```

Noted that `WORKDIR /usr/src/app`  becomes `WORKDIR /clarek-crm-backend`
2. **Build the Docker Image:**

Open a terminal and navigate to the directory containing your Dockerfile and application code. Run the following command to build the Docker image:

```bash
docker build -t clarek-crm-backend .
```

This command will build the Docker image using the instructions in the Dockerfile and tag it with the name `clarek-crm-backend`.

3. **Run the Docker Container:**

After building the image, you can run the Docker container using the following command:

```bash
docker run -p 8000:8000 -d clarek-crm-backend
```

This command maps port 8000 on your host machine to port 8000 in the Docker container and runs the container in detached mode (`-d`).

Now, your Clarek CRM backend should be accessible at `http://localhost:8000`.

Note: Make sure your Express.js application is configured to listen on port 8000. You can set the port in your Express.js application code or through a configuration file.

Remember to replace any placeholder names or values with your actual project details. Adjust the Node.js version in the `FROM` statement based on your project's compatibility.
SQL - Handle NULL Values Safely in Queries
Tags: sql, programming, beginners, tutorial
Published: 2023-12-18 15:30:00

When working with SQL queries, be cautious when dealing with NULL values. Use SQL functions like IS NULL, IS NOT NULL, COALESCE, and CASE statements to handle NULL values appropriately, preventing unexpected results or errors in your queries.

Suppose you have a table called "employees" with a "birthdate" column that may contain NULL values, and you want to retrieve the age of each employee.

Dealing with NULL Values:
```sql
SELECT employee_id, 
       CASE
           WHEN birthdate IS NULL THEN 'N/A'
           ELSE DATE_DIFF(CURRENT_DATE(), birthdate) / 365
       END AS age
FROM employees;
```

In this example, the CASE statement checks if the "birthdate" is NULL, and if so, it returns 'N/A.' Otherwise, it calculates the employee's age using DATE_DIFF. This approach ensures that NULL values are handled gracefully, preventing potential errors or unexpected results in the age calculation.

Handling NULL values properly in your SQL queries is essential for accurate data processing and reporting. Use SQL's built-in functions and conditional statements to tailor your queries to the specific handling requirements of your data.
programming language
Tags: webdev, programming, beginners, codenewbie
Published: 2023-12-18 15:29:37

a computers native tongue is binary.a language made out of two numbers, one and zero.For humans it is hard to comprehend binary language that is why we need a programming language.
programming languages are like bridges, allowing us to translate our thoughts into structures computer can understand using a specific human readable language.
programming languages fall into two classifications , low level and high level, low level languages are closer to binary language , and they are faster compared to high level languages.
high level languages are closer to how humans communicate, using words that are closer to human language.their downside is that they take longer ,compared to low level languages, to be translated to machine code for computers to understand.
As computers are getting more powerful the difference in runtime between low-level and high level-language is often only milliseconds.
handleZodError create
Tags: webdev, programming, beginners, tutorial
Published: 2023-12-18 15:20:12

```ts
//=> src/app/errors/handleZodError.ts
import { ZodError, ZodIssue } from 'zod';
import { TErrorSources } from '../interface/error';

const handleZodError = (err: ZodError) => {
  const errorSources: TErrorSources = err.issues.map((issue: ZodIssue) => {
    return {
      path: issue?.path[issue.path.length - 1],
      message: issue.message,
    };
  });

  const statusCode = 400;

  return {
    statusCode,
    message: 'Validation Error',
    errorSources,
  };
};

export default handleZodError;

```

```ts
//=> src/app/middlewares/globalErrorhandeler.ts
export const globalErrorHandeler: ErrorRequestHandler = (
  err,
  req,
  res,
  next,
) => {
  let statusCode = err.statusCode || 500;
  let message = err.message || 'Something went wrong';

  let errorSources: TErrorSources = [
    {
      path: '',
      message: 'something went wrong',
    },
  ];

  if (err instanceof ZodError) {
    const simpliedError = handleZodError(err);
    statusCode = simpliedError?.statusCode;
    message = simpliedError?.message;
    errorSources = simpliedError?.errorSources;
  }

  return res.status(statusCode).json({
    success: false,
    message,
    errorSources,
    stack: config.NODE_ENV === 'development' ? err?.stack : null,
  });
};
```


```ts
import mongoose from 'mongoose';
import { TErrorSources } from '../interface/error';

const handleValidationError = (err: mongoose.Error.ValidationError) => {
  const errorSources: TErrorSources = Object.values(err.errors).map(
    (val: mongoose.Error.ValidatorError | mongoose.Error.CastError) => {
      return {
        path: val?.path,
        message: val?.message,
      };
    },
  );

  const statusCode = 400;

  return {
    statusCode,
    message: 'Validation Error',
    errorSources,
  };
};
export default handleValidationError;

```
What are your goals for the week of Dec 18?
Tags: motivation, discuss
Published: 2023-12-18 15:05:00

## What are your goals for this week? 

- Are you building anything you want to talk about? 
- What will be a good result by week's end?
- What events are happening any week? 
  * in person or virtual?
- Any goals for the end of the year?

The schools are half day every day till Wednesday. Then off till January. That means networking in am, pick up my son, then projects or something in the afternoon. 

### Last Week's Goals
 
- [:white_check_mark:] Continue Job Search. 
   * I'll apply and network. 
   * Finish editing resumes, linkedIn, and my personal site.
- [:white_check_mark:] Blog. 
- Project work
- [:white_check_mark:] CSS Sweater build and blog.
- Events
  * [:x:] Thursday Virtual Coffee. Nope was busy blogging. Checked time. Saw I had time kept writing, next time I looked twenty minutes had passed and I knew I missed the intros. Decided to finish my blog. 
  * [:white_check_mark:] UnGhosted Live on Wednesday. 
- [:white_check_mark:]Run a weekly Slack thread similar to this post. 
- [:white_check_mark:] Build LEGO might led to CSS blog. 
- [:x:] Finish the pictures from the end of October. 
- [:white_check_mark:] Moved my portfolio site earlier this year. The old site had a WP add on blog that didn't move but is still up since I paid for the year. 

Last week's blog.

{% embed https://dev.to/jarvisscript/ugly-sweater-css-spider-man-2ke2 %}

### This Week's Goals


- Continue Job Search. 
   * I'll apply and network. (very light on it this week)
- Project work
- CSS Sweater build and blog.
- Events
  * Thursday Virtual Coffee.
  * I don't know of thing this week. 
- Run a weekly Slack thread similar to this post. 
- Build LEGO might led to CSS blog. 
- Finish the pictures from the end of October.
- Finish Christmas shopping. Wrap up presents.



### Your Goals for the week

Your turn what do you plan to do this week? 

- Are you building anything you want to talk about? 
- What will be a good result by week's end?
- What events are happening any week? 
  * in person or virtual?
- Any goals for the end of the year?


```html
-$JarvisScript git push
```
Why 'Easy Money' Isn't So Easy: The Truth About Passive Income
Tags: blog, income, learning
Published: 2023-12-18 15:03:09

We've all heard about the dream of making money without breaking a sweat. Passive income promises just that – earning cash effortlessly. But before we get too excited, let's dig into the simple truth and find out if it's as easy as it sounds.

**The idea of making money while you sleep sounds amazing, right?** But the catch is, the road to passive income often needs a lot of work upfront. Whether it's starting a blog or investing in something, you've got to put in the effort first.

**Active nature of passive income:**
Passive income, surprisingly, can be quite active initially. Rather than an instant reward, it involves putting in work upfront before the income becomes truly passive. It's not about avoiding work altogether but about delaying when you get paid for it.

**Risks:**
Passive income isn't risk-free. Investments can go up and down, and things change. For example, if you own a rental property, it needs care and attention. Stock markets can be unpredictable, so thinking it's all smooth sailing is a bit of a stretch.

**Keep an eye open:**
Even so-called 'passive' stuff needs looking after. Renting out a place? You've got to manage it. Running an online business? Regular updates and new stuff are a must. It's not like setting it up and forgetting about it – you need to keep an eye on things.

**NO days Off:**
Thinking you can set up a passive income and then go on vacation forever? That's not how it works. Successful folks will tell you that it's not a 'set it and forget it' deal. There's ongoing work to make sure things keep going well.

**Need Active Management:**
One major misconception is the idea that something can generate income without ongoing management. In truth, most passive income sources require continuous management to keep the money flowing.

The claim that passive income is a scam stems from the fact that it often requires a substantial upfront investment, ongoing management, or both. Remember, there's no such thing as a free lunch.
Beginner's TypeScript #1
Tags: programming, typescript, beginners, tutorial
Published: 2023-12-18 15:00:00

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

⭐ **The Implicit 'Any' Type Error** ⭐

We have this **addTwoNumbers** function:

```ts
export const addTwoNumbers = (a, b) => {
  return a + b
}
```

This function takes in a and b and adds them together.

It looks like perfectly valid JavaScript. But TypeScript is not happy.

We get the following errors along with the line of code where they happen:

```bash
Parameter 'a' implicitly has an 'any' type.
Parameter 'b' implicitly has an 'any' type.
```

This error occurs because TypeScript does not have enough information to infer a type, so it defaults to **any**.

👉 **Solution:**

The solution is to add type annotations to the function's arguments.

In this case, both a and b should be typed as **number**:

```ts
export const addTwoNumbers = (a: number, b: number) => {
  return a + b
}
```

✍️ **Summary:**

[TypeScript](https://www.typescriptlang.org/) relies on type annotations to understand the contracts the function must meet. Type annotations are critical to understanding TypeScript.

**Whenever you create a function, we must always specify the types of each argument!**

I recommend turning on [strict mode](https://www.typescriptlang.org/tsconfig#strict) for all TypeScript projects.

When strict mode is enabled, we will get **the implicitly has 'any' type** error whenever you leave type annotations out.

---

I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- **Medium:** https://medium.com/@nhannguyendevjs/
- **Dev**: https://dev.to/nhannguyendevjs/
- **Hashnode**: [https://nhannguyen.hashnode.dev](https://nhannguyen.hashnode.dev/)/
- **Linkedin:** https://www.linkedin.com/in/nhannguyendevjs/
- **X (formerly Twitter)**: https://twitter.com/nhannguyendevjs/
@click to a method in Nuxt using mapbox in a popup
Tags: vue
Published: 2023-12-18 14:58:44

I am using MapBox in my NUXT 3 project. In my code, I have 2 popups. I am trying to call a method **openDrawer** to log something to the console, this doesn't seem to be working?! please help

```
<script setup>
import { ref, onMounted, reactive } from 'vue';
import mapboxgl from 'mapbox-gl';

const accessToken = ref("");
const map = ref(null);
const drawer = ref(false);
const markers = reactive({}); // Reactive object to store marker information

onMounted(() => {
  createMap();
  addMarkers();
});

const createMap = () => {
  accessToken.value = "xxxxxxxxxx";
  mapboxgl.accessToken = accessToken.value;
  map.value = new mapboxgl.Map({
    container: "map",
    style: "mapbox://styles/mapbox/light-v11",
    zoom: 11,
    center: [107.61861, -6.90389],
  });
}

const addMarkers = () => {
  const markerData = [
    { id: 1, lngLat: [107.61861, -6.90389], popupContent: 'Marker 1' },
    { id: 2, lngLat: [107.62, -6.9], popupContent: 'Marker 2' },
    // Add more marker data as needed
  ];

  markerData.forEach(data => {
    const { id, lngLat, popupContent } = data;

    // Create a marker
    const marker = new mapboxgl.Marker()
      .setLngLat(lngLat)
      .addTo(map.value);

    // Create a popup for each marker
    const popup = new mapboxgl.Popup({ offset: 25 })
      .setHTML(`
        <h3>${popupContent}</h3>
        <p>This is a popup.</p>
        <button @click="openDrawer(id)">Click me!</button>
      `);

    // Add a popup to the marker
    marker.setPopup(popup);

    // Store marker information in the reactive object
    markers[id] = { marker, lngLat, popupContent };
  });
}

const openDrawer = (markerId) => {
  // Use markers[markerId] to access information about the clicked marker
  const clickedMarker = markers[markerId];
  drawer.value = !drawer.value;
  console.log('Clicked Marker Information:', clickedMarker);
}
</script>
```
Remote Work Trends
Published: 2023-12-18 14:45:57

In 2023, 65% of companies that had established remote work processes plan to transition to a hybrid model, combining both remote and office work. Why has such a trend emerged?

First and foremost, the hybrid work format allows companies to save costs on maintaining office spaces and related expenses. Employees, on the other hand, gain more autonomy, save commuting time, and can independently manage their workdays.

Accenture provides data indicating that 83% of professionals prefer the hybrid employment model. Furthermore, almost half of the respondents are willing to accept a 5% reduction in salary if the employer offers remote or hybrid work.

Although most professionals report that their productivity doesn't decline with remote work, employers still value maintaining control mechanisms. Thus, the hybrid work format becomes a kind of compromise where both employees and businesses satisfy their demands in the work process.