teleren/devto huggingface dataset:
Elixir Task, Task.Supervisor - Another way to work with Elixir process
Tags: elixir, task, supervisor
Published: 2024-07-06 04:29:02

## Intro

If you just jump to Elixir from other languages, process & supervisor is one of many things you need to understand to fully take advance of  Elixir.

For newbie can work easy with process, Elixir provides `Task` & `Task.Supervisor` to help us work with Elixir process.

## Task

`Task` is high level abstract to work with process. We can create a process to execute a task and get result without boilerplate code (for spawn & get result).

Not same as `GenServer` (much more simply) `Task` just provides a simple way to execute a function (anonymous fn or define in a module). We must care our state & loop function if need a long-run task.

`Task` is quite simple for both cases, using directly or define a module.

For start directly we can use like:

```Elixir
# create a task in other process.
task = Task.async(fn ->
  # execute a task.
end)

# do something.

# get result
result = Task.await(task)
```
We can use `await_many` for case we need to wait two or more tasks.

We can see a flow to create & wait a task:

![Task flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vdwahc6egws4y3crkv6t.png)

We can see to execute a function as process and get result is only in two functions call.

Remember our task create by `Task.async` will linked with current process (parent) then if task is crashed or current process is crashed other process will die follow (if we don't want a link, can use `async_nolink` in `Task.Supervisor`).

We can use task as a child in supervisor by simple `use Task` in our module like:

```Elixir
defmodule PermanentTask do
  use Task, restart: :permanent

  def start_link(arg) do
    Task.start_link(__MODULE__, :run, [arg])
  end

  def run(arg) do
    # ...
  end
end
```

Then we can add to our supervisor like:

```Elixir
Supervisor.start_link([
  {PermanentTask, arg}
], strategy: :one_for_one)
```

As we see, if we need add a simple task then `Task` can help us reduce complex things like self define process or implement a `GenServer` for supervisor (I have other posts for explaining [GenServer](https://dev.to/manhvanvu/genserver-a-simple-way-to-work-with-elixir-process-364p) and [Supervisor](https://dev.to/manhvanvu/elixir-supervisor-a-powerful-thing-for-dev-devops-can-sleep-well-4ge7)).

`Task` can return a stream by using `async_stream` for case we need to work with stream.

For case we want to ignore we can call `ignore/1` to unlink a running task (task's still running).

For case we need check status of unlinked task we can use `yield/2` & `yield_many/2`.

## Task.Supervisor

Elixir provides a supervisor for `Task` to work & manage dynamically tasks (support to create remote tasks).

```Elixir
children = [
  {Task.Supervisor, name: OurApp.TaskSupervisor}
]

Supervisor.start_link(children, strategy: :one_for_one)
```

And at runtime we can add async task like:

```Elixir
task = Task.Supervisor.async(OurApp.TaskSupervisor, fn ->
  # execute a task.
end)
```

For case we need to create a lot of tasks we can use `Task.Supervisor` with partition to avoid bottleneck.
Precedência de operadores
Tags: java, javaprogramming
Published: 2024-07-06 04:21:32

Aqui está um resumo da tabela de precedência dos operadores Java:

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

**Mais alta:**
Operadores de incremento e decremento pós-fixo (++, --).
Operadores de incremento e decremento prefixo, unários (+, -, ~, !), e coerção de tipo.

**Alta:**
Multiplicação, divisão, e módulo (*, /, %).

**Intermediária:**
Adição e subtração (+, -).
Deslocamentos de bits (>>, >>>, <<).
Comparações (>, >=, <, <=, instanceof).
Igualdade (==, !=).

**Baixa:**
AND bit a bit (&).
XOR bit a bit (^).
OR bit a bit (|).
AND lógico (&&).
OR lógico (||).
Operador ternário (?:).

A precedência de operadores refere-se à ordem em que as operações são realizadas dentro de uma expressão. Quando você escreve uma expressão com múltiplos operadores, a precedência determina quais partes da expressão são avaliadas primeiro. Isso é especialmente importante em expressões complexas para garantir que o resultado seja o esperado.

Exemplo de Precedência de Operadores

Considere a expressão:
```
int result = 3 + 5 * 2;

```
De acordo com a precedência dos operadores, a multiplicação (*) tem uma precedência mais alta do que a adição (+). Portanto, a expressão é avaliada como:

```
int result = 3 + (5 * 2); // result = 3 + 10
```
O resultado final é:

```
int result = 13;

```

**Outro Exemplo com Parênteses**
Se você quiser alterar a ordem de avaliação, pode usar parênteses para forçar uma ordem diferente:

```
int result = (3 + 5) * 2;

```
Neste caso, a adição é realizada primeiro porque os parênteses têm a precedência mais alta:

```
int result = 8 * 2; // result = 16

```
**Importância da Precedência de Operadores**
Compreender a precedência dos operadores é crucial para escrever expressões corretamente e evitar erros lógicos no seu código. Isso garante que as operações sejam realizadas na ordem desejada sem a necessidade de parênteses desnecessários, tornando o código mais legível e eficiente.
The first 90 days
Tags: career, careerdevelopment, challengecareer
Published: 2024-07-06 04:10:08

> **
> **My Ideas for Advancing in the New Work Area****

1. **Dream Fulfilled:**
   - Initially, working in the investment field was a dream come true for me, especially as an economist.
   - My prior experience in data & analytics allowed me to quickly contribute to the team.

2. **Communication and Guidance:**
   - Now, I can communicate better with people and assist them in decision-making.
   - This interaction provides me with more experience and brings me closer to my goal of becoming a coordinator.

3. **Engaging with Leadership:**
   - Leadership has been receptive to my ideas and insights about the business.
   - We are focused on improvement and achieving our objectives.

4. **Challenges and Learning:**
   - Redefining the team's activities was an initial challenge.
   - Despite difficulties, I sought support from colleagues and did my best.

5. **Autonomy and Contribution:**
   - My leadership provides autonomy, responsibilities, and trust.
   - Joining the climate team presents challenges, but my experience will be valuable.

6. **Ideas & Innovations:**
   - I want to explore visual tools with modern indicators and dashboards, ensuring that as many people as possible can access data on AWS and use data manipulation tools and report creation to address their data-related pain points and generate insights.
   - Staying updated on data governance and technology trends is crucial.
   - Proposing new meeting formats, such as smaller groups with leaders, can strengthen our data agenda.
   - Initiatives like in-person brainwriting forums, benchmark agendas, and a monthly delivery journal can drive the team forward.
   - I also aim to contribute to agile methodology evolution and bridge the gap between technology and data leadership.
   - Encouraging internal training and improving communication are vital goals, including advocating for a weekly study hour per person.
   - Finding effective ways to ensure people read and understand relevant emails remains a challenge.
   - Collaborating on the evolution of analytics by design, especially with leadership, as they serve as the entry point for this topic among team members.
   - Leveraging artificial intelligence to enhance creativity and efficiency, providing daily support.
   - Enhancing internal processes by documenting critical information necessary for smooth operations, benefiting our clients and readers.

7. **People Development:**
   - I contribute to the development of three individuals: two interns and one analyst seeking new challenges.
 🚀😊

---


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zay5cevc1rjvgdhtqzv9.jpeg)
Os primeiros 90 dias
Tags: job, career, changemanagement, beginners
Published: 2024-07-06 03:51:55


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uag270ieduzz1p23iqof.jpeg)
**Minhas Ideias para Evoluir na Nova Área de Trabalho**

1. **Sonho Realizado:**
   - Inicialmente, trabalhar na área de investimentos foi um sonho para mim, especialmente por ser economista.
   - Minha experiência prévia em dados & analytics me permitiu contribuir rapidamente com a equipe.

2. **Comunicação e Direcionamento:**
   - Agora, consigo me comunicar melhor com as pessoas e ajudá-las nas tomadas de decisão.
   - Essa interação me proporciona mais experiência e me aproxima do objetivo de me tornar coordenadora.

3. **Interação com a liderança:**
   - A liderança tem sido receptiva às minhas ideias e percepções sobre o negócio.
   - Estamos focados em melhorar e atingir nossos objetivos.

4. **Desafios e Aprendizado:**
   - Redefinir as atividades da equipe foi um desafio inicial.
   - Busquei apoio de colegas e fiz o meu melhor, mesmo com as dificuldades.

5. **Autonomia e Contribuição:**
   - Minha liderança me proporciona autonomia, responsabilidades e confiança.
   - A entrada no time de clima apresenta desafios, mas minha experiência será valiosa.

6. **Ideias & evoluções:**
   - Quero explorar ferramentas visuais com indicadores e painéis modernos, e que o máximo de pessoas saibam consultar dados na AWS e que saibam usar ferramentas de manipulação de dados e criação de relatórios que resolvam suas dores em obter dados e geração de insights.
   - Acompanhar as novidades em governança de dados e tecnologias é essencial.
   - Propor novos formatos de reuniões, como grupos menores com líderes, pode fortalecer nossa agenda de dados.
   - Iniciativas como fóruns presenciais de brainwriting, agendas de benchmark e um jornal mensal de entregas podem impulsionar a equipe.
   - Também desejo contribuir para a evolução da metodologia ágil e aproximar as áreas de tecnologia e diretoria de dados.
   - Incentivar a capacitação interna e melhorar a comunicação são metas importantes, e convencer os líderes de implantarem uma quantidade de horas de estudo por semana por pessoa.
   - Encontrar maneiras eficazes de garantir que as pessoas leiam e compreendam e-mails relevantes é outro desafio.
   - Colaborar na evolução da agenda de analytics by design, principalmente lara a liderança, pois eles serão a porta de entrada do assunto para os colaboradores.
   - Uso de inteligência artificial para aumento da criatividade e assertividade, sendo apoio nas atividades diárias.
   - Melhorar os processos internos, documentando tudo o que é mais importante e necessário para o andamento das atividades e para que nossos clientes e leitores tenham todas as informações necessárias rapidamente.

7. **Desenvolvimento de pessoas:**
   - Contribuição e apoio no desenvolvimento de 3 pessoas: 2 estagiárias e 1 analista que busca novos desafios.
 🚀😊
call, apply, bind
Tags: javascript, call, apply, bind
Published: 2024-07-06 03:46:17

### **call** 
**Why do we use call?**
We use **call** when we want to borrow a function from one object and use it with another object.

**What is call?**
**call** is a way to use a function with a different object, pretending that object owns the function.

**How does call work?**
You take a function from one object and call it with another object, telling the function, "Hey, use this other object as your **this**."

**Example:**
Imagine you have two friends, Alice and Bob. Alice knows how to introduce herself, but Bob doesn't. You can help Bob introduce himself using Alice's way.

```
const alice = {
  name: 'Alice',
  introduce: function(greeting) {
    console.log(`${greeting}, my name is ${this.name}`);
  }
};

const bob = { name: 'Bob' };

alice.introduce.call(bob, 'Hello'); // Output: Hello, my name is Bob
```
### **apply**
**Why do we use apply?**
We use **apply** for the same reason as **call**, but when we want to pass arguments as an array.

**What is apply?**
**apply** is similar to **call**, but it takes arguments in an array instead of individually.

**How does apply work?**
You take a function from one object and call it with another object, giving the arguments as an array.

**Example:**
Imagine you want to introduce Bob, but this time you want to say both "Hello" and "Nice to meet you" at once.

```
const alice = {
    name: 'Alice',
    introduce: function(greetings) {
        const fullGreeting = [...greetings]
        console.log(`${fullGreeting[0]}. My name is ${this.name}. 
        ${fullGreeting[1]}`);
    }
  };

alice.introduce.apply(bob, ['Hello', 'Nice to meet you']); // Output: Hello, my name is Bob
```

### **bind**
**Why do we use bind?**
We use **bind** when we want to create a new function that always uses a specific object as **this**.

**What is bind?**
**bind** creates a new function that remembers which object should be **this** when it's called.

**How does bind work?**
You create a new version of a function that always uses the same **this** value.

**Example:**
Imagine you want to help Bob introduce himself later, but you want to make sure he does it the right way every time.


```
const bobIntroduce = alice.introduce.bind(bob);

bobIntroduce('Hi'); // Output: Hi, my name is Bob
bobIntroduce('Hey there'); // Output: Hey there, my name is Bob
```


**Summary with a Simple Story**
Imagine you have a magical talking toy named Toy that can say things. Toy belongs to Alice, and it can say her name. You have another toy that belongs to Bob, but it doesn't know how to talk.

**call:** You tell Toy, "Say Bob's name using your voice," and it says, "Hello, my name is Bob."
**apply:** You tell Toy, "Say Bob's name and also 'Nice to meet you' using your voice," and it says, "Hello, my name is Bob. Nice to meet you."
**bind:** You create a new version of Toy that always knows it's talking about Bob. Whenever you tell this new toy to talk, it says, "Hi, my name is Bob."
These magical talking toys are just like functions in JavaScript, and **call**, **apply**, and **bind** help you control which toy is talking!
JavaScript NaN - advanced JS interview question
Published: 2024-07-06 03:31:47

In JavaScript, NaN means "not a number." If you run

`typeof NaN   // number`

you will get "number" because NaN is used to define a number that really isn't a number. 

Many times when we code we need to be sure that the data type we are working with is actually a number. JS has a built in method called isNaN that will accept any input and let you know if it's not a number. Let's take a look at a few examples:

```
isNaN(1)    // false   1 is not not a number

isNaN("A")   // true   "A" is not number

isNaN("1")   // false  "1" is not not a number ..... wait what? 
```

The string "1" is a number? That's what JS is telling us. But anything in quotation marks is for sure Not a Number because anything in quotation marks is a _string_. If you run `typeof "1"` you will get string. The thing to understand here is that isNaN is doing [implicit coercion](https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion) "behind the scenes." It is first calling Number("1"), which turns "1" into 1, and then running isNaN(1). 

```
isNaN(Number("1"))    // false because it is a number now that it's been coerced.
```
Great, so basically isNaN isn't going to be very useful unless we are 100% sure of the input type, but in a [dynamically typed language](https://developer.mozilla.org/en-US/docs/Glossary/Dynamic_typing), how can you ever really be sure? That's exactly why we need a foolproof way to check. Is there a way to **_guarantee_** that some input is truly not a number? Yes, and we can really impress our interviewers by showing them our deep understanding of JS. 

Firstly, in JS, anything compared to itself is true.

```
a = 1;
a === a;   //true 
b = "B";
b === b;   // true
```

and NaN compared to anything else will be false.

```
NaN === 1   // false  
NaN === false    // false
NaN === "b"   // false


```

Ok. So far so good. This makes perfect sense. So NaN compared to itself is going to be true then, right? Nope.

```
NaN === NaN    //false
```
What? Ok, that's weird, but could we use this to our advantage to ensure something is a number?  If we know that only in this one situation of something being NaN will the comparison to itself fail, we can simple compare any variable in question to itself with the !== operator and if we get "true" we know that our input is NaN.

```
a = 1
a !== a  // false because 1 === 1

a = NaN
a !== a   // true
```

If 'a' is anything other than NaN, the !== will **_always_** be false. But due to the strange truth that NaN === NaN is false, a !== a will be true. 

Your deep knowledge of the inner workings of JS will surely impress! Now go use [Number.isNaN()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN). It's far more readable and understandable.
Day 12 of Studying AWS
Published: 2024-07-06 03:30:01


I successfully created a 2 GB EBS (Elastic Block Store) volume and attached it to my EC2 instance (server). Then, I made a snapshot of the EBS and loaded a copy of that onto another instance I created.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/43yrwtu78mklwrw3necq.png)
Deploying an Application on Azure: Guide
Published: 2024-07-06 00:33:57

In today's world of cloud computing, Microsoft Azure stands out as one of the leading platforms enabling developers and businesses to deploy applications efficiently and at scale. This article will guide you through the essential steps to deploy an application on Azure, from initial setup to production deployment.

###Step 1: Creating an Azure Account

Before you begin, you'll need a Microsoft Azure account. If you don't have one yet, you can sign up at azure.microsoft.com and create a free or paid account depending on your needs.

###Step 2: Creating a Resource Group

In Azure, a Resource Group acts as a logical container that groups related resources for an application. Follow these steps to create one:

1. Sign in to the Azure Portal.

2. Click on "Create a resource" in the side menu.

3. Select "Resource group" and click on "Create".

4. Fill in the details such as the resource group name, region, and then click on "Review + Create" and finally on "Create".

###Step 3: Creating a Web Application (Example with Azure App Service)

Azure App Service allows you to deploy and scale web applications quickly and easily. To create one:

1. In the Azure Portal, select your newly created Resource Group.

2. Click on "Add" to add a new resource.

3. Search for "App Service" and select "Create".

4. Complete the details such as application name, development stack (e.g., .NET, Node.js), and service plan (consumption plan or an App Service plan).

5. Click on "Review + Create" and then on "Create".

###Step 4: Application Deployment

Once your App Service is configured, you can deploy your application:

1. Open the settings of your App Service from the Azure Portal.

2. In the "Deployment" section, choose the option that best fits your application (e.g., FTP, GitHub, Azure DevOps).

3. Follow the instructions to connect your repository or upload your 
code.

###Step 5: Configuration and Management

Azure offers various tools to configure and manage your application:

- **Application Settings:** Adjust environment variables, connection settings, and more from the Azure Portal.


- **Monitoring and Scaling:** Use Azure Monitor to track your application's performance and adjust scaling as needed.


- **Security:** Implement security measures such as SSL certificates, multi-factor authentication, and access policies.

###Step 6: Optimization and Maintenance

Once deployed, optimize your application to improve performance and ensure it stays updated with the latest software versions and security patches.

Deploying applications on Azure not only enhances accessibility and scalability through its diverse service options but also streamlines operational efficiencies and enhances security protocols. With this guide, you now possess a robust foundation to harness Azure's cloud capabilities effectively, enabling seamless project expansion and innovation while ensuring optimal performance and reliability across your applications.
Object.defineProperty()
Published: 2024-07-06 03:06:11

The `Object.defineProperty()` method in JavaScript allows you to define or modify a property directly on an object and control the property's behaviour. It provides fine-grained control over the properties of objects, including whether they are writable, enumerable, or configurable.

Syntax
```
Object.defineProperty(obj, prop, descriptor);
```
- `obj:` The object on which to define the property.
- `prop:` The name of the property to be defined or modified.
- `descriptor:` An object that describes the property being defined or modified.

### Property Descriptors
A property descriptor is an object that can contain the following keys:

- `value`: The value associated with the property (data descriptor).
- `writable`: Boolean indicating if the property value can be changed.
- `configurable`: Boolean indicating if the property can be deleted or changed.
- `enumerable`: Boolean indicating if the property will be listed during enumeration of the properties (like in a for...in loop).

### Examples
**Basic Example**
Let's create an object and define a new property on it using `Object.defineProperty()`.

```
const person = {};

// Define a property 'name' on the person object
Object.defineProperty(person, 'name', {
  value: 'Alice',
  writable: true,
  enumerable: true,
  configurable: true
});

console.log(person.name); // Output: Alice
```
**Making a Property Read-Only**
You can use `Object.defineProperty()` to make a property read-only by setting `writable` to `false`.

```
Object.defineProperty(person, 'age', {
  value: 30,
  writable: false,
  enumerable: true,
  configurable: true
});

console.log(person.age); // Output: 30

person.age = 25; // This will not change the value of age
console.log(person.age); // Output: 30
```
**Making a Property Non-Enumerable**
You can make a property non-enumerable by setting `enumerable` to `false`.

```
Object.defineProperty(person, 'gender', {
  value: 'female',
  writable: true,
  enumerable: false,
  configurable: true
});

console.log(person.gender); // Output: female

for (let key in person) {
  console.log(key); // Output: name, age (gender is not listed)
}
```
**Summary**
`Object.defineProperty()` gives you detailed control over the properties of an object. You can control whether a property is writable, enumerable, configurable, and even define custom getters and setters. This makes it a powerful tool for creating complex and well-encapsulated objects in JavaScript.
日本語 ChatGPT 2024: 新しい対話の先へ
Tags: webdev, javascript, beginners
Published: 2024-07-06 03:00:31

近年、人工知能の発展により、私たちの日常生活はますます便利で魅力的なものになっています。その一環として、OpenAIが開発した最新の日本語 ChatGPT 2024は、その先駆的な存在として注目されています。このエッセイでは、そのユニークな機能、美しいインターフェイス、そして高速で自然な応答能力に焦点を当てて紹介します。

詳細については、以下を参照してください。: [ChatGPTJapanese](https://chatgptjapanese.net/)


ユニークな機能の充実
日本語 ChatGPT 2024は、多くのユニークな機能を備えています。まず、その多言語対応が挙げられます。これにより、世界中のユーザーが自分の言語で自然な会話を行うことができます。また、AIの理解力が向上し、会話の文脈を理解してより賢く応答します。例えば、複数の質問を一度に処理したり、特定の情報を継続して追跡したりする機能があります。

美しいインターフェイスとアクセシビリティ
日本語 ChatGPT 2024は、使いやすさと美しさを兼ね備えたインターフェイスを提供しています。直感的なデザインにより、誰もが簡単に操作でき、必要な情報に素早くアクセスできます。視覚的に魅力的な要素が取り入れられ、長時間の使用でも疲れにくい設計となっています。

高速で自然な応答能力
このプラットフォームの最も優れた特性の一つは、その超高速で自然な応答能力です。ユーザーの質問や要求に対して、ほとんど遅延なく適切な回答を提供します。これは、AIの処理能力の向上と、高度な自然言語理解技術の結果です。例えば、会話の流れを途切れさせることなく、継続して意味のある対話を展開することができます。

結論
日本語 ChatGPT 2024は、その先進的な技術と使いやすさにより、現代のコミュニケーションに革新をもたらしています。ユーザーはその美しいインターフェイスを通じて、いつでもどこでも賢い会話相手として活用できます。AIの未来は明るく、ChatGPT 2024のような技術がもたらす可能性は無限大です。

接触

会社名：ChatGPT Japanese - ChatGPT 日本語

市区町村：東京都渋谷区

国: 日本

郵便番号：150-0022

電話番号：+81 80-1234-5678

メール：chatgptjapanese@gmail.com

Google Map：東京都渋谷区恵比寿南1-2-3

#日本語チャットgpt #日本語チャットgpt #無料チャットgpt