teleren/devto huggingface dataset:
Poetry — Gerenciamento de dependências em Python!!
Tags: python, poetry, env, datascience
Published: 2022-09-12 14:59:18

Quando se trata de gerenciamento de dependências de software a conversa costuma ser curta e bem direta. Isso é o normal na maioria das linguagens de programação existentes atualmente, porém com python, é diferente. Existem hoje diversas opções que podemos utilizar para fazer este gerenciamento de dependências para a linguagem python. Conda, Pip, Virtualenv, Pipenv são gerenciadores bem conhecidos para fazer esse controle de dependências. Contudo, não é sobre nenhuma dessas que abordaremos hoje, mas sim sobre o Poetry.

Criado por Sébastien Eustace em 2018, o Poetry surge para tentar trazer soluções que foram deixadas de lado por gerenciadores antigos. Ele permite que você declare as bibliotecas das quais seu projeto depende e assim tudo será gerenciado para você.

## Instalação do Poetry

### Linux

```
curl -sSL https://install.python-poetry.org | python3 -
```

### Windows

```
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py -
```

## Principais comandos

Agora que já temos o Poetry instalado, vamos iniciar criando um novo projeto para desenvolvermos. Para isto, basta fazer:

```
poetry new project
```
E este comando gera o seguinte arquivo para a gente. Todas as pastas já criadas inclusive de testes e o pyproject.toml, que é o arquivo que orquestra todo o seu projeto e todas as suas dependências.

```
project
├── pyproject.toml
├── README.md
├── project
│   └── __init__.py
└── tests
    └── __init__.py 
    └── test_project.py
```

Para instalar todos as bibliotecas presentes no seu pacote, basta escrever o comando:

```
poetry install
```
Esse comando além de instalar todas as dependências também criará um arquivo chamado **_poetry.lock_** que irá listar todas as dependências do seu projeto e as versões que elas estão.

E por fim, vamos ver como podemos adicionar uma nova dependência. Para isso, é bastante simples, basta escrevermos no terminal:

```
poetry add nome_da_dependência
```

## Conclusão

E isso é tudo pessoal. No artigo de hoje vimos um pouco sobre o Poetry e seus principais comandos para podermos gerenciar dependências com python. Como mostrado é tudo muito simples e muito “intuitivo”. Para saber um pouco mais afundo sobre o Poetry e diversos outros comandos que ele possui, basta acessar a [documentação](https://python-poetry.org/docs/).

Até a proxima!!!
How to easily use CKEditor in your Django project
Tags: webdev, django, python, ckeditor
Published: 2022-09-12 14:55:47


A **CKEditor** is a **WYSIWYG HTML** editor that can fit a wide range of use cases: from word-like documents with large toolbars to simple toolbars.

**WYSIWYG** here is an acronym for **what you see is what you get;** this is a feature that enables user to see and edit content in a form that appears as it would when displayed on an interface

In a nuthsell **CKEditor** gives you more text formatting options when working with your **HTML** text area.

To get the best out of this library, first you need to have Django and Python running on your server next, `pip install django-ckeditor`

After installing the `django-ckeditor` library import the library to your models and make a few adjustments to your models

`models.py`
```
from ckeditor.fields import RichTextField
```
Django model has two main fields `CharField` and `TextField` but for the purpose of this tutorial we'll be making use of CKEditor's `RichTextField`, include the following line of code to your custom model

```
text = RichTextField(null=True, blank=True)
```
As normal practice whenever changes are made to a model we `makemigrations` and `migrate`

After migrating our model into our application we add a little tweak to our `settings.py` file

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

Lastly, login into your admin panel and preview your modified models you should be able to see the new changes on your admin page.

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

to effect the changes on your frontend view form you need to load the `ckeditor` form media tag

So, just above where you `{{form.as_p}}` tag is located also include `{{form.media}}`

and boom just like that your formatted text editor is ready to use.
Adding Unique Outcomes With Random Numbers
Tags: rails, javascript, programming, beginners
Published: 2022-09-12 14:54:46

## The Idea
I decided to create a rogue-like text based adventure game for my final capstone project while I was in Flatiron. It was a ton of fun, and a good learning experience. I was challenged to find ways to keep elements randomized but not to the point that the game would be impossible. It helped me grow my understanding and ability in Ruby as well as React.

## Getting Started
Most coding languages have a nice and easy way to create a random number upon being called. This is a great start but has some issues. One is if you want a progression system you will have to tweak your formula in order to things relevant to your progression. There are many different approaches to this problem. Here I am going to show how I tackled this issue.


## Basic Set Up
In my game I was allowing a user to create a character, I wanted their starting stats to be randomized but within a range. Ruby makes this super easy.
`rand(3..8)
 rand(3...8)
`
Both of these methods allow us to create a random number within the range specified. The difference between them are .. runs from the beginning to the end inclusively where as ...  excludes the end value. This is an easy solve and doesn't require and additional logic to be checked.


## Next Challenge
Now I wanted to be able to present that character with a encounter and an enemy to fight. This is where it gets a bit tricky but not crazy. For the encounter I set a Round to be incremented and then checked, with a simple case statement. When the round was 1..3 I would select from a sorted array of encounters by index, and then just repeated that till round 12. For the enemy spawn It was basically the same thing. Sort enemies by power and then select weaker enemies when the round was low and stronger enemies when the round was higher.

## Loot
What would the game be without loot? Now I wanted to create a chest system that would reward completed encounters with loot. I was able to solve this using most of the same logic from my encounter and enemy logic so that was a nice moment. When could you wrote before was reusable for another function with just some minor modifications. The game itself is linked in linkedin profile which can be found at jeremy-francis-klofnod on linkedin. Feel free to reach out and ask and questions or comments you have about the project
Like a GIF For Your Yard
Tags: adventofcode, algorithms, programming, javascript
Published: 2022-09-12 14:48:28

## [Advent of Code 2015 Day 18](https://adventofcode.com/2015/day/18)

### Striving for 4/4 stars
- I skipped today's puzzle to complete Day 6
- Thankfully, Day 6 was relatively easy, and I earned two stars
- I hope I can earn two stars today, too
- Let's do it!

## Part 1
1. The origin of this puzzle theme?
2. Writing a working algorithm

### The origin of this puzzle theme?
- In years past, this puzzle theme occurred around the same time: Days 15-25
- This puzzle's instructions feel comprehensive and introductory
- Making me think that today's puzzle was the first of its kind in this first year of puzzles
- I'm just glad it's not the first time I'm encountering it
- To the contrary, it seems very doable given all my previous successful encounters

### Writing a working algorithm
Parsing the input into a grid of nested arrays:
```js
input.split('\n')
     .map(line => line.split(''))
```

Relative coordinates of all eight adjacent cells:
```js
adjacents = [
  [-1,-1],
  [-1, 0],
  [-1, 1],
  [ 0,-1],
  [ 0, 1],
  [ 1,-1],
  [ 1, 0],
  [ 1, 1]
]
```

Iterate through each of the 10,000 cells in the grid:
```js
for (let row = 0; row < grid.length; row++) {
  for (let col = 0; col < grid[row].length; col++) {
    // access each cell
  }
}
```

Count `on` and `off` lights in adjacent cells:
```js
let neighbors_on = adjacents.map(coord => 
  grid[row + coord[0]] == undefined || 
  grid[row + coord[0]][col + coord[1]] == undefined
  ? 0 : grid[row + coord[0]][col + coord[1]] == '#'
  ? 1 : 0
).reduce((lights_on, current) => lights_on + current)
```

Queue up each light that must change:
```js
let changers = []

if (grid[row][col] == "#" && ![2,3].includes(neighbors_on)) {
  changers.push([row, col, "."])
} else if (grid[row][col] == "." && neighbors_on == 3) {
  changers.push([row, col, "#"])
}
```

Return the count of lights that are `on`:
```js
return [
  ...grid.map(
    el => el.join('')
  ).join('\n')
  .matchAll(/#/g)
].length
```

It generated the correct answer for my puzzle input!

## Part 2
1. Another disappointment
2. One more loop in each iteration

### Another disappointment
- Much like with Day 6, I was hoping there would be a message or picture revealed after a certain number of light-changing rounds
- Instead, just a simple change to the rules and another count after the same number of iterations

### One more loop in each iteration
The list of four corner coordinates:
```js
let corners = [[0,0],[99,0],[99,99],[0,99]]
```

Ensuring each one is left on at the end of each iteration:
```js
corners.forEach(coord => {
  grid[coord[0]][coord[1]] = "#"
})
```

It generated the correct answer for my puzzle input!

## I did it!!!!
- I solve both parts!
- Thus, I earned all four stars from each part of both days!
- I wrote yet another adjacent-cell checking, queuing and changing algorithm!
- I [built a simulator](https://aoclikeagifforyouryard.rmion.repl.co/) to re-create the light show!
Ask Me Anything about Code Reviews
Tags: webdev, programming, discuss, ama
Published: 2022-09-12 14:48:09

## We are interviewing former AWS engineer and creator of "Master the Code Review", [Curtis Einsmann](https://twitter.com/curtiseinsmann). What should we ask him? 

Hi Dev.to community, let's start an AMA thread.

On September 20th, we will have a live talk: **“Becoming a Code Review Master”**, with Codacy CEO Jaime Jorge and guest speaker Curtis Einsmann, a software engineer at Gumroad and previously six years at Amazon Web Services. Curtis is an advocate of empathic and effective code reviews, and is passionate about helping developers and organizations level up in that space.

What would you like to ask him? Post your questions in the comments.

:point_right: Save your spot for the live talk [here](https://us02web.zoom.us/webinar/register/8816627433311/WN_TcLTok1jTamydt426Kklsg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lg126u5mlpbqzeqpkany.png)
What are your Goals for the week? 9/12
Published: 2022-09-12 14:28:55

It's Monday, so what are your plans for this week?

- What are your plans for the week?   
- What are you building? 
- What will be a good end result by week's end?

**My Goals**

- I was at an non tech event over the weekend. I need to process the pictures I took and add the content to a website. 
- Finish prepping a repo to help demo a side project.
- Continue on the job search.
- Work some code challenges.
- Create some CSS art and blog about it.
- Make a cover image for this series. 

Update:
- Attend Frontend Foxes virtual event, tweet about it, possibly write blog post one it.  
- Possibly attend a couple local meetups. 



```
-$JarvisScript git push
```
Music Monday — What are you listening to? (Homeland Edition)
Tags: watercooler, discuss, music
Published: 2022-09-12 14:26:21

_cover image source: [Liotta Seoul](https://giphy.com/Liotta-Seoul/)_ 

**Alright alright! So, this week the focus is gonna be on sharing music from your native, home land. You can take that prompt however you wanna... home could be where you were born, where you currently live, where you lived most of your life... It could also be your home country, state, province, city, town, etc. Alternatively, maybe you just have a song that reminds you of home? That's fair game too. Whenever sharing your choice please just let us know why this music is your choice!**


![The words "Home is where the computer is"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/15jxnyuop7jnpbx28wi8.gif)

***

## How we do 

In this weekly series, folks can chime in and drop links to whatever it is they've been listening to recently + browse others suggestions.

If you like talking about music, consider following the org [#music discussions](https://dev.to/music-discussions) for more conversations about music!

{% embed https://dev.to/music-discussions %}

***

So, wanna share some tunes that make you feel at home? _Note: you can embed a link to your song on most platforms using the following syntax `{% embed https://... %}`._

I look forward to listening to y'all's suggestions! 👂 🎶
Why you Should Participate in Hacktoberfest
Published: 2022-09-12 14:05:50


![Hacktoberfest logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lnps44exy96bfkoym6je.png)
Hacktoberfest is just around the corner. [Hacktoberfest](https://hacktoberfest.com/) is a yearly event put on by DigitalOcean. Open source projects take contributions from anyone and the first 40,000 participants who complete Hacktoberfest (complete = four separate changes to projects that get accepted) earn either a shirt or a tree planted in their name. It's September now and you have time to prepare to jump into the fun.

Why should you participate in Hacktoberfest?

### 1. Make a difference.

You'd be surprised how much small changes mean for a project. The more a project scales, the easier it is for small errors to live within it. You can correct documentation, edit files that have typos, and make a meaningful difference in tech.

While fixing typos may be seemingly insignificant, across hundreds of thousands of projects, the more people do it, the more accurate and production ready open source becomes as a whole.

### 2. Find community.

The people who run and actively contribute to open source are amazing (almost always!). Many open source projects have a Discord or Slack for folks to socialize and share links, etc.

I've contributed to multiple open source projects and enjoyed talking with maintainers and contributors. One community that I joined earlier this year was [Novu](https://novu.co/).

Another awesome part of open source is pairing with someone else (I talk more about my [pairing experience here](https://dev.to/alexcurtisslep/fall-in-love-with-open-source-aib)). This gets you chatting with someone who may know more than you, or at least wants to talk it out and work towards a solution.

While working through issues I was having on my local version of the project, we talked about where we live and how each place would be a great place to visit (among other things).

No matter how technical or not technical you feel you are, you can find people with common interests! The possibilities are endless for what that could do for you. You could land a job, experience a different country or town like you never have before, or finally find someone else who feels just as passionate about pickleball (for example) as you!

### 3. Discover newfound passion.

When you go down a new street, you might discover a new coffee shop that has a terrific atmosphere and views. Similarly when contributing to projects that you may not have been exposed to before, you might find you love machine learning, computer vision, or making sure all the tests pass when you're squashing a bug!

People tend to think that coding is only for a specific subset of individuals. The beautiful part about Hacktoberfest is it presents a chance for people from all walks of life to take off that veil and test the technical waters.

While your contributions don't have to be incredibly technical, be open minded, take the plunge, and see how you go!
Expressões Regulares III - âncoras, limites de palavras e caracteres de palavras
Tags: regex, beginners, expressoesregulares, pcre
Published: 2022-09-12 14:00:42

## Âncoras
"Âncora" é o nome que damos para os caracteres `^` e `$`. `^` significa o início da linha e `$` significa o fim da linha.
Então se eu tiver a seguinte regex

`^[Tt]este`

e aplicá-la ao seguinte texto

```
Teste unitário é um tipo de teste que visa testar
apenas uma unidade de código, como um fluxo determinado de
uma função.
```

A regex vai dar match apenas no primeiro `Teste` porque ele está no início da linha, representado pelo `^`. A mesma coisa acontece com `$`.

A regex
`nunca$`
aplicada no texto
```
Lembre-se, nunca diga nunca
```
vai dar match somente no segundo `nunca`.

## Limites de palavras
`Limites de palavras` é o nome que damos ao caracter especial `\b`. Ele serve para darmos match no início ou no final de uma palavra.

A regex
`\bvel`
aplicado sobre o texto
`O vel da noiva é invisível`
vai dar match apenas na palavra `vel`, porque `\b` dá o match no limite da palavra.

Em contrapartida, o caracter `\B` vai dar match em posições que `\b` *não* dá match.

`\Bvel`
aplicado sobre o texto
`O vel da noiva é invisível`
dá match no `vel` de `invisível`.

Mas como a engine sabe que a palavra acabou? Como ela decide o final da palavra `anti-herói`? `\b` dá match no que `\w` não dá. `\w` é chamado de `word character`. Ele dá match em "caracteres de palavras", então as letras do alfabeto, algarismos e underline (`_`). Algumas implementações, ou _flavors_, de regex suportam Unicode por padrão, como a engine do Python. Nas que não suportam, o `ó` de `herói` não será reconhecido como `\w` se não for colocada uma _flag_, que na maioria dos _flavors_ é `u`. Falaremos sobre _flags_ mais pra frente.
No entanto, nenhuma engine de regex dá match no hífen (`-`). Então se você quiser que a sua engine dê match em `anti-herói`, você precisará da seguinte regex

`/[\w-]+/u`

Assim você engloba tanto todos os caracteres representados por `\w` e o hífen.
Notem que eu coloquei duas barras (`/`), uma no começo e uma no final da regex. Esses são os separadores e indicam quando a regex começa e termina. Esses separadores não foram incluídos antes porque não eram necessários para a explicação, mas por conta da _flag_ `u`, foi preciso incluí-los. Novamente, falaremos sobre _flags_ mais pra frente.

## Conclusão
Nessa parte foi a primeira vez que eu falei de _flavors_ de regex. É importante falar sobre isso porque o que a gente chama de _regex_ é na verdade uma especificação. Cada linguagem ou plataforma implementa de uma maneira diferente essa especificação, então agora é a primeira vez que digo uma das _regras da regex_, que eu mesmo formulei.

Regra 3: conheça muito bem sua engine de regex

Até a próxima.
Paystack Payment Initialization using PHP Laravel Backend
Published: 2022-09-12 13:51:12

Initializing paystack transaction from your backend is safer way of building a secured payment integration.

For this content, I will be using postman for my testing. If you are new to postman, check my post on [how to setup postman with laravel backend](https://dev.to/nobleokechi/how-to-setup-postman-with-laravel-project-521n).

**Create a Route**

Create a route on `api.php` file with any preferred name.

```
Route::post('initialize_paystack', [PaystackController::class, 'initialize_paystack'])->name('api.initialize_paystack');
```

**Create a Controller**

For this solution, I have a controller called `PaystackController` and a function inside the controller called `initialize_paystack`.

To initialize payment, see the code below.

```
private $initialize_url = "https://api.paystack.co/transaction/initialize";

public function initialize_paystack(Request $request)
    {
        // $amount = number_format($request->amount,2);
        $fields = [
            'email' => $request->user()->email,
            'amount' => $request->amount * 100,
        ];
        $fields_string = http_build_query($fields);
        //open connection
        $ch = curl_init();
        //set the url, number of POST vars, POST data
    
        curl_setopt($ch,CURLOPT_URL, $this->initialize_url);
        curl_setopt($ch,CURLOPT_POST, true);
        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer ".env('PAYSTACK_SECRET_KEY'),
    
        "Cache-Control: no-cache",
    
        ));
    
        //So that curl_exec returns the contents of the cURL; rather than echoing it
    
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
        //execute post
    
        $result = curl_exec($ch);
        $response = json_decode($result);

        return json_encode([
                'data' => $response,
                'metadata' => [
                    'payment_for' => 'token'
                ]
           ]);
    }
```

**Send data from postman**

To trigger the initialization, I will send the `amount` from postman which can also be sent from your frontend.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/021ple6ymfwqn3gdon3f.PNG)

Your response will return payment link, which you can use to make a payment or return back to the frontend.

```
"data": {
        "status": true,
        "message": "Authorization URL created",
        "data": {
            "authorization_url": "https://checkout.paystack.com/zbm34791mm5t9wk",
            "access_code": "zbm34791mm5t9wk",
            "reference": "dod8hghbhc"
        }
    },
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17bpfq8xjxti97wl470s.PNG)

The image above is response gotten after clicking the payment link.
Simple JavaScript template engine by (ab)using template literals
Tags: javascript, programming, tutorial, webdev
Published: 2022-09-12 13:37:05


Templating inline strings is simple using ES6 template literals:
```
const a = "hello"
const b = "world"

console.log(`${a} ${b}`)
//hello world
```

But what if you have a string that can't be inlined (i.e. it comes from an external source)?

Here's the gist of the function I recently used for this purpose:

```
function tpl(str, props) {
    let names = Object.keys(props);
    let vals = Object.values(props);
    return new Function(...names, `return \`${str}\`;`)(...vals);
}
```

Or, (a slightly less readable) one-liner version:

```
const tpl = (str, props) => new Function(...Object.keys(props), `return \`${str}\`;`)(...Object.values(props))
```

Example:
```
console.log(tpl('${a} ${b}', {a: 'hello', b: 'world'}))
//hello world
```

## Explanation

So, we are defining a function called `tpl`:

```
function tpl(str, props) {
    let names = Object.keys(props);
    let vals = Object.values(props);
    return new Function(...names, `return \`${str}\`;`)(...vals);
}
```

The first two lines are self-explanatory - we are just extracting keys and values from the passed-in `props` object.

In the last line, we are dynamically creating a function from a string. Instead of doing `eval`, we are using the `Function` constructor, which is a much safer alternative.

Our new (dynamically generated) function receives a list of names of our props keys, and returns the same passed-in `str` string but delimited with backtick characters (basically, we are turning our "external" string into an inline template string). 

After that, we just need to call our new function with a list of values.

## Function.call alternative

We could simplify things by doing something like this instead of extracting names and values:
```
new Function(`return \`${str}\`;`).call(props)
```

But then we would need to use `${this.a}` instead of just `${a}`.


## Caching

Each time you're calling the `Function` constructor, the function body needs to be parsed (some overhead), but it would be very easy to do some caching based on the value of `str`.
        
<hr><small>
Note: This is a snapshot of the wiki page from the <a href="https://betterways.dev">BetterWays.dev wiki</a>, you can find the latest (better formatted) version here: <a href="https://betterways.dev/simple-javascript-template-engine-by-ab-using-template-literals">betterways.dev/simple-javascript-template-engine-by-ab-using-template-literals</a>.
</small>