teleren/devto huggingface dataset:
How to Mount an S3 Bucket into an ECS Container
Tags: aws, containers, docker, s3
Published: 2023-08-26 02:57:05


**Introduction**:

In this blog post, we will show you how to mount an S3 bucket into an ECS container. This allows you to access the files in the S3 bucket from within the container.

**Steps:**

- Create an S3 bucket.
- Create an IAM role that allows the ECS container to access the S3 bucket.
- Create an ECS task definition that mounts the S3 bucket into the container.
- Deploy the ECS task definition.

**Detailed Steps:**

- To create an S3 bucket, you can use the AWS Console, the AWS CLI, or the AWS SDKs.

- To create an IAM role, you can use the AWS Console, the AWS CLI, or the AWS SDKs. The IAM role must have the following permissions: 

>         - s3:ListBucket
>         - s3:GetObject
>         - s3:PutObject

- To create an ECS task definition, you can use the AWS Console, the AWS CLI, or the AWS SDKs. The task definition must specify the following:

>         - The container image that you want to use.
>         - The mount point for the S3 bucket.
>         - The IAM role that you created in step 2.

- To deploy the ECS task definition, you can use the AWS Console, the AWS CLI, or the AWS SDKs.

**Example:**

Here is an example of an ECS task definition that mounts an S3 bucket:

```
{
  "taskDefinition": {
    "family": "my-task-family",
    "containerDefinitions": [
      {
        "name": "my-container",
        "image": "my-container-image",
        "mountPoints": [
          {
            "containerPath": "/data",
            "sourceVolume": "my-s3-volume",
            "readOnly": true
          }
        ]
      }
    ],
    "volumes": [
      {
        "name": "my-s3-volume",
        "host": {
          "sourcePath": "/mnt/my-s3-bucket"
        },
        "dockerVolumeConfiguration": {
          "driver": "s3fs",
          "options": {
            "s3Url": "https://s3.amazonaws.com/my-bucket",
            "accessKeyId": "my-access-key-id",
            "secretAccessKey": "my-secret-access-key"
          }
        }
      }
    ]
  }
}
```

In this example, the container is named my-container and it is using the image my-container-image. The S3 bucket is mounted at the /data path in the container. The S3 bucket is also configured with the IAM role that you created in step 2.

**Conclusion:**

In this blog post, we showed you how to mount an S3 bucket into an ECS container. This allows you to access the files in the S3 bucket from within the container.

I hope this helps!
Embarking on a Coding Odyssey: From Khulna to the World of Software Engineering
Published: 2023-08-26 02:50:11

Hey everyone! 👋 I wanted to share my exciting journey as I work towards my dream of becoming a software engineer. As someone hailing from the beautiful city of Khulna, Bangladesh, I've embarked on a coding odyssey that's filled with challenges, learning, and a whole lot of passion.

🖥️ Falling in Love with Code

From the moment I wrote my first line of code, I was hooked. There's something mesmerizing about how a few instructions can bring life to digital creations. I've always had a knack for problem-solving, and coding seemed like the perfect outlet for my creativity and logical thinking.

📚 Learning with a Purpose

As an unemployed individual with a burning desire to excel, I've chosen the path of a self-taught programmer. My days are filled with learning sessions that delve into various programming languages, algorithms, and design patterns. The goal? To not just write code, but to craft elegant and efficient solutions.

🌐 Connecting with the Coding Community

One thing I've learned is that the coding community is incredibly supportive. Whether it's joining forums like Stack Overflow or collaborating on open-source projects on GitHub, I'm continuously amazed at how much knowledge is shared freely. It's heartwarming to see how programmers from all around the world come together to help each other grow.

🚀 Striving for Mastery

My ultimate aim is to become a better coder every day. I devour tutorials and immerse myself in coding challenges, pushing the boundaries of my understanding. Concepts like data structures and algorithms, once daunting, now feel like exhilarating puzzles waiting to be solved.

🎓 The Feynman Technique: My Secret Weapon

One technique that's been a game-changer for me is the Feynman Technique. By simplifying and teaching coding concepts as if I were explaining them to someone new, I've found my understanding deepening and my confidence soaring. It's like being both the student and the teacher, all in one.

🌟 The Road Ahead

While the path to becoming a software engineer might be demanding, I'm fueled by my passion and a vision of the future I'm working towards. I'm excited to explore new languages, contribute to open-source projects, and one day build applications that make a positive impact on the world.

If you share my love for coding, self-improvement, or if you're just curious about the world of programming, let's connect! Feel free to drop a comment, ask questions, or share your own experiences. We're all on this coding journey together. 🚀💻
Updating UI with API Data in Swift
Tags: swift, programming, tutorial
Published: 2023-08-26 01:57:26

In this unit, we will delve into the process of updating the user interface (UI) with the data fetched from the API. This involves understanding the concept of data binding in Swift and implementing it to reflect the changes in the weather data on the UI. We will also cover error handling techniques during UI updates.

## UI Updates

Updating the UI with the fetched weather data is a crucial part of creating a weather application. This involves displaying the data on the screen in a user-friendly manner. In Swift, this can be achieved using various UI elements such as labels, images, and buttons. The data fetched from the API can be displayed on these UI elements.

## Data Binding

Data binding is a technique that establishes a connection between the app's UI and the data sources. It ensures that changes in the data source (in our case, the weather data) automatically reflect on the UI.

In Swift, this can be achieved using property observers and SwiftUI's `@State` and `@Binding` property wrappers. Property observers `willSet` and `didSet` observe and respond to changes in a property's value. SwiftUI's `@State` and `@Binding` property wrappers provide a way to create a mutable state for some data, that when changed, will re-render the view that depends on that data.

## Implementing Data Binding

To implement data binding, we first need to declare a `@State `variable in the view that will hold the weather data. This variable should be updated whenever new data is fetched from the API.

Next, we bind this variable to the UI elements that display the weather data. This can be done using the `$` prefix. For example, if we have a label that displays the temperature, we can bind it to the temperature property of our weather data like this: `Text("\(self.$weatherData.temperature)")`.

Now, whenever the weather data changes, the UI will automatically update to reflect these changes.

## Error Handling

Errors can occur during UI updates, especially when dealing with asynchronous data fetching from an API. Swift provides several techniques to handle these errors and ensure that the app doesn't crash unexpectedly.

One common technique is using Swift's do-catch statement to catch and handle errors. Another technique is using optional binding (if let or guard let) to handle cases where the data might be nil.

In the context of our weather app, we can use these techniques to handle cases where the weather data might not be fetched correctly, or the data might be nil. This ensures that our app handles these situations gracefully and provides a smooth user experience.
Representing Weather Data Using Models in Swift
Tags: swift, programming, tutorial
Published: 2023-08-26 01:55:48

In this unit, we will delve into the concept of data models in Swift and how to create a data model for our weather data. We will also learn how to map the parsed JSON data to our weather model.

## Introduction to Data Models

Data models in Swift are a way of structuring data in a specific format. They are essentially classes or structs that encapsulate related data in a way that makes it easy to work with. Data models are a fundamental part of any application and are particularly useful when dealing with complex data structures, such as the data we receive from a weather API.

## Creating a Weather Model

Creating a data model for our weather data involves defining a new struct that represents the data we want to capture. For our weather app, we might define a Weather struct like this:
```swift
struct Weather {
    let temperature: Double
    let humidity: Double
    let precipitationProbability: Double
    let summary: String
}
```
In this struct, we have four properties that represent the key pieces of data we want to capture about the weather: the temperature, humidity, precipitation probability, and a summary of the weather.

## Mapping JSON to the Model

Once we have our Weather struct defined, we can map the parsed JSON data to instances of this struct. This involves extracting the relevant pieces of data from the JSON and using them to initialize new Weather instances.

Here's an example of how we might do this:
```swift
if let temperature = json["temperature"] as? Double,
   let humidity = json["humidity"] as? Double,
   let precipitationProbability = json["precipProbability"] as? Double,
   let summary = json["summary"] as? String {
    let weather = Weather(temperature: temperature, humidity: humidity, precipitationProbability: precipitationProbability, summary: summary)
    // Do something with `weather`...
}
```
In this code, we're using optional binding to safely extract the data from the JSON. If any of the data is missing or of the wrong type, the if let statement will fail and the weather instance won't be created.

By the end of this unit, you should have a solid understanding of how to create data models in Swift and how to map JSON data to these models. This is a crucial step in building our weather app, as it allows us to work with the weather data in a structured and type-safe way.
Serialization in Flask to prevent recursion
Published: 2023-08-26 01:55:13

While learning how to build a web application using Flask and React, I've run into the ever delightful recursion error because I forgot to use an extremely helpful extension. The 'flask-restful' extension has a tool called 'SerializerMixin' which allows you to control how the objects are serialized.

###What is Serialization?
It's a process to convert complex data structures (like Python objects) into a format that is easily transmitted/stored (like JSON).

###How would SerializerMixin help to avoid recursion?
Let's say that in the application that is being built, there is a many to many relationship between authors and books. An author can write many books and a book can have multiple authors.  When you try to fetch an author's information and you want to include a list of books that they've written, you might end up in an infinite loop when you serialize the author object with their books.

To prevent this, you would use 'serialize_rules' in the author class to control the depth of recursion, which would look something like- `serialize_rules = ('-what_you_want_to_remove',)`. Just remember that when you use 'serialize_rules it has to equal a tuple.
Understanding JSON Parsing in Swift
Tags: swift, programming, tutorial
Published: 2023-08-26 01:54:49

JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

## Understanding JSON

JSON is a syntax for storing and exchanging data. JSON data is written as key/value pairs, just like JavaScript object properties. A key/value pair consists of a field name (in double quotes), followed by a colon, followed by a value. For example:
```swift
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
```
## Swift and JSON

Swift provides built-in support for JSON encoding and decoding. The `JSONDecoder` and `JSONEncoder` types can convert between JSON and Swift data types like `String`, `Int`, `Double`, `Date`, `Array`, `Dictionary`, and your own custom types.

## Parsing JSON

Parsing JSON in Swift is a common task that most developers need to do. Swift makes this process easy and efficient with the use of `Codable` protocol. Here is a simple example of how to parse a JSON string into a Swift object:
```swift
struct User: Codable {
    let name: String
    let age: Int
    let city: String
}

let jsonString = """
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
"""

let jsonData = jsonString.data(using: .utf8)!
let user = try! JSONDecoder().decode(User.self, from: jsonData)

print(user.name) // Prints: John
```
In this example, `User` is a struct that conforms to the `Codable` protocol. This allows us to decode a JSON string into a `User` object.

## Error Handling

When parsing JSON data, it's important to handle potential errors. Swift provides several error handling mechanisms. For example, you can use a do-catch statement to handle errors in a graceful manner:
```swift
do {
    let user = try JSONDecoder().decode(User.self, from: jsonData)
    print(user.name)
} catch {
    print("Error decoding JSON: \(error)")
}
```
In this example, if an error occurs during the decoding process, the error is caught and handled by the catch block.

In conclusion, JSON parsing is a fundamental skill for any Swift developer. With Swift's built-in support for JSON encoding and decoding, you can easily parse JSON data and use it in your applications.
Completing the Full Stack Bootcamp: A Summer to Remember!
Published: 2023-08-26 01:27:33


Hey everyone,

I'm excited to share that I've successfully wrapped up a whirlwind 10-week journey with the NYC Tech Talent Pipeline Full Stack Development Bootcamp. This summer has been an incredible ride of growth, challenges, and learning, and I couldn't be more proud of the progress we've made.

A massive shoutout to Sabine Salandy and Farzana Ruzehaji – your guidance and constant encouragement made a world of difference. Dakota Lee Martinez, Ahsan Abbasi, Chadrick Hinds, Nicky Liu, Jorge Vasquez, and Jean Luis Urena – you all are rockstars! Your unwavering support and dedication fueled us through every twist and turn this summer.


And to my fellow TTP peers, you all are a powerhouse of potential. It's been fantastic connecting with so many incredible individuals this summer. Here's to each of you reaching new heights and accomplishing great things in your journeys ahead.

As we each step into the future, armed with newfound skills and connections, let's continue pushing boundaries and making our mark in the tech world. Here's to the exciting adventures that lie ahead!

Stay awesome,
TypeScrip
Tags: beginners
Published: 2023-08-26 00:27:27

The Journey of thousand step. My first pre-work assignment before entering a Coding Bootcamp Write a Short Blog post of what I learned this week. TypeScrip, Could it Be the multitool of the future? I learned that TypeScrip Could be use to construct web-apps,Mobile-apps Backend systems and applications, also TypeScrip supports front end and Backend.
scraping all airconditioned from the free market sales site
Tags: webscraping, python
Published: 2023-08-26 00:08:39

```
from bs4 import BeautifulSoup
import requests
from time import sleep
import csv
import re
import math

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
    }

response = requests.get("https://lista.mercadolivre.com.br/ar-condicionado#D[A:ar%20condicionado]", headers=headers)
soup = BeautifulSoup(response.content, "html.parser")

items = soup.find('span', class_='ui-search-search-result__quantity-results shops-custom-secondary-font').get_text()
itemsI = items.find(' ')
items = items[:itemsI]
items = items.replace('.','')
items = math.ceil(int(items)/50)
index = 1



dictItems = {'Title':[], 'Price':[], 'Link':[]}


for i in range(1, items+1):
    nextPage = f'https://lista.mercadolivre.com.br/eletrodomesticos/ar-ventilacao/ar-condicionado/ar-condicionado_Desde_{index}_NoIndex_True'
    response = requests.get(nextPage, headers=headers)
    soup = BeautifulSoup(response.content, "html.parser")
    ar = soup.find_all('li', class_=re.compile('ui-search-layout__item shops__layout-item'))
    
    for i in ar:
        name = i.find('h2', class_=re.compile('ui-search-item__title shops__item-title')).get_text()
        price = i.find('span', class_=re.compile('andes-money-amount__fraction')).get_text()
        urls = i.find('a')['href']
        dictItems['Title'].append(name)
        dictItems['Price'].append(price)
        dictItems['Link'].append(urls.get('href'))
```
Polimorfismo e Generics Avançados em TypeScript
Tags: typescript, programming, webdev, productivity
Published: 2023-08-25 23:37:56

O TypeScript oferece recursos avançados para tipos e polimorfismo, especialmente ao trabalhar com generics. Estes recursos proporcionam maior segurança ao tipar e flexibilidade em cenários de programação comuns.

## Generics com Restrições

Em algumas situações, deseja-se permitir qualquer tipo com generics, mas ainda quer-se restringir os tipos possíveis com certas características. Essas restrições são definidas usando a cláusula `extends`.

### Exemplo:

Suponha que você queira uma função que retorne uma propriedade de um objeto, mas você quer garantir que a propriedade realmente exista no objeto.

```typescript
function getPropriedade<T, K extends keyof T>(obj: T, chave: K): T[K] {
    return obj[chave];
}

const pessoa = {
    nome: "Ana",
    idade: 25
};

// Uso válido
let nome: string = getPropriedade(pessoa, "nome");

// Erro! "altura" não é uma chave de pessoa.
// let altura: number = getPropriedade(pessoa, "altura");
```

Neste exemplo, `K extends keyof T` garante que o segundo argumento seja uma chave do objeto fornecido como primeiro argumento.

## Usando a palavra-chave `keyof`

A operação `keyof` é uma operação de tipo que pega um tipo e produz uma string ou tipo numérico literal que representa as chaves desse tipo.

### Exemplo:

```typescript
interface Carro {
    marca: string;
    modelo: string;
    ano: number;
}

type ChavesDoCarro = keyof Carro;  // "marca" | "modelo" | "ano"
```

Aqui, `ChavesDoCarro` é um tipo que pode ser `"marca"`, `"modelo"` ou `"ano"`. 

### Usando `keyof` com Generics:

`keyof` é extremamente útil em conjunto com generics, especialmente quando se deseja garantir que a operação seja realizada com propriedades que existem em um objeto.

```typescript
function setPropriedade<T>(obj: T, chave: keyof T, valor: T[keyof T]): T {
    obj[chave] = valor;
    return obj;
}

const carro: Carro = {
    marca: "Toyota",
    modelo: "Corolla",
    ano: 2020
};

// Uso válido
setPropriedade(carro, "modelo", "Camry");

// Erro! "cor" não é uma chave de Carro.
// setPropriedade(carro, "cor", "Vermelho");
```

## Conclusão

Polimorfismo e generics avançados em TypeScript ampliam as possibilidades de criar código reutilizável e ainda mantêm uma forte segurança de tipo. Com a combinação de generics restritos e a operação `keyof`, é possível escrever funções genéricas precisas e seguras que operam em propriedades de objetos. Estes recursos tornam o TypeScript uma ferramenta poderosa para desenvolvimento, combinando flexibilidade com segurança de tipo.
Manipulação Avançada de Tipos com Utility Types
Tags: typescript, tutorial, programming
Published: 2023-08-25 23:35:28

Manipulação Avançada de Tipos com Utility Types

Os Utility Types no TypeScript permitem uma forma de transformar tipos de maneira modular e reutilizável. Alguns dos utility types mais comuns são `Partial`, `Readonly` e `Record`, mas há muitos outros igualmente úteis.

## Entendendo Partial, Readonly, Record, e outros

### 1. `Partial<T>`

Transforma todas as propriedades de um tipo `T` em propriedades opcionais.

```typescript
interface Pessoa {
    nome: string;
    idade: number;
}

type PessoaParcial = Partial<Pessoa>;
// Equivalent a:
// type PessoaParcial = {
//    nome?: string;
//    idade?: number;
// }
```

### 2. `Readonly<T>`

Torna todas as propriedades de um tipo `T` como somente leitura.

```typescript
type PessoaReadonly = Readonly<Pessoa>;
// Equivalent a:
// type PessoaReadonly = {
//    readonly nome: string;
//    readonly idade: number;
// }
```

### 3. `Record<K,T>`

Cria um tipo com um conjunto de propriedades `K` e um tipo de valor `T`.

```typescript
type DictionaryNumeros = Record<string, number>;
// Representa um objeto onde as chaves são strings e os valores são números
```

## Casos práticos: transformando tipos com utility types

### 1. Atualização Parcial

Suponha que você esteja criando uma função para atualizar os detalhes de um usuário. Usando `Partial`, você pode criar um tipo que representa um subconjunto dos detalhes do usuário:

```typescript
interface Usuario {
    id: number;
    nome: string;
    email: string;
}

function atualizarUsuario(id: number, detalhes: Partial<Usuario>) {
    // atualiza o usuário no banco de dados
}
```

### 2. Objetos Configuráveis

Utilizando o tipo `Record`, você pode criar um tipo para representar um objeto de configuração onde todas as chaves são strings e todos os valores seguem um tipo específico:

```typescript
type Configuracoes = Record<string, string | number | boolean>;

function aplicarConfiguracoes(config: Configuracoes) {
    // aplica as configurações
}
```

### 3. Objetos Imutáveis

Para garantir que um objeto não seja modificado após ser criado, você pode usar `Readonly`:

```typescript
const userReadonly: Readonly<Usuario> = {
    id: 1,
    nome: "João",
    email: "joao@example.com"
};

// A seguinte linha resultará em erro
// userReadonly.nome = "Pedro";
```

## Outros Utility Types úteis:

- `Pick<T, K extends keyof T>`: Cria um tipo selecionando um conjunto de propriedades `K` de `T`.
- `Omit<T, K extends keyof T>`: Cria um tipo removendo um conjunto de propriedades `K` de `T`.
- `Exclude<T, U>`: Exclui os tipos de `U` de `T`.
- `Extract<T, U>`: Seleciona os tipos de `T` que podem ser atribuídos a `U`.
- `ReturnType<T>`: Obtem o tipo de retorno de uma função.

## Conclusão

Os Utility Types em TypeScript fornecem uma série de ferramentas poderosas para a manipulação de tipos, tornando o sistema de tipos ainda mais flexível e expressivo. Quando você se familiarizar com essas construções, encontrará muitos casos em que elas podem tornar seu código mais limpo e mais seguro.