teleren/devto huggingface dataset:
Patrón Proxy: Una introducción teórica
Tags: javascript, webdev, performance, designpatterns
Published: 2024-01-02 11:43:59

Este post forma parte de una serie en la que estaremos desglosando uno por uno los distintos patrones de diseño de manera teórica en un blog post. Además, subiré la explicación práctica a [mi canal de YouTube](https://www.youtube.com/c/wiar8). ¡No olvides seguirme para no perderte este interesante contenido! 😁

En el desarrollo de software, el patrón Proxy es un patrón de diseño que proporciona un objeto intermediario para controlar el acceso a otro objeto. El objetivo principal del Proxy es agregar una capa adicional de indirección y control sobre una funcionalidad existente.

El Proxy actúa como un sustituto o representante del objeto real, permitiendo controlar el acceso a dicho objeto y agregar funcionalidades adicionales si es necesario. Esto puede ser útil en situaciones donde se requiere una validación previa, un manejo de caché o una restricción en el acceso a ciertos recursos.


![3 personas en las que actúa un intermediario](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/15n2k9rbvpg8ram4km60.jpeg)

## Estructura del patrón Proxy

El patrón Proxy se compone de los siguientes elementos:

- Sujeto: Es la interfaz común que define tanto al Sujeto Real como al Proxy. Define las operaciones que el Proxy puede realizar en nombre del Sujeto Real.

- Sujeto Real: Es el objeto real al cual el Proxy proporciona acceso controlado. Contiene la implementación concreta de las operaciones definidas en el Sujeto.

- Proxy: Es el objeto intermediario que implementa la misma interfaz que el Sujeto Real. Controla el acceso al Sujeto Real y puede realizar tareas adicionales antes o después de llamar al Sujeto Real.

## Aplicabilidad del patrón Proxy

El patrón Proxy es aplicable en diversas situaciones, tales como:

- Control de acceso: El Proxy puede verificar y autorizar el acceso a un objeto antes de permitir que se realice una operación.

- Carga diferida (Lazy loading): El Proxy puede retrasar la creación o carga de un objeto hasta que sea realmente necesario, mejorando así el rendimiento.

- Caché: El Proxy puede almacenar en caché los resultados de operaciones costosas y devolverlos directamente en futuras solicitudes.

- Logging: El Proxy puede agregar registros o realizar un seguimiento detallado de las operaciones realizadas en el Sujeto Real.

## Cuando NO utilizar el patrón Proxy

El patrón de diseño Proxy no es adecuado para todos los casos. A continuación, se muestran algunos escenarios en los que no se debe utilizar el patrón Proxy:

1. Cuando el rendimiento es un problema: El proxy puede agregar una capa adicional de indirección, lo que puede afectar al rendimiento de la aplicación.

2. Cuando el objeto real es simple: Si el objeto real es simple, no es necesario utilizar un proxy.

3. Cuando el proxy no proporciona ninguna funcionalidad adicional: Si el proxy no proporciona ninguna funcionalidad adicional, no es necesario utilizarlo

😁 Si este post te ha gustado, puedes seguirme en mi canal de [YouTube ](https://www.youtube.com/c/wiar8) en el cual subo contenido relacionado a la programación 🐢
O que o Mr Robot nos ensina sobre bugs
Published: 2024-01-02 11:33:51

Às vezes, agimos como se os bugs aparecessem em nosso código sozinhos, mas todos sabemos que isso não é verdade. Os erros no meu código foram escritos por mim. Eu não quis escrevê-los. Eu não queria escrevê-los. Mas eu fiz assim mesmo.

Eu me lembro quando li pela primeira vez [Al Shalloway](https://twitter.com/alshalloway) referir-se a um bug como “código que ele havia escrito” e me ocorreu, eu sou o autor dos bugs no meu código. Não havia mais ninguém para culpar além de mim.

Muitas equipes acumulam bugs. Em vez de observar a mensagem que os bugs estão nos dizendo e corrigi-los assim que são encontrados, eles os identificam, rastreiam e dizem a eles mesmos que um dia eles vão se livrar deles.

Boa sorte.

Esse número simplesmente cresce e cresce até que haja tantos bugs que torna inviável corrigir, assim aprende-se a viver com a maioria deles e os bugs puxam o projeto para baixo.

Bugs são frequentemente a ponta do iceberg, eles são o prenúncio de algo muito pior que está por vir, um sinal de alerta de que as coisas estão indo mal. Devemos prestar atenção a esses avisos e não ignorá-los.

Alguns bugs se escondem muito bem e encontrá-los, muitas vezes, pode ser a parte mais difícil de elimina-los. Um velho amigo me diz que encontrar um bug em um sistema grande é como ser informado de que há uma palavra incorreta em um dicionário. Consertar uma palavra incorreta é fácil, encontrar a palavra incorreta pode ser demorado e entediante.

Na série Mr. Robot, no episódio 1.2_d3bug.mkv, Elliot diz: “Debugar não é só sobre encontrar o bug. É sobre entender por que o bug estava lá para começar. Saber que sua existência não foi acidental. ”

Eu tenho lidado com bugs por muitos anos como desenvolvedor, mas só recentemente comecei a vê-los pelo que eles realmente são: falhas no meu processo de desenvolvimento de software.

E como os insetos, os bugs de softwares precisam das condições certas para se reproduzir. Bugs não acontecem, nós os deixamos acontecer.

Mas não tem que ser assim. Em vez de acumular bugs, podemos reconhecê-los pelos mensageiros que são e atender a mensagem deles para retomar o caminho. Todo bug é um teste ausente, uma distinção crítica que não conseguimos perceber. Se pudermos ver isso, nós podemos não apenas consertar esse bug, mas também vencer uma série inteira de bugs.

Se pudermos ver um bug como o que realmente é, então ele se torna meu professor e nós nos tornamos seus alunos agradecidos.
5 Projects To Build As A Developer
Tags: productivity, coding, learning, beginners
Published: 2024-01-02 11:30:31

_Building Project is the best way to learn coding and these are the only project you need to build which can be added to your portfolio as a beginner._

Take your time and build these exciting projects ⬇️

**Expense Tracker:**

- _Create a web or mobile app that allows users to track their expenses._
- _Implement features such as adding, categorizing, and deleting transactions._
- _Provide visualizations and insights into spending patterns over time._

**Blog Platform:**

- _Build a blog platform where users can create accounts, write, edit, and delete posts._
- _Implement features like comments, tags, and user authentication._
- _Explore additional functionalities such as image uploads and markdown support._

**Job Board for Developers:**

- _Develop a job board website specifically tailored for developers._
- _Allow employers to post job listings and developers to search and apply for jobs._
- _Implement user authentication, notifications, and possibly integrate with third-party job APIs._

**E-learning Platform:**

- _Create an e-learning platform with features for course creation, enrollment, and progress tracking._
- _Include user authentication, video content hosting, and a discussion forum for each course._
- _Explore incorporating gamification elements like badges or certificates._

**Real-Time Chat Application:**

- _Build a real-time chat application that supports one-on-one and group chats._
- _Implement features like message history, user presence indicators, and notifications._
- _Use technologies like webSockets for real-time communication._
Django Views
Tags: django, beginners
Published: 2024-01-02 11:22:51

As of the day I write this post, Django supports 3 ways to create a view: 

- function-based
- class-based
- generic class-based

Most problems you are trying to solve have probably already been done via a generic class based view. If it hasn't it is often possible to modify one of the generic views to suit your needs. 

This will be my default approach to always utilise a generic class based view. Failing that I will fall back to creating a class-based view, then a function-based view. 

For further learnings on this topic, check out the very useful [Classy Class-Based Views site](https://ccbv.co.uk/).
How to buy Ripple (XRP) using Tether (USDT) on koinpark?
Tags: ripple, buyripple, tradexrptousdt, tradexrptoinr
Published: 2024-01-02 11:15:03


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lenjrugw1qklx41rzhk.jpg)
**How to buy Ripple (XRP) using Tether (USDT) on koinpark?**

To Buy Ripple (XRP) using Tether(USDT), you can utilize a Koinpark ([Global Cryptocurrency Exchange](https://www.koinpark.com/)), which facilitates various crypto trades. Koinpark offers a streamlined process, robust security features including 2FA verification, and a user-friendly interface for seamless transactions.

**What Makes Koinpark Ideal for XRP Trading?
**
Koinpark stands out for its wide selection of cryptocurrencies, particularly XRP, catering to traders of various expertise levels. We ensure affordable fees and increased investment value on our platform. Your XRP security is our top priority, employing cutting-edge security measures. With a user-friendly interface, our platform simplifies Ripple trading, accommodating traders of all skill levels.

**Here are the steps to buy Ripple using USDT on Koinpark:**

Register on Koinpark: Sign up on Koinpark by registering an account. Ensure to provide a valid email address and phone number during the signup process.

Identity Verification: Complete the identity verification process as required by the platform. This usually involves submitting valid identification proof.

Deposit USDT: Once your account is set up and verified, deposit USDT into your wallet via bank transfer. Make sure that your 
wallet contains the required balance before moving forward.

Navigate to the Trade Page: Access the trade section on Koinpark's platform.

Select XRP/USDT Pair: Choose the [XRP/USDT](https://www.koinpark.com/trade/XRP-USDT) trading pair to initiate the purchase.

Place Your Order: Select the quantity of Ripple (XRP) you wish to buy and then proceed by either placing your order at the current market price or setting a personalized price for your 

Review and Confirm: Review the specifics of your purchase, such as the quantity and price, before confirming the transaction.

Complete the Purchase: Once confirmed, execute the trade to buy Ripple using your deposited USDT.

**Conclusion:
**
Join the Koinpark community now and explore the world of cryptocurrency trading. Take advantage of the platform's features to Buy Ripple (XRP) using Tether (USDT) through Koinpark. Visit Koinpark's website (https://www.koinpark.com/register) to sign up and start your journey in trading Ripple with USDT seamlessly.
Download the Koinpark [Cryptocurrency Exchange app](https://play.google.com/store/apps/details?id=com.application.koinpark&hl=en_US)
Pay & Use
Tags: arduino, raspberrypi, upi, circuitpython
Published: 2024-01-02 11:02:59

Abstract:

We're seeking engineering and development assistance for a community project that aims to design and implement a pay-per-use system for a solar-powered pump machine in our village. The primary goal is to allow villagers to pay for the pump's operation on an hourly basis using the Unified Payments Interface (UPI) or similar digital payment methods.

Objective:

To develop a reliable and user-friendly system where villagers can select the number of hours they intend to use the pump and make a payment accordingly.
Ensure the pump operates for the paid duration and stops automatically after the time lapses.
Integrate safety measures, including manual overrides and fail-safes.
Key Components:

A Payment Interface Device (PID) capable of UPI or other digital payments.
A microcontroller-based system (e.g., Arduino, Raspberry Pi) to process payment details, control pump operations, and manage timing.
A relay circuit to act as an electronic switch for the pump.
Appropriate software logic to interface between the payment system and the machinery.
Why This Matters:
The project aims to promote fairness in resource allocation, ensuring that all villagers have equal access to the water resource. By monetizing the operation, we hope to maintain the machinery better, ensuring long-term availability and reduced downtimes.

Seeking Expertise In:

Electronic circuit design and implementation.
Microcontroller programming (Arduino, Raspberry Pi, etc.).
UPI or digital payment integration.
Relay control and automation.
Any experience or knowledge in similar pay-per-use systems would be a bonus.
Project Location: Bihar

Contact Information: rahulsingh@pradan.net. Keep subject as "Pay & Use Project"

We invite passionate engineers, developers, and hobbyists to join us in making a difference in our community. Any leads, advice, or direct assistance would be immensely appreciated!
Creating a Staking Smart Contract on Solana using Anchor
Tags: solana, webdev, beginners, blockchain
Published: 2024-01-02 10:56:22

This article explores a concise yet comprehensive guide on creating a staking smart contract on Solana utilizing Anchor. Explore the vast potential of [Solana blockchain development services](https://blockchain.oodles.io/solana-blockchain-development-services/?utm_source=devto) by leveraging Anchor’s capabilities to build robust staking mechanisms.

## What is Solana Blockchain
[Solana](https://blockchain.oodles.io/solana-blockchain-development-services/?utm_source=devto) is a high-performance blockchain platform that provides fast, secure, and scalable transactions for decentralized applications (dApps) and marketplaces. Solana uses a unique consensus algorithm called Proof of History (PoH), which allows the network to verify transactions and reach consensus quickly and efficiently.

Solana also provides a suite of developer tools, including a web-based wallet, smart contract language, and decentralized exchange (DEX) for developers to build on its platform. Its native cryptocurrency, SOL, is used for transaction fees, staking, and exchange within the Solana ecosystem.

Learn about smart contracts and their installation process and versions used in code by reading on — [Installation and Versions Used in Code.](https://blockchain.oodles.io/dev-blog/Create-a-Staking-Smart-Contract-on-Solana-using-Anchor/?utm_source=devto)
Amazon Managed Streaming for Apache Kafka
Tags: aws, awsmsk, awsbigdata
Published: 2024-01-02 10:50:18

### Introduction to Amazon Managed Streaming for Apache Kafka (Amazon MSK)
Amazon MSK makes it easy to ingest and process streaming data in real-time with fully managed Apache Kafka.

**APACHE KAFKA AT A HIGH LEVEL**

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

What can fully manage Apache Kafka on AWS do:

- Allow you to create, update, and delete clusters
- MSK creates & manages Kafka brokers nodes & Zookeeper nodes for you
- Deploy the MSK cluster in your VPC, multi-AZ (up to 3 for HA) Automatic recovery from common Apache Kafka failures Data is stored on EBS volumes
- You can build producers and consumers of data 
- Can create custom configurations for your clusters
- Default message size of 1MB
- Possibilities of sending large messages (ex: 10MB) into Kafka after custom configuration 

### MSK – Configurations

- Choose the number of AZs (3 – recommended, or 2)
- Choose the VPC & Subnets
- The broker instance type (ex: kafka.m5.large)
- The number of brokers per AZ (can add brokers later)
- Size of your EBS volumes (1GB – 16TB) 

### MSK – Security 
**Encryption:**
- Optional in-flight using TLS between the brokers
- Optional in-flight with TLS between the clients and brokers
- At rest for your EBS volumes using KMS

**Network Security:**
- Authorize specific security groups for your Apache Kafka clients

**Authentication & Authorization:**

- Define who can read/write to which topics
- Mutual TLS (AuthN) + ​​Kafka ACLs (AuthZ)
- SASL/SCRAM (AuthN) + ​​Kafka ACLs (AuthZ)
- IAMAccessControl(AuthN+AuthZ)

### MSK – Monitoring
**CloudWatch Metrics:**
- Basic monitoring (cluster and broker metrics)
- Enhanced monitoring (++enhanced broker metrics)
- Topic-level monitoring (++enhanced topic-level metrics) 

**Prometheus (Open-Source Monitoring):** 
- Opens a port on the broker to export cluster, broker, and topic-level metrics
- Setup the JMX Exporter (metrics) or Node Exporter (CPU and disk metrics)
 
**Broker Log Delivery:**
- Delivery to CloudWatch Logs
- Delivery to Amazon S3
- Delivery to Kinesis Data Streams 

### MSK Serverless

- Run Apache Kafka on MSK without managing the capacity
- MSK automatically provisions resources and scales compute & storage
- You just define your topics and your partitions and you're good to go!
- Security: IAM Access Control for all clusters

#### Kinesis Data Streams vs Amazon MSK

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/514lbqk1vocveugtd4ro.png)
27. Remove Element Problem Solved using JavaScript.
Tags: javascript, programming, webdev
Published: 2024-01-02 10:43:08


![Remove Element Problem Solved using JavaScript.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4lqkezk6i9xjnkbz6dkw.JPG)

Here's a step-by-step explanation of the code:

**1. Function Definition:**

_let removeElement = function (nums, val) { ... }_

This line defines a function named removeElement that takes two arguments:
   **nums:** An array of numbers.
   **val:** The value to be removed from the array.

**2. Initializing Variables:**

_let i = 0;_

This line initializes a variable i to 0. This variable will be used as a pointer to keep track of the position where the next non-val element should be placed in the array.

**3. Iterating Through the Array:**

_for (let j = 0; j < nums.length; j++) { ... }_

This for loop iterates through each element of the nums array using a variable j as the index.

**4. Checking for Elements to Keep:**

_if (nums[j] !== val) { ... }_

Inside the loop, this if statement checks if the current element at index j is not equal to the target value val.

**5. Shifting Elements and Incrementing Pointer:**

_nums[i] = nums[j];_

If the element is not equal to val, it means we need to keep it in the array. So, this line copies the element at index j to the position at index i, effectively shifting non-val elements to the left.

_i++;_

This line increments i to point to the next available position for a non-val element.

**6. Returning the New Length:**

_return i;_

After the loop completes, the function returns the value of i, which represents the new length of the array after removing all occurrences of val. The original array is modified in place.

**7. Calling the Function and Output:**

_let result = removeElement([0, 1, 2, 2, 3, 0, 4, 2], 2);_

This line calls the removeElement function with the array [0, 1, 2, 2, 3, 0, 4, 2] and the value 2 to remove.
_console.log(result);_
This line prints the value returned by the function, which will be 5 in this case, indicating the new length of the array with the 2's removed.
Short quotes for indie hackers (source: my twitter friends)
Published: 2024-01-02 10:33:55

1. Launch fast and a lot. Wait until you get lucky.
50% of your success depends on luck

2. Don't pay attention to 'authorities', think for yourself

3. Doubting yourself doesn't mean that you can't do it.
It means that you are trying to do something you haven't done before

4. If you have a job and see an opportunity to take on more responsibility and grow your career,  don't. Instead, stay under the radar. Take every minute of extra time you have to build your own thing.

5. Drug dealers know more about running a business than 95% of college professors.

6. A lot can change in a year. It  takes some work, a bit of luck and a lot of persistence
Python Enums
Tags: python, beginners
Published: 2024-01-02 10:29:39

A lot of new programmers make the mistake of using strings when they should be using a constant.

```python
if x == 'red':
    // do something
elif x == 'green':
    // do something
elif x == 'blue':
    // do something
```

The obvious problems with this code is that it is error prone as any typo such as 'Red' instead of 'red' will cause an error that doesn't throw an exception and therefore is harder to debug. Also, if we ever want to change 'red' to something else, such as 'orange', in the future then we need to find every occurrence of 'red' in our code and manually change it.

The solution is to create a variable that stores the value of 'red' and to always use this variable wherever we use 'red'.

Sometimes I see people creating a class to store these colour variables.

```python
class Color():
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'
```

This is a reasonable solution, as we now can use `Color.RED` to refer to 'red' everywhere and if we need to change it, can change it directly inside the class. A problem we have here is that if we have 'red' how do we use that to get `Color.RED`?

This solution can be improved using Python's built-in enum module which was introduced in Python 3.4 (https://docs.python.org/3/library/enum.html).

To use it, simply import the `Enum` class from the `enum` module and let your class inherit from `Enum`. Now, we can get the constant from the value simply by using call syntax without any further work, `Color('red') // Color.RED`. To access the value, we can use `Color.RED.value // 'red'`.

```python
from enum import Enum

class Color(Enum):
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'

user_input = 'red'
selected_color = Color(user_input)

if selected_color == Color.RED:
    // do something
elif selected_color == Color.GREEN:
    // do something
elif selected_color == Color.BLUE:
    // do something
```
mua tool ahref
Tags: webdev, javascript, beginners, programming
Published: 2024-01-02 10:27:54

Ahrefs Advanced là gì?
[mua tool ahref](https://www.wsovn.net/mua-chung-ahrefs-advanced) là giải pháp dữ liệu và phân tích toàn diện hỗ trợ cho công việc SEO. Đây được coi là một trong những công cụ hàng đầu đối với những người làm SEO bao gồm các tính năng chính: Thống kê dữ liệu SEO, nghiên cứu từ khóa, theo dõi thứ hạng website, nghiên cứu nội dung, kiểm tra tình trạng SEO.
Ahrefs ‘s Site Explorer
Tính năng này cung cấp cho bạn những thông tin về: Organic Search, Backlink, Paid Search. Bạn có thể vào mục Site explorer nhập địa chỉ website và xem tất cả các thông tin này. Điều này, đặc biệt hữu ích khi bạn phân tích các website của đối thủ để học hỏi và tìm cách vượt lên họ.
Ahrefs ‘s Organic Search
Trong phần này bạn sẽ biết được danh sách những từ khóa của website mục tiêu xuất hiện trên các công cụ tìm kiếm miễn phí. Bằng cách xem xét lưu lượng truy cập, độ khó của những từ khóa này bạn có thể chọn được những từ khóa có nhiều truy cập để phát triển. Một cách khác, bạn có thể chọn những từ khóa ít cạnh tranh hơn để tập trung đưa chúng lên top.
Mua ngay tại: [https://www.wsovn.net/mua-chung-ahrefs-advanced](https://www.wsovn.net/mua-chung-ahrefs-advanced)