teleren/devto huggingface dataset:
Solved: Tailwind properties missing in production
Tags: tailwindcss, javascript, webdev, react
Published: 2024-03-03 03:18:27

So, one fine (Monday) morning, I was fully committed to optimise my portfolio website - [https://utkarsh-tiwari-portfolio-react.netlify.app/](https://utkarsh-tiwari-portfolio-react.netlify.app/). Built using React and Tailwind CSS, everything was coming out great.

When I deployed it on **gh-pages**, something broke! The background colour behind the images in the **skills section** was just _transparent_!
But I had properly given different colours like _bg-teal-100_, _bg-amber-300_, _bg-green-100_, _bg-emerald-800_, _bg-yellow-800_, etc.

I checked the localhost 10 times, it worked on my machine!

![It works on my machine meme - https://i.pinimg.com/736x/71/ff/d4/71ffd47d032be54a1fad877bded70868.jpg](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kityrgimwzisaplspadz.png)
 

## The problem exactly - 

**Localhost**:
![Localhost - bg colours injected properly](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtheshml8kuhmw11wiwn.png)

**The not-so Localhost a.k.a gh-pages**:
![Production - bg colours are transparent](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oe33yhfynrncdqycv3vi.png)
 
## The culprit = 

Turns out that while I was trying to be too smart for my own good and over-optimising the code, I dynamically injected the bg-colors from the skills.js file.

Snapshot of _skillsData.js_ file - 

```js
export const skillsData = [
  {
    id: 1,
    img: "/images/html-css-logo.png",
    alt: "html-css-logo",
    name: "HTML & CSS",
    level: "Proficient",
    bgColor: "teal-800",
  },
]
```

Snapshot of _skills.jsx_ file -

```js
<li className="col-span-1 flex shadow-sm rounded-md" key={skill.id}>
    <div className={`bg-${skill.bgColor} text-sm font-medium justify-center w-16`}>
...
...
...
    </div>
</li>
```

Do you see the **bgColor** property? That's being dynamically inserted!

And when we build for production, Tailwind purges all the unused css to reduce the overhead and only adds the classes which are actually being used. 

So, the dynamic values (which are basically completing the property names) are not exactly "in-use" when purge css runs. Hence they are removed.

(If you did not understand what I meant - _"The exact property name is **bg-teal-500**, but since the code is split into two parts, it looks like the value is just **bg-**"_)

**Pro** - File size is reduced and overall it will be faster.
**Con** - Dynamically injected values are not compiled and hence are lost in production.
**Result** - Transparent background 🥲

PS: I've a new site on [utk09.com](https://utk09.com)
Using LangChain Expression Language (LCEL) for prompts and retrieval
Tags: ai, python, tutorial, learning
Published: 2024-03-03 03:16:32

In my previous post [Use case for RAG and LLM](https://dev.to/jkyamog/use-case-for-rag-and-llm-4pih) my sample code only used basic string manipulation of the prompt.  On this post I will show how to use [LangChain Expression Language (LCEL)](https://python.langchain.com/docs/expression_language/get_started)


Instead of string manipulation, LCEL offers a more effective alternative.  Here are the step by step conversion: 

- Instead of using python string interpolation: 
```python
prompt = f"I need help on {context}"
``` 
use the same string without interpolation and a chat prompt template
```python
prompt = ChatPromptTemplate.from_template("I need help on {context}")
```
- We can directly use the vector store as a retriever within a sub-chain, simplifying the search and integration process.
```python
retriever = vector_store.as_retriever(search_type='similarity')
context_subchain = itemgetter('user_query') | retriever
```
- Finally combine the prompts, retriever and output processing in a chain.  RunnablePassthrough is used for the user_query  is supplied when the chain is invoked.  itemgetter is use for llm_personality which will be substituted from a disctionary passed on the chain's invocation.
```python
chain = (
    {
        'context': context_subchain, 
        'user_query': RunnablePassthrough(), 
        'llm_personality': itemgetter('llm_personality')
    } 
    | prompt
    | model
    | StrOutputParser()
)
```

Here is as sample code is written using LCEL
```python
template_system = """

Use the following information to answer the user's query:

{context}
"""

template_user = """
User's query:

{user_query}
"""

prompt = ChatPromptTemplate.from_messages([
        SystemMessagePromptTemplate.from_template(template_system),
        HumanMessagePromptTemplate.from_template(template_user)
    ])

retriever = vector_store.as_retriever(search_type='similarity')
context_subchain = itemgetter('user_query') | retriever

chain = (
    {
        'context': context_subchain, 
        'user_query': RunnablePassthrough(), 
        'llm_personality': itemgetter('llm_personality')
    } 
    | prompt
    | model
    | StrOutputParser()
)

response = chain.invoke({**{'user_query': user_query}, **prompt_placeholders})
```

You can see a more complete [commit diff](https://github.com/jkyamog/ml-experiments/commit/3d5494e5364b3c58d4cacdcd214fe797df93b4ad?diff=split&w=1) from old string manipulation to LCEL
What innovative coding techniques have you employed to solve a particularly complex problem in your development projects?
Published: 2024-03-03 02:31:01

In one of my recent development projects, I encountered a particularly complex problem related to optimizing the performance of a real-time data processing system. To tackle this challenge, I employed an innovative approach by leveraging a combination of advanced algorithms and data structures. By carefully analyzing the problem requirements, I identified opportunities to implement custom data structures tailored to the specific needs of the [application](https://reminimod.com/). Additionally, I integrated highly optimized algorithms to efficiently process large volumes of data in real-time. This approach not only addressed the performance bottlenecks but also improved the overall scalability and reliability of the system. Collaborating closely with team members, we were able to refactor and optimize the codebase to achieve significant performance gains. Overall, this experience reinforced the importance of staying abreast of the latest developments in computer science and continuously seeking out innovative solutions to complex problems in software development.
A importância do Granted ao trabalhar com AWS e múltiplas contas
Published: 2024-03-03 02:27:24

## Introdução

Ao trabalhar com a AWS, gerenciar múltiplas contas pode ser um desafio. É necessário alternar entre contas, lembrar de credenciais e gerenciar permissões para cada uma delas. O Granted facilita esse processo, tornando o gerenciamento de várias contas AWS mais eficiente e seguro.

![AWS SSO LOGIN](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bfb3fj4d2y796asvq4mt.png)


## Benefícios do Granted:

-     Acesso rápido e fácil: O Granted permite que você acesse todas as suas contas AWS com um único comando, sem precisar lembrar de credenciais ou alternar entre consoles.
-     Gerenciamento de permissões simplificado: O Granted facilita o gerenciamento de permissões para suas contas AWS, permitindo que você defina e controle o acesso de forma granular.
-     Segurança aprimorada: O Granted usa autenticação multifator e criptografia para proteger suas contas AWS contra acesso não autorizado.
-     Melhoria na produtividade: O Granted pode aumentar sua produtividade ao automatizar tarefas de gerenciamento de contas, como alternar entre contas e gerenciar permissões.


## Exemplo de uso:

Suponha que você tenha três contas AWS: uma para desenvolvimento, uma para teste e uma para produção. Com o Granted, você pode:

-     Acessar qualquer uma das suas contas com um único comando.
-     Definir permissões diferentes para cada conta, controlando quem tem acesso a quais recursos.
-     Automatizar a tarefa de alternar entre as contas, economizando tempo e esforço.

## Conclusão:

O Granted é uma ferramenta essencial para qualquer pessoa que trabalhe com a AWS e gerencie múltiplas contas. Ele facilita o acesso, o gerenciamento de permissões e a segurança de suas contas, além de aumentar sua produtividade.

Para mais informações:


- Artigo detalhado sobre o Granted: [https://devopsmind.com.br/aws-pt-br/granted-aws-sso-login-multiplas-contas/]
-     Site do Granted: Site Granted: [https://www.granted.dev/]
Some Git Branch Stuff
Published: 2024-02-26 09:27:59

This is pretty minor, but one thing that’s always bugged me about Git is that I run git branch a lot to view what branches I have, but they’re in the dumbest possible order (alphabetic) and there are a million of them after a while.

At some point I started naming my branches in a way to partially cope with this. Every branch would be something like sc-0831-my-thing meaning that the branch topic was “my thing”, it was created on August 31st and the sc are my initials so I can group them by whose branch. It’s a lot of stupid metadata to try to cram into a branch name just because of how it’s listed.

However, now we can ask Git to do two things that help with this. We can ask it to sort by objectsize, authordate, committerdate, creatordate, or taggerdate with the --sort option and we can set it as a default with the branch.sort config setting.

So for example, if I want to sort by last commit date descending, I can run:

`$ git config --global branch.sort -committerdate`

And now the default will show the branch that I last committed to at the top.

> 💡 Important note: the -committerdate has a leading - but not a double dash. It’s just a negative. I’ve seen people mess this up and then things break.

However, now if I have a bunch of branches, that will scroll off the screen. Sad. But now Git also has a way to take a list of branches and try to split it into columns to make better use of the screen real estate. You can do this either with the new `--column` option, or with the `column.ui` setting.

Check it out:

![Git column example1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ntokusguk8vnamm06q9m.png)

As another sort of funny thing, in order to help with this, Git implemented it’s own list to column terminal command that is sort of completely independent of anything else in Git and is it’s own command called `git column`.


![Git column example2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o8e336jd3v4q3riq0bwe.png)

Just in case there is anything else you need to convert into columns that isn’t Git related.
Ajna Events & Rentals
Tags: audiovisual, rental, bangalore, audiovisualhire
Published: 2024-03-03 01:15:24

Established in 2013, [AJNA Events & Rentals](https://g.page/r/CXMma9HeKHEJEBM/review) is your one-stop solution for transforming any event into a memorable occasion. From renting projectors, televisions & speakers to led walls and karaoke systems, we provide a comprehensive selection of audio-visual & party equipment rentals in bengaluru city. Whether you're planning a corporate conference or a vibrant party, or an immersive video conferencing experience, our team of experts helps you choose the perfect setup to captivate your audience & leave a lasting impression.

Our services:

projector rental in bangalore
projector screen rental in bangalore
television rental in bangalore
speakers and mics rental in bangalore
pa systems rental
led wall rental in bangalore
video conference setup
Verificando se item já existe em uma lista de objetos em JAVASCRIPT
Tags: javascript, programming, braziliandevs
Published: 2024-03-03 01:15:20

obs: Para ver minha solução final vá ao fim do texto.

Olá, recentemente eu estava desenvolvendo um app em react-native e tive a necessidade da seguinte validação: verificar se item já existe em uma lista de objetos.

A principio você pode tentar simplesmente usar usar o método includes na lista

```
const newObject = {"name": "matematica",
 "startHour": "13:30",
 "endHour": "17:30"}


listObjects.includes(newObject)
```

Porém dessa forma não vai funcionar devido a cada instancia de objeto ser uma instancia diferente, o que fará com que sempre retorne false.

Minha segunda solução foi:

```
let objectIsEqual = false
listSubject.forEach(item => {
  objectIsEqual = (item['name'] == subjectObject['name'] &&
            item['startHour'] == subjectObject['startHour'] &&
            item['endHour'] == subjectObject['endHour'])
            
  if(objectIsEqual){
    setError("disciplina já existe")
    return
  }
});
if(objectIsEqual) return
```

Porém essa solução não funciona pois no javascript o forEach não é interrompido pelo return, o que faz com que isso só compare com o ultimo objeto da lista.

obs: Alias o Lucas Montano do canal Lucas Montano tem um vídeo interessante sobre isso: https://youtu.be/yLmoMBMDE4o?si=G2Q97C300NhnIqJZ

Então talvez uma solução seja usar o for simples:


```
const subjectObject = {
            "name":valueSubject,
            "startHour": startHour,
            "endHour": endHour
        }

for (let index = 0; index < listSubject.length; index++) {
            const item = listSubject[index]
            const objectIsEqual = (item['name'] == subjectObject['name'] &&
            item['startHour'] == subjectObject['startHour'] &&
            item['endHour'] == subjectObject['endHour'])
            
             if(objectIsEqual){
                setError("disciplina já existe")
                return
            }
        }
```

Essa solução já funciona para essa validação porém pensando em diminuir o número de linhas de códigos e deixar essa solução mais concisa a solução final pode ser usando o método some:

obs: Para entender melhor como funciona o método some acesse: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/some

```
const subjectObject = {
            "name":valueSubject,
            "startHour": startHour,
            "endHour": endHour
        }
const objectIsEqual = listSubject.some(object => 
object['name'] == subjectObject['name'] &&
object['startHour'] == subjectObject['startHour'] &&
object['endHour'] == subjectObject['endHour'])

if(objectIsEqual){
      setError("disciplina já existe")
      return
}
```

O resultado dessa validação no app:


![Interface de app com inputs: nome da disciplina, hora de inicio e hora de fim. Botão de adicionar e abaixo do botão um erro dizendo "Disciplina já existe", abaixo uma lista de disciplinas](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/38nwjz171oj5rl9zfki2.png)

Ao tentar adicionar o mesmo item é exibido a mensagem de erro e o item não é adicionado.
Understanding the Basics of Docker Containers
Tags: docker, devops, kubernetes, linux
Published: 2024-03-03 00:31:11

## Introduction

In the world of software development, efficiency and accessibility are crucial factors. Docker containers have emerged as a popular solution in this regard. They allow developers to package their applications along with all necessary components and dependencies into a portable container. These containers can then be easily deployed and run on any operating system, making the development process seamless and efficient. In this article, we will delve into the basics of Docker containers and their advantages, disadvantages, and features.

## Advantages of Docker Containers

1. **Portability:** Docker containers are highly portable, making it easier for developers to run their applications on any platform without worrying about compatibility issues.

2. **Isolation:** Each application runs in its own container, providing a secure and isolated environment. This allows multiple applications to run on a single machine without interfering with each other.

3. **Resource Efficiency:** Docker containers are lightweight and consume fewer resources, making them ideal for efficient use of hardware resources.

## Disadvantages of Docker Containers

1. **Learning Curve:** Docker containers have a relatively steep learning curve, and it may take some time for developers to grasp the concepts and effectively use them.

2. **Security Concerns:** As containers share the operating system's kernel, a compromised container can potentially affect all other containers on the same machine.

## Features of Docker Containers

1. **Images:** Docker containers use images as a template to create and run containers. These images contain all the necessary components and dependencies, making it easier to replicate the same environment across different machines.

    ```bash
    # Pulling a Docker image from Docker Hub
    docker pull ubuntu:latest
    ```

2. **Orchestration:** Docker provides orchestration tools like Docker Swarm or Kubernetes to manage, scale, and deploy multiple containers.

    ```bash
    # Running a simple Docker Swarm service
    docker service create --replicas 3 -p 80:80 nginx
    ```

3. **Microservices:** Docker containers are perfect for deploying microservices, as they are lightweight and can be easily scaled up or down based on demand.

    ```bash
    # Starting a microservice in a Docker container
    docker run -d -p 5000:5000 my-microservice
    ```

## Conclusion

Docker containers have revolutionized the way software is developed and deployed by providing numerous advantages such as portability, isolation, and resource efficiency. However, they also have some drawbacks, including a steep learning curve and potential security concerns. Nevertheless, Docker containers remain a popular and powerful tool in the world of software development, and understanding the basics of these containers is crucial for any software developer.
Understanding the map Function in Python
Tags: python, beginners, programming
Published: 2024-03-02 23:30:24

# Introduction

The `map()` function in Python is a powerful tool for transforming data. It allows you to apply a function to each item in an iterable, such as a list, and returns an iterator that yields the results. This chapter will delve into the intricacies of the `map()` function, exploring its syntax, common use cases, and practical examples.

# Topics

- Syntax of the `map()` function
- Using `map()` with built-in functions
- Applying `map()` with lambda functions
- Combining `map()` with multiple iterables
- Handling different data types with `map()`

# Examples

## Syntax of the `map()` function

The syntax of the `map()` function is straightforward:

```python
map(function, iterable)
```

Where:
- `function` is the function to apply to each item in the iterable.
- `iterable` is the sequence, collection, or any iterable object.

Let's see a simple example:

```python
# Define a function
def square(x):
    return x ** 2

# Apply square function to a list using map
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)

# Convert map object to list to see the result
print(list(squared_numbers))
```

Output:

```
[1, 4, 9, 16, 25]
```

## Using `map()` with built-in functions

`map()` can be combined with built-in functions like `str()` or `int()` to transform data types:

```python
# Convert list of numbers to list of strings
numbers = [1, 2, 3, 4, 5]
str_numbers = map(str, numbers)

# Convert list of strings to list of integers
strings = ["1", "2", "3", "4", "5"]
int_numbers = map(int, strings)

print(list(str_numbers))
print(list(int_numbers))
```

Output:

```
['1', '2', '3', '4', '5']
[1, 2, 3, 4, 5]
```

## Applying `map()` with lambda functions

Lambda functions are commonly used with `map()` for quick, inline transformations:

```python
# Using lambda function with map to double each element
numbers = [1, 2, 3, 4, 5]
doubled_numbers = map(lambda x: x * 2, numbers)

print(list(doubled_numbers))
```

Output:

```
[2, 4, 6, 8, 10]
```

## Combining `map()` with multiple iterables

`map()` can accept multiple iterables, applying the function to each corresponding element:

```python
# Combine two lists element-wise
voltages = [5, 10, 15]
resistances = [2, 4, 6]
currents = map(lambda v, r: v / r, voltages, resistances)

print(list(currents))
```

Output:

```
[2.5, 2.5, 2.5]
```

## Handling different data types with `map()`

`map()` can handle different data types seamlessly:

```python
# Apply different operations to different data types
data = [1, 2, 3, "4", "5"]
processed_data = map(lambda x: x + 1 if isinstance(x, int) else int(x) + 1, data)

print(list(processed_data))
```

Output:

```
[2, 3, 4, 5, 6]
```

# Conclusion

The `map()` function in Python offers a flexible and efficient way to apply a function to each item in an iterable. Whether working with built-in functions, lambda functions, or combining multiple iterables, `map()` enables concise and readable code for data transformation tasks.
Revolutionizing Content Creation: Autopilots Connect LLMS and AI for Seamless Results
Published: 2024-03-02 23:00:35

<small>
Note: This content was automatically generated and published by Autopilots, without any human intervention.
</small>

# Autopilots: Revolutionizing Content Creation

In the fast-paced world of content creation, efficiency and accuracy are key. Autopilots have emerged as a cutting-edge service that connects multiple Learning Management Systems (LMS) and Application Programming Interfaces (APIs) to streamline the content creation process. Below, we explore why autopilots are becoming increasingly popular, how they work, and why they are revolutionizing the way content is produced.

## Why Use Autopilots?

Autopilots offer a range of benefits that make them a valuable tool for content creators. Some of the key reasons to use autopilots include:

- **Efficiency:** Autopilots automate repetitive tasks, such as importing data from different sources or formatting content, saving time and reducing the risk of errors.
  
- **Integration:** By connecting multiple LMS and APIs, autopilots enable seamless collaboration and data sharing between different systems, making it easier to access and utilize a wide range of resources.
  
- **Consistency:** Autopilots ensure that content is created and delivered consistently across different platforms, maintaining brand identity and quality standards.
  
- **Scalability:** As content needs grow, autopilots can easily scale to handle larger volumes of data and tasks, without compromising on speed or accuracy.

## How Autopilots Work

Autopilots function by leveraging advanced algorithms and machine learning techniques to automate various aspects of the content creation process. They typically operate in the following manner:

1. **Data Integration:** Autopilots connect to different LMS and APIs to gather relevant data, such as user information, course materials, and performance metrics.

2. **Analysis:** Autopilots analyze the collected data to identify patterns, trends, and insights that can inform content creation decisions.

3. **Content Generation:** Based on the analysis, autopilots generate personalized and targeted content, such as course recommendations, assessment questions, or learning pathways.

4. **Delivery:** Autopilots deliver the content to the intended audience through the appropriate channels, such as websites, mobile apps, or email notifications.

## Conclusion

In conclusion, autopilots are revolutionizing the way content is created by offering a powerful combination of efficiency, integration, consistency, and scalability. By automating repetitive tasks, connecting multiple systems, ensuring uniformity, and accommodating growth, autopilots enable content creators to focus on creativity and innovation, ultimately enhancing the overall quality and effectiveness of their work. As technology continues to advance, autopilots are set to play an increasingly important role in shaping the future of content creation."Revolutionizing Content Creation: Autopilots Connect LLMS and AI for Seamless Results