teleren/devto huggingface dataset:
How to Iterate Through Multiple Python Lists at Once
Tags: python, tutorial, beginners
Published: 2020-11-23 01:18:36

The Python [zip](https://docs.python.org/3.3/library/functions.html#zip) built-in function makes it easy to iterate through multiple iterables all at once. It aggregates elements from each iterable to create an iterator of tuples. The *i-th* tuple contains the *i-th* element of each of the constituent iterables. For example:

```python
>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c']
>>> zipped = zip(x, y)
>>> for x, y in zipped:
...    print(x, y)
...
1 a
2 b 
3 c
```
## Getting the zipped elements as a list
The `zip` function returns a -- wait for it -- `zip` object. You can confirm this by printing the `zipped` variable out in the console. You should see something like this:

```python
>>> zipped = zip(x, y)
<zip object at ox7f45ddba2c08>
```

To convert it into a `list` you can manipulate, you use the very aptly named `list` function like so:

```python
>>> list(zipped)
[(1, 'a'), (2, 'b'), (3, 'c')]
``` 

## Unzipping a zip object
If for any reason you need to reverse a `zip` operation, you can do so with the `zip` function, in conjunction with the destructuring operator (`*`) to return the original itertables as tuples:

```python
>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c']
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True 
```

## Zipping unequal list lengths
Zipping unequal list lengths causes the elements of the longer lists to be dropped:
```python
>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c', 'd']
>>> list(zip(x, y))
[(1, 'a'), (2, 'b'), (3, 'c')]
```

Fortunately, we can use the [itertools.zip_longest](https://docs.python.org/3.3/library/itertools.html#itertools.zip_longest) function to solve this. `zip_longest` takes iterables as paramaters like `zip`, but with an additional `fillvalue` parameter which substitutes for missing values. It defaults to `None`. Here's how you use it:

```python
>>> from itertools import zip_longest
>>> x = [1, 2, 3]
>>> y = ['a', 'b', 'c', 'd']
>>> list(zip_longest(x, y))
[(1, 'a'), (2, 'b'), (3, 'c'), (None, 'd')
``` 

And with a `fillvalue`:
```python
>>> list(zip_longest(x, y, fillvalue=-1))
[(1, 'a'), (2, 'b'), (3, 'c'), (-1, 'd')]
```

 As you can see, with Python, it's very simple to iterate over multiple lists at once. 

## Further Reading
+ The official documentation for [zip](https://docs.python.org/3.3/library/functions.html#zip)
+ The official documentation for [itertools](https://docs.python.org/3.3/library/itertools.html#itertools.zip_longest)
+ How to use the [enumerate](https://www.adrianperea.dev/better-python-for-loops-using-enumerate/)
Criando sistemas legados com o framework da moda
Tags: portugues, desenvolvimento, legado, boaspraticas
Published: 2020-11-23 00:56:53

Não é um assunto necessariamente recente, porém restam controvérsias e, sem dúvidas, ainda cabe uma opinião. 

Legados não são ruins. Ruins são as gambiarras, a ausência de testes e de boas práticas de desenvolvimento. Colocar a mesma equipe que desastrosamente sustenta um legado para criar uma nova API fresquinha, com o último framework da moda é potencializar as chances de criação de código ruim, frequentemente chamado de legado.

Também incorro no erro de chamar de construção de novos legados quando vejo códigos escritos de qualquer forma. Mas é força do hábito. Muitas vezes pensei que a solução para melhorar um software era reescrevê-lo, não por convicção própria, pois muitas vezes o CTO da empresa ou o arquiteto induziram a equipe a pensar desta forma. Fato é que essa abordagem nunca resolveu o problema inicial. Meses após o início das migrações sempre parece haver um "novo legado".

E o que acontece ao tentar escrever um novo software com os mesmos vícios de programação? Temos dois softwares ruins para manter, com a mesma equipe que já não aguenta manter o legado. Óbvio que é tentador explorar novos frameworks e linguagens. E o ganho de velocidade realmente surpreende nas primeiras Sprints pois, obviamente, ainda não está uma bagunça completa: ela vem com o tempo. A situação ainda é agravada com os microsserviços e com a criação de novas APIs de forma desenfreada e sem qualidade.

O problema é colocado sobre o sistema, mas na verdade deveria ser sobre a sua forma de manutenção. Não há uma atenção especial à qualidade e melhoria contínua, haja vista que o foco é criar os entregáveis e fazer as peças funcionarem a todo custo. Há uma pressão clara de entrega e isso faz parte do negócio, mas os desenvolvedores devem contrapor isso com seus pontos técnicos ao longo das Sprints.

A equipe de desenvolvimento deve continuamente levantar débitos, ajustar desvios e executar pequenas refatorações. Estas não deveriam exigir um Sprint dedicado apenas a débitos técnicos de tempos em tempos, mas sim pequenas tarefas dentro de cada Estória, melhorando continuamente o código e a arquitetura. Olhar com a visão de escoteiro, melhorando pouco a pouco cada classe alterada irá dar uma sustentabilidade muito maior ao sistema, deixando mais fácil adicionar novas features.

E se o framework ficar defasado? Inseguro? Precisar ser escalado? Bem, se o software foi bem cuidado pode ser planejada uma estratégia de migração ou fracionamento. As classes de negócio poderão ser reaproveitadas, se mantida a linguagem, mas as demais provavelmente terão de ser reescritas. Será doloroso, contudo a migração será mais curta e garante foco total em apenas uma aplicação, sem legados.

---

_Originalmente postado em meu blog: https://blog.lptn.com.br/posts/codigo/criando-sistemas-legados-com-o-framework-da-moda/_
_Photo by Jon Tyson: https://unsplash.com/@jontyson_
JS Fundamentals: Scope explained
Tags: javascript, tutorial, webdev
Published: 2020-11-23 00:13:50

##What is Scope?
Scope is the concept of where something is available. The actual MDN definition states it's `the context in which values and expressions are "visible" or can be referenced.`

In Javascript, there are 3 types of scope: **Global, Function, and Block Scope.**
##Global Scope
When a variable or function has a global scope, that means it can be accessed everywhere in our code.

```javascript
var a = "I'm a global variable!";

function myFunct(){
  console.log(a); // has access to 'a' since it has global scope.
}

myFunct() // 'I'm a global variable!'.
```
**Tip:** If a variable or function is NOT declared inside a function or block, it most likely falls under the global scope.

##Function Scope
When variables, functions, or parameters are declared inside of a certain function, they are only accessible within that specific function.

```javascript
function eatDinner(){
  var item = 'Turkey';
  console.log(`I love ${item}!`)
}

eatDinner(); // 'I love Turkey!'
console.log(item); // 'ReferenceError: item is not defined.'
```
From outside of the function, we can't reference anything declared inside of it.

##Block Scope
A block statement creates its own scope.

Variables declared with `var` are **not** block-scoped.
```javascript
if (true){
  var myVar = 42;
}

myVar; // => 42
```
Variables declared with `const` and `let` **are** block-scoped.
```javascript
if (true){
  const myVar = 42;
  
  let secondVar = 1000;
}

myVar;
// Uncaught ReferenceError: myVar is not defined

secondVar;
// Uncaught ReferenceError: secondVar is not defined
```

##Things to keep in mind when defining scope
Variables created without const, let, or var keywords will be globally-scoped, regardless of where they are in your code.

```javascript
const greeting = 'Hey guys'; // global scope
holiday = 'Thanksgiving'; // global scope

if (true){
  lastName = 'Cortez'; // global scope
  let firstName = 'Allison'; // block scope
}

lastName;
// => "Cortez"
firstName;
// 'ReferenceError'

```
Generally, you should never use global variables. 

For example, say you're storing sensitive information...
```javascript
function userAccount(){
  password = 'secretPassword';
  
}

password;
// => "secretPassword"
```
In our example, we probably wanted our password variable to have a function scope.. BUT since it had global scope, we got access to sensitive information when we shouldn't have.

It's best practice to make variables and functions available only where they're needed. 

[MDN Scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope)
Can the class containing `main` be private?
Tags: java, help, watercooler
Published: 2020-11-23 00:07:31

I realize, that, in some cases, `main` shall not be `private` (and sometimes not `protected`), and in other cases, it may compile.

But, I was wondering if the class containing `main` can look like this:
```java
private final class Main {
    public static void main(String[] args) { /* ... */ }
}
```
.
Why did I decide to study Software Engineering?

Published: 2020-11-23 00:03:37

I started my professional career in management. I spent my years in collecting navigating corporate america. Things seemed straightforward for the first 5 years of managing people.  I guess I was lucky. Then I landed at a place that was slightly different different than what I have experienced. The work environment was a lot more toxic. My employees were not the best, to say the least. As a manager your performance is measured on how you can motivate your employees to excel at their job and to continue to be better.  What if you have employees that do not want to be better or are unmotivated to do their job? What about the attitude of those type of employees? These are only some of the factors that play into how my performance is measured. When an employee under performed then I was not doing a good job. I quickly realized this is not what I want to be doing for the rest of my life. I had to reflect on what I really wanted out of a career. It came down to a few things; work life balance, salary, being able to create, have my performance be measured by what I have done and no one else,  and last but not least impact. Through a lot of searching I found remembered that I used to love Zango and MySpace. Finding lines of code to make my page "cool." I always had an interest in how it was done. I researched a lot on the capabilities of software and decided this is what I want to do. This checks checks all of my boxes.
How to fill an array with a specific value in JavaScript?
Tags: javascript
Published: 2020-11-23 00:00:00

---
  title: How to fill an array with a specific value in JavaScript?
  published: true
  tags: JavaScript
  date: Mon Nov 23 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/fill-array-with-value-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-834058443758634a81c239d62f5df289.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/fill-array-with-value-javascript)
  
To fill an array with a specific value, you can use the `fill()` array method in JavaScript.

Consider this array of numbers,

```js
// number array
const numArr = [1, 2, 3, 4, 5];
```

Let's use the `fill()` array method to fill the entire array with value `9` by passing value as the first argument to the method like this,

```js
// number array
const numArr = [1, 2, 3, 4, 5];

// fill the entire array
// with value 9 using the fill() method
numArr.fill(9);

console.log(numArr); // [9, 9, 9, 9, 9]
```

See this example live in [JSBin](https://jsbin.com/dumoliyoji/edit?js,console).

If you don't want the whole array to be filled with a specific element but from one index to another index in the array, you can pass the `start` index as the second argument and `end` index as the third argument to the `fill()` method like this,

```js
// number array
const numArr = [1, 2, 3, 4, 5];

// fill the entire array
// with value 9 but from index 1 to 3
// using the fill() method
numArr.fill(9, 1, 3);

console.log(numArr); // [1, 9, 9, 4, 5]
```

The method will start filling from the `start` index and ends without filling the `end` index.

See this example live in [JSBin](https://jsbin.com/raqideleda/edit?js,console).

### Feel free to share if you found this useful 😃.

---
Hash-tastic! part three
Tags: codenewbie, ruby, beginners
Published: 2020-11-22 23:21:10

######Photo by <a href="/photographer/neopicture-53843">Joel Dietle</a> from <a href="https://freeimages.com/">FreeImages</a>

Hello again! I hope that so far you are learning to appreciate hashes and the power of nested data structures. Let's take a final look at our awesome bookshelf hash. In case you've forgotten what it looks like, parts 1 & 2 of this series have a lovely image for review. 

This time we'll be working with the last shelf, the Harry Potter bookshelf, a hash of hashes. We will go over how to output data from within this structure that is itself nested within the parent hash **_bookshelf_**.

The desired output in this example is a sentence that displays to the user the book number (1st level key) and title (2nd level key) of every volume within the **':harry_potter'** shelf.

**Run the repl.it below to see how it works.**

{% replit @cdversiontwo/bookshelfhashexthree %}

**Here is a closer look at the magic that makes it happen:**

```ruby
def print_potter_books(shelf)
  shelf.each do |volume, info|
    info.each do |k, v|
      if k == :title 
        puts "The title of #{name(volume)} is #{v}."
        sleep(2)
      end
    end  
  end
end
print_potter_books(bookshelf[:harry_potter])
```
Here we take the **':harry_potter'** *shelf*, iterate  over it, taking each *volume*, which contains *info*, and then iterating over that *info*, making a comparison against each *key* inside the *info* and if it matches, outputting the desired text containing data from two different layers of the hash. 

**NOTE:** The *name* method can be found on line 44 in the **_repl.it_**

Whew! If that was a bit much, just take a moment to read the code line by line. Try to think about the nested data structure like an onion and just peel away at it one layer at a time. 

For example, the code to show the user the date for Book 7 looks like this:

``` ruby
puts bookshelf[:harry_potter][:book_7][:date]
```
**Puts out to the user:**
2007

Here it is easy to see the different levels of the data structure. The parent hash is **_bookshelf_** and to get to the date you must reach down three levels. 

Thanks for reading this far. If you didn't already know how awesome hashes and nested data structures are, hopefully now you do (at least a little bit)!
Meses sin Intereses en Stripe con Python y React parte 3
Tags: python, react, flask, stripe
Published: 2020-11-22 23:11:03

En nuestro post anterior iniciamos la creación de nuestro formulario de pago, en esta sección terminaremos de preparar el formulario para poder aceptar los pagos.

# El evento submit

Por ahora tenemos un formulario donde validamos cada cambio en el formulario en el evento onChange pero como dijimos es un formulario por lo que necesitamos `subir` ese cambio es decir un evento onSubmit y así es como lo escribiremos.

Nos situamos dentro del componente `CheckoutForm.js`

```
import React from 'react'
import CardSection from './CardSection'
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';

const CheckoutForm = () => {
    const stripe = useStripe();
    const elements = useElements();

    const handleSubmit = async (ev) => {
      ev.preventDefault();

      if (!stripe || !elements) {

        return;

      }

      const cardElement = elements.getElement(CardElement);

      const {error, paymentMethod} = await stripe.createPaymentMethod({
        type: 'card',
        card: cardElement,
      })

      if (error) {
        console.log(['error'], error);
      } else {
        console.log(['PaymentMethod'], paymentMethod);
      }

    }

    return (
        <div className="col-lg-12">
            <form onSubmit={handleSubmit}>
                <h1>Formulario de Pago</h1>
                <div className="form-group">
                    <CardSection/>
                </div>
                <button className="btn btn-primary">Donate</button>
            </form>
        </div>
    )
}

export default CheckoutForm;
```

Lo primero que estamos haciendo es importar los hooks `useStripe` y `useElements` de la librería de stripe. Ahora situándonos en el JSX agregamos el método o prop `onSubmit` en el formulario.

Ahora la parte mas importante es `const cardElement = elements.getElement(CardElement);` ya que esta se encargara de buscar el `CardElement` y con el creara el método de pago.

Para este punto recuerden poner su api key de stripe.

Ahora y para terminar este post tenemos que enviar el método de pago al servidor y esto lo vamos a hacer usando la función fetch de JS, esto se va a hacer dentro del `else` de la función `handleSubmit`.

```
 let response = fetch('http://localhost/api/acept_payment',
          {'payment_method': paymentMethod}).then((response) => {
            console.log(response)
          }).catch((error) => {
            console.log('[error]', error)
          });
```

y por ahora es todo, en el siguiente post vamos hacer nuestro backend con python y flask donde vamos por fin a aceptar el pago.

Nuevamente les dejo el repo del proyecto de react para que puedan ver todos los cambios. https://github.com/leonardoAlonso/StripeForm
Montre connectée smartwatch
Published: 2020-10-14 09:31:56

Dans la plupart des activités populaires, les montres liées sont devenues utiles. Ils simplifient les choses pour les utilisateurs, grâce notamment à leurs nombreuses fonctionnalités. Trouvez-vous une montre connectée en fonction de vos moyens et de vos besoins, à l'aide de cet article. les montres connectées seront fournies par vos fournisseurs dans tous types de produits électroniques, variant en volume.

À quoi sert une montre connectée
La montre intelligente smartwatch s'appelle toujours SmartWatch, qui est populaire sur le marché de l'électronique. Il s'est développé en fonction des besoins de ses utilisateurs, avec de plus en plus de demande sur le marché. C'est un excellent outil pour différentes industries, et même pour le sport. Il sert dans certains cas de substitut aux smartphones. La montre connectée permet à son utilisateur d'émettre ou de recevoir des appels mais également des alarmes. C'est un excellent raccourci pour accéder à certaines de vos applications ou utiliser Internet. C'est essentiellement un moyen efficace de réduire le coût d'utilisation de votre smartphone. Par exemple, lorsque vous recevez une notification sur votre smartphone, elle émettra des vibrations. Il est très utile pour les sportifs, car lors de vos séances de sport il sert de podomètre avec l'avantage essentiel d'être léger et de ne pas vous encombrer.

Critères de choix!

Offrez-vous des montre connectée femme hautes performances à des prix très abordables. Les prix varient en fonction des fonctions et de la technologie de la montre, ou de son autonomie. Plus une montre est chère, meilleures sont ses performances. Mais nous nous intéressons ici aux smartwatches utiles et abordables. Et il y en a quelques-uns à un excellent rapport qualité / prix sur le marché. L'essentiel est de définir vos besoins, et de prendre les mesures appropriées pour faire un bon achat. Il faut avoir une idée du type d'écran à cet effet. Il peut s'agir d'une montre connectée avec ou sans écran tactile. Définit ensuite les fonctions qu'il exécutera. Les fonctionnalités dépendent cependant de ce dont vous avez besoin. Si vous êtes un athlète par exemple,

Enfin, le dernier critère concerne la connectivité. La connectivité est possible grâce aux applications disponibles, ou via Wifi, voire bluetooth.
Vous pouvez choisir l'idéal en fonction de vos besoins et de l'usage que vous comptez en faire.

For more info please visit at - https://fitpowerforce.com/
Marching Ants Puzzle
Tags: challenge, codingpuzzle, math, algorithms
Published: 2020-11-22 23:03:25

Suppose there is an ant at each vertex of a triangle (cube, regular tetrahedron / octahedron / dodecahedron / icosahedron / general planar graph / any graph).

Suddenly each ant randomly (with equal probability) picks a neighboring edge and crawls along it to the next vertex. What is the probability that no two ants collide, neither on a vertex, nor en route on an edge?

**Example solution for triangle.**
Each ant can move either Left, or Right. That gives 8 options: LLL, LLR, LRL, LRR, RLL, RLR, RRL, RRR. However, only in LLL and RRR no ants collide. Two options out of eight give probability 2/8 = 1/4.

Give your numeric solutions for the mentioned polyhedra or an algorithm for a sufficiently general case!
Angular. Where to start?
Tags: explainlikeimfive, angular, beginners, typescript
Published: 2020-11-22 22:59:01

Spoiler:exclamation: I don't give advices here, I'm looking for them. :grin:

**Prequel:**

At the beginning, when I've entered the beautiful world of programming I was trying to get the latest and the coolest tech. 
Last Ubuntu version, last Python (I've started my journey with it), the new shiny version of the IDE and so on. 

**Drama:**

But... few months later I've started to learn OOP and Java. (Drum roll)
That was the very first moment when I've discovered 'LTS' magic world.
Also, a lot of tutorials on older Java releases. But, back then a good friend of mine helped me out.

**Sequel:**

Now, I have to lear Angular as my employer asked me to. But I have no idea where to start. As I have found, the last version of Angular is 11, but most tutorials on YouTube and other sources are for earlier versions and there is also this Typescript.:confused:

So, please, give me an advice and to others like me:
 - Where do I start?
 - Do I have to master typescript as well?
Getting Started with Rails as an API
Tags: react, ruby, rails, javascript
Published: 2020-11-22 22:32:11

An API is known in the programming world as an Application Program Interface. What does this mean you ask? Well from my understand an API is used to grab data from a particular source, usually a database.

You may ask, what is a database? From my understanding, a database is used to store and retrieve information, and when I get really good at communicating with these suckers, I'll become a better engineer.

An API can be created by anyone, that's the really cool part. The way to get started will be explained in this blog post. Now the first thing I will tell you is, APIs enable programmers like me, to access and display on a web page.

APIs can become the grit of your application because of the freedom and the ability to grab any informational database and use it as a tool. APIs are great because your program is allowed to be multi-resourced. It has range, it has freedom, go create. This tool comes with flexibility by using a powerful gem called the Fast JSON API. The Fast JSON API gem provides a quick way to generate and customize JSON serializers. 

Woah, slow down! What are you even saying?
Okay, I'll break it down, you're probably asking, "what is JSON?" It stands for JavaScript Object Notation. JSON (JavaScript_Object_Notation)  is a simple data format that uses sets of the familiar *key & value pairs* to store information. Back to that information storing thing again. JSON is chosen because it uses javascript to pass information around. Serializers enable us to handle the logic of arranging our JSON data the way we want it.

There are many gems out there, but there is a particular gem in Rials that I truly have fallen madly in love with. It was an instant connection, didn't make much for me to realize the power of this tool. It's not just me that can confirm how brilliant it is. Using this popular option, the Fast JSON API gem creates a JSON serializer for Rails APIs. It provides a way for us to generate serializer classes for each resource object in our API that is involved in customized JSON rendering.

Setting up Fast JSON API
To add the Fast JSON API gem to your Rails program, go to your project's Gemfile and copy and paste this line there:

```ruby

gem 'fast_jsonapi'

```

Then run bundle install in your terminal.

Once installed, you will gain access to a new generator, serializer.

Godly Gem!