teleren/devto huggingface dataset:
Namespaces e Módulos em TypeScript
Tags: typescript, webdev, tutorial
Published: 2023-08-25 23:32:12

Namespaces e módulos são dois conceitos em TypeScript que ajudam a organizar e modularizar seu código. Embora ambos tenham propósitos semelhantes, eles têm características e casos de uso distintos.

## Namespaces

Namespaces, anteriormente conhecidos como "módulos internos", são um meio de agrupar uma coleção relacionada de detalhes sob um único nome.

### Como estruturar seu código com Namespaces:

```typescript
namespace MeuNamespace {
    export class MinhaClasse {
        // Implementação da classe
    }
    
    export interface MinhaInterface {
        // Definição da interface
    }
}
```

Para usar elementos dentro do namespace, você precisa prefixar com o nome do namespace:

```typescript
const minhaInstancia = new MeuNamespace.MinhaClasse();
```

### Namespaces aninhados

Namespaces podem ser aninhados para uma organização ainda mais detalhada:

```typescript
namespace MeuNamespace {
    export namespace SubNamespace {
        export class MinhaSubClasse {
            // Implementação da classe
        }
    }
}
```

## Módulos

Ao contrário dos namespaces, os módulos em TypeScript correspondem mais estreitamente ao módulo ES6 em JavaScript. Eles não adicionam qualquer valor ao escopo global e são mais adaptáveis às técnicas modernas de empacotamento e carregamento de módulos, como CommonJS e AMD.

### Como estruturar seu código com Módulos:

Num arquivo `meuModulo.ts`:

```typescript
export class MinhaClasse {
    // Implementação da classe
}

export interface MinhaInterface {
    // Definição da interface
}
```

Para usar elementos de um módulo, você importa eles:

```typescript
import { MinhaClasse, MinhaInterface } from './meuModulo';
```

## Importação e Exportação de Módulos Avançados:

### Exportando como alias

```typescript
class ClasseInterna {
    // Implementação
}

export { ClasseInterna as MinhaClasseExportada };
```

### Importação com alias

Se houver conflitos de nome ou se o nome for muito longo, você pode usar um alias:

```typescript
import { MinhaClasseExportada as AliasDeClasse } from './meuModulo';
```

### Importando tudo

```typescript
import * as TodoMeuModulo from './meuModulo';

const minhaInstancia = new TodoMeuModulo.MinhaClasse();
```

### Exportações padrão

Cada módulo pode ter no máximo uma exportação padrão:

```typescript
export default class MinhaClassePadrao {
    // Implementação
}
```

Importando uma exportação padrão:

```typescript
import MinhaClasse from './meuModulo';
```

## Conclusão

Enquanto namespaces são ótimos para organizar código interno em grandes bases de código TypeScript, módulos são mais alinhados com o ecossistema moderno JavaScript e se adaptam bem com sistemas de carregamento e empacotamento de módulos. Com a crescente adoção de ES6+ e ferramentas como Webpack e Rollup, usar módulos tornou-se a prática padrão recomendada.
Tipos Avançados em TypeScript
Tags: typescript, webdev, tutorial
Published: 2023-08-25 23:27:11

TypeScript, sendo uma superconjunto de JavaScript, fornece uma camada robusta de recursos de tipagem que nos permitem escrever código de maneira mais segura e previsível. Um desses recursos é o conjunto de tipos avançados. Vamos explorar alguns dos mais notáveis: tipos de união e interseção, tipos literais e mapeamento de tipos, e o tipo condicional e `infer`.

## 1. Tipos de União e Interseção

### 1.1 Tipos de União (`Union Types`)

Um tipo de união é uma maneira de dizer que um valor pode ser de um de vários tipos. Por exemplo:

```typescript
type StringOrNumber = string | number;
```

Isso significa que a variável que tem esse tipo pode ser tanto uma string quanto um número.

```typescript
let value: StringOrNumber;
value = 123;  // válido
value = "abc"; // válido
value = true; // erro
```

### 1.2 Tipos de Interseção (`Intersection Types`)

Enquanto um tipo de união indica que um valor pode ser de um tipo _ou_ outro, um tipo de interseção combina múltiplos tipos em um:

```typescript
type Named = {
  name: string;
}

type Aged = {
  age: number;
}

type Person = Named & Aged;

const person: Person = { name: "Alice", age: 30 }; // válido
```

## 2. Tipos Literais e Mapeamento de Tipos

### 2.1 Tipos Literais (`Literal Types`)

Um tipo literal é uma maneira de definir um tipo que só aceita um valor específico. Por exemplo:

```typescript
type ButtonType = "submit" | "reset";
```

Isto significa que só aceitamos as strings "submit" ou "reset" para este tipo.

### 2.2 Mapeamento de Tipos (`Mapped Types`)

Mapeamento de tipos nos permite criar novos tipos com base em propriedades de um tipo existente:

```typescript
type ReadOnly<T> = {
  readonly [K in keyof T]: T[K];
}

type User = {
  name: string;
  age: number;
}

type UserReadOnly = ReadOnly<User>;
```

No exemplo acima, `UserReadOnly` será um tipo onde todas as propriedades são somente leitura.

## 3. Tipo Condicional e `infer`

### Tipo Condicional

Os tipos condicionais nos permitem escolher um tipo com base em uma condição:

```typescript
type IsString<T> = T extends string ? "yes" : "no";
type Test = IsString<number>; // "no"
```

### Infer

A palavra-chave `infer` nos permite inferir um tipo dentro do escopo do tipo condicional:

```typescript
type ExtractArrayElementType<T> = T extends (infer U)[] ? U : never;

type ElementType = ExtractArrayElementType<string[]>; // string
```

No exemplo acima, inferimos o tipo do elemento do array, que é `string`, e atribuímos a `ElementType`.

## Conclusão

TypeScript, com seus tipos avançados, nos oferece uma ferramenta poderosa para escrever código mais seguro e auto-documentado. Esses recursos avançados de tipagem, quando usados corretamente, podem reduzir significativamente a probabilidade de erros em tempo de execução e tornar nossas aplicações mais robustas.
I want your opinion!
Tags: webdev, javascript, design, react
Published: 2023-08-25 23:10:09

I'm in the process of developing my portfolio website and have been on the lookout for captivating designs that align with my light theme. However, I've noticed that the color scheme I've been using tends to render the website somewhat lackluster.

So far, so good!

I would greatly appreciate any constructive feedback or advice you may have for my website. Please bear in mind that it's still a work in progress, and certain elements, such as the footer on all web pages, have yet to be implemented.

You can access my website through the following link: https://portfolio-kallarari.vercel.app/
Azure Function manifest not found
Tags: azure, azurefunctions
Published: 2023-08-25 22:59:49

Have you ever encountered the frustrating error message "Azure Function manifest not found" while working on your software development projects? Don't worry, you're not alone! This common issue can be a real headache, but with a little understanding and some humor, we can tackle it together.

Before we dive into the solution, let's first understand what this error message actually means. When you create an Azure Function, it requires a manifest file that contains important information about the function, such as its name, entry point, and triggers. This manifest file is crucial for the Azure platform to properly deploy and execute your function.

So, what happens when you see the dreaded "Azure Function manifest not found" error? Well, it means that either the manifest file is missing or it cannot be located by the Azure platform. This can happen due to various reasons, such as incorrect file paths, misconfigured deployment settings, or even a mischievous gremlin hiding your manifest file.

Now, let's get to the fun part - solving this error! Here are a few steps you can follow:

1.  Double-check the file path: Make sure that the manifest file is located in the correct directory. Sometimes, it might have wandered off to a different folder, so be sure to bring it back home.
2.  Verify the file name: The manifest file should be named `function.json`. If it has a different name, rename it to match the expected name. Remember, Azure has a strict sense of humor when it comes to file names.
3.  Inspect your deployment settings: If you're deploying your Azure Function from a source control repository, make sure that the manifest file is included in the deployment. It's easy to overlook this tiny file, but it holds great power!
4.  Summon the gremlin whisperer: If all else fails, it's possible that a mischievous gremlin has hidden your manifest file. Try bribing it with some virtual cookies or consult an expert in gremlin negotiations.

Hopefully, one of these steps will help you resolve the "Azure Function manifest not found" error and get your function up and running smoothly. Remember, a little laughter can go a long way in the world of software development!

References:

*   [Azure Functions - Official Documentation](https://docs.microsoft.com/azure/azure-functions/functions-reference)
*   [Stack Overflow - Azure Function manifest not found](https://stackoverflow.com/questions/12345678)
2023-08-25: WebSockets
Tags: devjournal
Published: 2023-08-25 22:40:10

Good news, everyone. I finally remembered to do it on time this week!

Anyway, the vast majority of this week has been dedicated to learning how websockets work.

The first thing we did this week was start getting oriented with our Monday board, which was finally set up with some tasks to work on for our sprints. We also have a Figma board that has schematics for the application overall which we're working on collaboratively and putting smaller tasks on. 

Back to the websockets, since we're looking to implement a real-time chat functionality between the AI and the client, and eventually P2P chats, we need direct connections between server and client to pass off that information with low latency. Websockets are obviously the standard protocol for this.

Last week I'd written up a whole Python notebook full of test functions using Starlette, the underlying engine for FastAPI, and I discovered some of the mechanisms of WebSockets through talking to ChatGPT and such. 

After a knowledge sync with my coworker on the backend, we got to work setting up a miniature application with a tiny FastAPI server and Svelte frontend. We were able to make two concurrent client connections to the backend without much issue.

We then wanted to explore load testing to see how many websockets a server could possibly take, so I got to work on that alone. I discovered the Python module called Locust, so I decided to use that for this purpose. It has a nice web interface with a GUI, but it was surprisingly difficult to configure a proper connection to the backend. I eventually did get it to work.

Weirdly, though, I noticed that it would start dropping connections exactly after 8174, and I have yet to determine why that number specifically. When I mentioned it to my boss, he told me that we should try testing it on an actual web server, so he spun up the environment on a Linode server and we got the Locust load test to run on there, which started disconnecting even sooner and indeterminately, which is in contrast to how it was on my local machine. We also went through the efforts of setting up SSH between my local machine and that server so I can work off it.

Regardless, I think that's where I'm going to leave it off for this week. I'll probably have to keep testing on the Linode server to see what the deal is with this max connections issue. There's no way it can only be 8174.

Until next time, cheers.
How To Install Private Git Hosted Dependencies Inside Docker Image Using SSH
Tags: docker, devops, security, python
Published: 2023-08-25 22:35:02

## Introduction

This quick guide will show you how to mount a ssh key inside a container in build time, to allow you to install private dependencies, that won't be persisted in the final image. It uses python but could work with any language/package manager that uses git + ssh.

## Dockerfile

First you need to set `Dockerfile` syntax to `docker/dockerfile:1.2`. Put this in the beggining of the file:

```docker
# syntax = docker/dockerfile:1.2
```

Now install git and openssh, and setup ssh folders:

```docker
RUN apt update && \
    apt install -y git openssh-client && \
    mkdir -p /root/.ssh && \
    ssh-keyscan github.com >> /root/.ssh/known_hosts
```

> May vary depending on the base image you're using, just change with the package manager you use.

Make sure to change `github.com` with your git host.

Now you have to mount the ssh key in the step that installs the dependency:

```docker
RUN --mount=type=secret,id=id_rsa,dst=/root/.ssh/id_rsa \
    pip install git+ssh://git@github.com/username/repository.git@version
```

This will mount secret identified by `id_rsa` on `/root/.ssh/id_rsa`.

## Building

When building you need to specify your ssh key as `id_rsa` secret:

```bash
docker build . \
    -f Dockerfile \
    --secret id=id_rsa,src=/home/user/.ssh/id_rsa
```

Or using docker compose:

```yaml
version: '3.7' 
services:
  your_service:
    build:
      context: .
      dockerfile: Dockerfile
      secrets:
        - id_rsa
secrets:
  id_rsa:
    file: /home/user/.ssh/id_rsa
```

## Final file

```docker
# syntax = docker/dockerfile:1.2

FROM python:3.11

RUN apt update && \
    apt install -y git openssh-client && \
    mkdir -p /root/.ssh && \
    ssh-keyscan github.com >> /root/.ssh/known_hosts

RUN --mount=type=secret,id=id_rsa,dst=/root/.ssh/id_rsa \
    pip install git+ssh://git@github.com/username/repository.git@version
```

## Conclusion

Keep your secrets secret!
The essence of Recursion ?
Tags: java, discuss, programming, newbie
Published: 2023-08-25 22:29:16

I have been learning recursion recently and have to really question it's nature, It is a fascinating technique and over all just so intuitively human in nature which surprises me. The logic of context within a context and the complexity it dwells into and further in thought the existence of relying on receiving data within itself is something i never thought of before. I cant pinpoint how using Recursion feels human because it is not relatable to any Human way of doing it, the closest I can point is the Summation function in mathematical series.
Add Syntax Highlighter in NuxtJS 3 with Prism
Tags: javascript, vue, nuxt
Published: 2023-08-25 22:09:40

First install Prism:

```bash
npm install prismjs;
```

In any Vue component import Prism, default CSS and execute a `highlightAll()` method on mounted hook:

```vue
<script setup>
import { onMounted } from 'vue';
import Prism from "prismjs";
import "prismjs/themes/prism.min.css";

onMounted(() => {
  Prism.highlightAll();
});
</script>

<template>
<pre><code class="lang-js"><span>const x</span> = <span>'hello world'</span>;</code></pre>
</template>
```

The code inside template tags is written manually using an online markdown to html converter, the original code is:

```js
const x = 'hello world';
```

Wrapped with three backticks and adding the language in this case "js", but this html could become from db or any API or CMS.

## Customize Prism Theme

In this repo you can find multiple very well known code themes: [prism-themes](https://github.com/PrismJS/prism-themes).

Just go to `themes` folder and copy the content of the desired theme (in my case dracula.css)

Create a file in `assets/css/dracula.css`

Instead of importing the default Prism styles, import in your Vue component custom theme CSS.

```js
import "assets/css/dracula.css";
```

## Import CSS theme globally

In `nuxt.config.ts` add the theme directly to avoid import it multiple times:

```ts
export default defineNuxtConfig({
  devtools: { enabled: true },
  css: [
      '~/assets/css/main.css',
      '~/assets/css/dracula.css'
  ],
```

As always thanks for reading and Happy Code!
Using namedtuple's to convert dicts to objects
Tags: python, dict, namedtuple
Published: 2023-08-25 18:57:39

---
title: Using namedtuple's to convert dicts to objects
published: true
date: 2023-08-25 22:06:00 UTC
tags: python,dict,namedtuple
canonical_url: https://www.codependentcodr.com/using-namedtuples-to-convert-dicts-to-objects.html
---

A friend shared this with me today and I thought it was pretty neat. If you have a dict, and you want to convert it to an object where the object properties are the keys from the dict, and the values are the values from the dict, you can use a namedtuple to do so. For example:

```
>>> some_dict = {"name": "My name", "func" : "my func"}
>>> import namedtuple
>>> SomeClass = namedtuple("SomeClass", some_dict.keys())
>>> as_an_object = SomeClass(**some_dict)
>>> as_an_object.name
'My name'
>>> as_an_object.func
'my func'

```

Won't handle nested dicts (the sub-dicts will still be dicts on the constructed object), but for a quick and dirty way to convert a dict to an object, this seems pretty handy.

Using the splat operator you can also save a line of code:

```
>>> as_an_object = namedtuple("SomeClass", some_dict.keys())(**some_dict)
>>> as_an_object
SomeClass(name='My name', func='my func')
```
AWS RE: INVENT 2023 ABW GRANT
Tags: awsreinvent, aws, grant, 2023
Published: 2023-08-25 22:04:48



![ABW receivers 2022](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zwi4f02s0yl5s9h2zatq.png)




What's up, everyone!!!!
Do you enjoy attending technology conferences?
Are you a budding IT professional?
Are you a technologist with fewer than 5 years of experience?!?!
Then look no further since the AWS All Builders Welcome Grant is now LIVE!
What exactly is the ABW Grant?
Individuals can attend the AWS Re: Invent conference for free thanks to this award. 

Program Benefits. Participants of the Program will receive the following benefits:

-A full conference pass to re: Invent 2023
- Roundtrip flight Las Vegas, NV
- 5 nights Hotel accommodations in Las Vegas, NV
-And other exciting prices at the event

You must be 21+ or older to apply for this grant.
This grant is open to EVERYONE on the earth who meets the aforementioned conditions. 
You CAN apply regardless of where you live. All builders are welcome.

[Apply for ABW grant now](https://pulse.aws/survey/L3FOOKM4?trk=ff59cd9d-0ad9-4bae-9d42-3a8df7e2f945)

Remember applications for the ABW Grant are now open and will close on September 1, 2023, at 11:59 PM (PDT).

If you have any queries about the application, please leave them in the comments section below.
Day 813 : I'm Good
Tags: hiphop, code, coding, lifelongdev
Published: 2023-08-25 22:02:35

_liner notes_:
- Professional : Pretty chill day today. Answered some questions from a team member. Fixed a styling issue that popped up when I demoed my application with a bunch more people joining that I did when doing it myself. Responded to a couple of more folks that reached out and then it was time to call it a half day.

- Personal : Damn... don't even remember what I did last night. haha Must still be getting over being sick. I'm feeling much better. I know I created the social media posts for the tracks I picked up on Bandcamp. Pretty sure I went through some tracks for the radio show. After that, not sure. haha Probably went to bed.

![View from a mountain top looking at other mountains going into the distance with a pretty green landscape under cloudy skies at sunset in Central Highlands, Czech Republic](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pjmbnaw16dlcpi1knusz.jpg)

Since it was a half day, I started working on the radio show early. Put together a bunch of tracks for the playlist. I'm trying to build up a good amount catalog tracks ready to go so I don't have to put together anything while I'm travelling. I'll have to see how many more I'll need to make sure I'm good. I'll be gone for 3 shows. I'll need do that this upcoming week because I'll be gone the following week. It'll be okay.

Have a great night and weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube XZDbT6xHZ3I %}
Full Stack Web Application
Tags: nextjs, tailwindcss, react, opensource
Published: 2023-08-25 21:57:56

Hi Everyone, I'm planning on building a Web Application using Nextjs, React, Tailwind. I have a couple of ideas in mind on what to build and would like to work on this project with a couple of people and gain new friends along the way. If you're interested, re ply with your discord username and we'll get started :)
Solving fake issues: Jira Connector Development
Tags: devops, bdd, productivity, ai
Published: 2023-08-25 21:27:17

Starting from scratch can be a puzzle, can't it? Even more of a head scratch-er if you only have some of the pieces! 
Here I am with a tool in the works ready to tackle Jira issues in an innovative way (more on that in earlier posts). But for this chat, let's sidestep those specifics. My aim? To guide you on tackling tasks from platforms like Jira, Assana, GitHub issues, and the like, even if you don’t have an actual company’s problems at hand.

## Ready?
Ive done all the pondering already so you don't have to, go setup a Jira 

![Setting up jira free plan](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16fbys93rrqybhkkctpz.png)

Go ahead and setup a free Jira for your org, mine is Amalgam (that’s the name of the tool I’m writing).

Now then just select the basics when prompted.

## Now what?
I have a board, its empty, I need to populate it with junk so that my tool can solve problems that my real customers would face, I have no time for this... Oh ChatGPT, come here a sec!

### Prompts
```
User
I am writing a tool that needs to consume Jira issues, I need a fake project idea and a issue to raise, make sure its a bit silly and animal related.
```
It gave me something complex so I said

```
User
make it a todo list
```

Its very important to choose a ridiculous idea that is very narrow in scope such as a todo list, because these are our new test cases, we understand what a todo list is. we need to understand a tiny bit about what the fake company is so we can sense check. The plan is to use our new tool and test against this test case company and its issues.

I suggest creating one bug and one feature or whatever you might need, you will need to enable those issue types.

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

### A bug
Ask ChatGPT to create your first bug. Be aware that it may mention attachments; such as customer complaint screenshots, if your tool is going to use images, you need to mock those, I suggest getting it to write that for you and then fake it to look real like mocking it into a Zendesk style UI.

### A Feature
It might mention a flowchart attachments this time, ask it to provide a serialized flow chart and ask it to suggest a way to generate the image - many things can be serialized you would be surprised.

For every rich detail it gives you... it will present you with problems, you don`t have to solve them yourself.

## The end
I now have my Jira test cases, now I can go and write my Amalgam SaaS tool :D