teleren/devto huggingface dataset:
Inspecting function annotations in Python
Tags: python, advanced
Published: 2020-02-03 16:40:10

---
title: Inspecting function annotations in Python
published: true
description: Learn how to inspect function annotations in Python and build some neat tricks.
canonical_url: https://nateclark.io/inspecting-python-functions/
tags: python, advanced
---

For this article, I'm just going to spend some time in the python shell. Please let me know if this is helpful or terrible 😄.

```python
>>> import inspect
>>> # Let's learn a little about the inspect module
>>> inspect.__doc__.splitlines()[0]
'Get useful information from live Python objects.'

>>> inspect.signature.__doc__
'Get a signature object for the passed callable.'

>>> inspect.Signature.__doc__.splitlines()[0]
'A Signature object represents the overall signature of a function.'

>>> # Let's inspect a simple function
>>> def add(x, y):
...     return x + y

>>> add_sig = inspect.signature(add)
>>> add_sig
<Signature (x, y)>

>>> add_sig.parameters['x']
<Parameter "x">

>>> add_sig.parameters['x'].annotation
<class inspect._empty>

>>> add_sig.return_annotation
<class inspect._empty>

>>> # If the function has more information
>>> # we can inspect more information
>>> def typed_add(x: int, y: float) -> float:
...     return x + y

>>> typed_add_sig = inspect.signature(typed_add)
>>> typed_add_sig.parameters['x'].annotation
<class int>

>>> typed_add_sig.return_annotation
<class float>

>>> # Let's pretend that we're pytest
>>> # and implement a baby version of fixtures
>>> def test_42_is_the_answer(the_answer):
...     assert the_answer == 42

>>> fixtures = {"the answer": 42}

>>> def fake_test_run(test_function):
...     test_function_parameters = inspect.signature(test_function).parameters.values()
...
...     if any(parameter.name not in fixtures for parameter in test_function_parameters):
...         raise Exception(f"Test function expected expected fixture named {name}")
...
...     arguments_to_pass = {
...         parameter.name: fixtures[parameter.name]
...         for parameter in test_function_parameters
...     }
...
...     try:
...         test_function(**arguments_to_pass)
...     except AssertionError as ex:
...         print("Fail: Test Failed")
...         print(ex)
...     except Exception as ex:
...         print("Error: Something bad happened")
...         print(ex)
...     else:
...         print("Pass!")

>>> fake_test_run(test_42_is_the_answer)
Pass!

>>> fixtures["the_answer"] = 2345

>>> fake_test_run(test_42_is_the_answer)
Fail: Test Failed

>>> # Goal!
>>> # Our test function is *magically* getting passed an argument
>>> # based on our function signature.
```
Que comiencen los juegos
Tags: capua, design, webdev
Published: 2020-02-03 16:39:11

# Capua es un blog de desarrollo & experiencia de usuario.

Tras una lucha “sangrienta” para conseguir el nombre de usuario **capua** en _GitHub_, ya no tenemos excusas para compartir nuestras locuras. Hace mucho tiempo que teníamos en mente este proyecto, pero al fin nos hemos puesto las pilas.

## Capua
Por contar un poco de donde procede el nombre del blog, nos gusta la temática romana, y Capua, antigua capital de Campania, tuvo el primer anfiteatro del mundo romano, donde los gladiadores dominaban la arena.

Los desarrolladores, desde siempre, tienen que reciclarse **diariamente** pues cada día salen nuevas tecnologías u otras se van actualizando, y para conseguir eso creemos que debemos ser como los gladiadores de la antigua Roma, capaces de enfrentarnos a cualquier bestia que se nos ponga por delante.

Si has visto o si eres fan de _spartacus_, es posible que te suene todo esto de Capua. También te será familiar nuestro grito de guerra:

> “Por Capua!”

Nuestra intención es compartir artículos interesantes de las cosas que hemos ido aprendiendo o que nos han enseñado a lo largo de los diferentes proyectos que hemos realizado.

## Quiénes somos…

{% user ayozebarrera %}
{% user marioblas %}

## …y donde estamos

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m8tnffpug103nm60glo8.png)

<figcaption>Las Palmas, Canary Islands, Spain ☺</figcaption >

## Contenido

Nuestros artículos se centrarán principalmente en dos campos, desarrollo y diseño. No descartamos hablar alguna vez de tecnología… o algún juego, quien sabe!

### Desarrollo

Estamos constantemente desarrollando aplicaciones con frameworks, servicios y plataformas de última hora.

Nuestro mundo gira principalmente en torno a Javascript y todas las tecnologías relacionadas con éste lenguaje.

Actualmente, nuestra librería principal es React.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xbbd88fhi6nubq9wa2v1.png)


### Diseño

Le damos mucha importancia al diseño de la experiencia de usuario (UX). UX es la calidad de experiencia que tiene un usuario cuando usa un diseño concreto.
Algunas tecnologías de las que usamos nos permiten tener mayor flexibilidad en nuestra aplicación para así conseguir una UX más elaborada…

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/j1hgnp26cgoom0jxukqm.png)

Probablemente hablemos de todo un poco, pero intentando no aburrir ☺.

### Objetivos

Somos algo novatos en el mundo de los blogs, pero intentaremos estar a la altura.

Unos de los objetivos que pretendemos conseguir con Capua es crecer como redactores. No queremos tener un blog de textos copiados, y puestos para rellenar simplemente por tener muchos artículos y visitas.

Le dedicaremos tiempo a cada artículo para intentar conseguir lo mejor de nosotros mismos. Y eso nos ayudará a conseguir otro de nuestros objetivos, la creación de nuestro propio imperio, nuestro lugar. Tenemos muchas ideas que llevamos guardando mucho tiempo.

Ya veremos hacia donde crece esto y con quien.

Dicho esto… Capua queda inaugurado!

Hasta el próximo artículo ☺
Idiomatic way to implement this in golang
Tags: discuss, go, typescript
Published: 2020-02-03 16:22:12

I am experimenting to migrate a nodejs system (typescript) to golang. Its going well except i am having trouble in reproducing the following in idiomatic go

I have the following abstract class: 
```ts
abstract class BaseSensor {
  beforeStart() {/*default implementation*/ }
  afterStart() {/*default implementation*/ }
  shutdown() {/*default implementation*/ }
  abstract process();

  work() {
    this.beforeStart()
    //...
    this.afterStart()
    //...
    this.process()
    //...
    this.shutdown()
  }
}
```

then i have some concrete classes/sensors which implement atleast the `process()` method and optionally any of the other lifecycle methods. 

```ts
class SensorA extends BaseSensor {
  process() {
    //SensorA specific processing
  }
}

class SensorB extends BaseSensor {
  beforeStart() {
    //SensorB overriding beforeStart()
  }
  process() {
    //SensorB specific processing
  }
}
```

`SensorA` only implements the `process()` method and doesn't override anything else. `SensorB` implements `process()` and also overrides `beforeStart()`.

What is the correct way of doing something like this in `golang`
216 new remote jobs for developers at PayPal, Zapier, Toggl and others
Tags: career, angular, java, android
Published: 2020-02-03 16:15:44

Good Monday, DEV community! 👏🏼

It's Arsen from Meerkad community of remote job seekers with weekly updates.

During the period from January 13 to 19, I collected 216 vacancies from popular job boards like Glassdoor, Flex Jobs, WeWorkRemotely, and others, as well as from Facebook, Twitter, and Reddit.

It takes about 3 hours a day to visit 78 sources that I prepared in advance. Here are the links for several job's categories:

- Front-end https://meerkad.com/remote-frontend-jobs
- Back-end https://meerkad.com/remote-backend-jobs
- Full-stack https://meerkad.com/remote-full-stack-jobs

All jobs for developers are here 👉🏻 https://meerkad.com/remote-developer-jobs

As you might already know from my intro post I am a full-stack web developer (php, laravel, javascript) and the creator of Meerkad. I started this Remote Job Board Community to connect companies with the current and hopeful remote working people from all over the world. So! If you are looking for a remote job I'm glad to help!

Ars
The Must-Read Javascript Book of 2020 is Free
Tags: javascript, books, codenewbie, beginners
Published: 2020-02-03 16:08:18

It’s real! The 2020, 2nd edition of _You Don't Know JS Yet: Get Started_ is here. The official tweeter account tweeted its realness just on February 1st, and only yesterday, we got the announcement that the print versions are ready.

This review is hot off the press for the new edition.

The new title of the 2nd edition of this Javascript series resonates with me. The new “yet” appended to the title has the perfect amount of snark: of course we can all say that we used Javascript and achieved the result we wanted, but we can’t all say that we know Javascript — yet.

That’s because the way Javascript thinks is complicated and not consistent with other programming languages. In my career, I deal with this insecurity about Javascript. Truly knowing Javascript is a touchy subject for many of us.

## Overview

_[You Don’t Know JS Yet: Get Started](https://github.com/getify/You-Dont-Know-JS)_ should not be called Get Started. Its truer title is “Under the Hood,” since the entire idea behind book one of the series is to lift the hood, point out the components, and highlight idiosyncrasies in Javascript.

[Read More on my Blog](https://booksoncode.com/articles/ydkjs-get-started?ref=dev)
Multiple service calls from an NgRx Effect
Tags: angular, ngrx, rxjs, beginners
Published: 2020-02-03 16:07:45

---
title: Multiple service calls from an NgRx Effect
published: true
tags: Angular, NgRx, RxJs, beginners
main_image: https://timdeschryver.dev/snippets/images/multiple-service-calls-from-an-effect.png
canonical_url: https://timdeschryver.dev/snippets/multiple-service-calls-from-an-effect
---

Follow me on Twitter at [@tim_deschryver](https://twitter.com/tim_deschryver) | Originally published on [timdeschryver.dev](https://timdeschryver.dev/snippets/multiple-service-calls-from-an-effect).

---------


# Multiple service calls from an Effect

## Use case

An action to fetch multiple entities at once, but the service has only an endpoint to fetch one entity at a time.

## Solution

Use the RxJS [merge](https://rxjs-dev.firebaseapp.com/api/index/function/merge) operator to flatten all request streams and concurrently emit all values to a single output stream.

```ts
refresh$ = createEffect(() =>
  this.actions$.pipe(
    ofType(CustomerActions.refresh),
    exhaustMap(({ customerIds }) =>
      merge(
        ...ids.map(id =>
          this.customersService.getCustomer(id).pipe(
            map(CustomerActions.getCustomerSuccess),
            catchError(err =>
              of(CustomerActions.getCustomerFailed(id, err.message)),
            ),
          ),
        ),
      ),
    ),
  ),
)
```


-------

Follow me on Twitter at [@tim_deschryver](https://twitter.com/tim_deschryver) | Originally published on [timdeschryver.dev](https://timdeschryver.dev/snippets/multiple-service-calls-from-an-effect).
API data persistence with relational databases
Tags: sql, backend
Published: 2020-02-03 16:04:40

---
title: API data persistence with relational databases
published: true
description: Ordering and limiting data in an SQL database query
tags: sql, backend
cover_image: https://ferrariwebdevelopment.s3.us-east-2.amazonaws.com/assets/20191206-databases.jpeg
---

## Ordering and limiting data in an SQL database query

In our previous article we have started introducing some database queries done with the SQL language.

To practice our skills we used a tool provided by W3 Schools, called
[Try SQL Tool](https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all)

This tool provides a sample database with several tables and an interface to easily make SQL queries and pull up data inside a web browser.

Let's continue our exploration by finding out how to order data.

### Ordering data
Sometimes we need to retrieve data in a specific order. For this we use the `ORDER BY` operator:

```
SELECT * FROM Products ORDER BY price;
```

Here we retrieve all Products ordered by price. By default, the ordering is ascending (from small to large), but we can control the order with `ASC` or `DESC` (for ascending or descending):

```
SELECT * FROM Products ORDER BY price DESC;
```

We can also add multiple filter clauses in the same query. In the example below we first filter by price, which will limit our results, and then sort the filtered records in descending order by price:

```
SELECT * FROM Products WHERE price > 50 ORDER BY price DESC;
```

### Limiting data

What if we want the 5 most expensive products?
One quick way of doing it is to order the products by price and then take the first 5 of them.

In this case, the `LIMIT` operator is our friend. It limits the returned record set by an arbitrary number:

```
SELECT * FROM Products ORDER BY price DESC LIMIT 5;
```

So far we have talked about reading data from existing database tables. But how do we insert data into a database? How do we update or delete data?

In the next article we will show how to use SQL to make `CRUD` (Create, Read, Update, Delete) operations on database records. Stay tuned.

---

*I write daily about web development. If you like this article, feel free to share it with your friends and colleagues.*

*You can receive articles like this in your inbox by [subscribing to my newsletter](https://cesare.substack.com).*
Two ways to determine if any arrays in an object has an entry
Tags: javascript
Published: 2020-02-03 15:55:26

---
title: Two ways to determine if any arrays in an object has an entry
published: true
description: 
tags: javascript
---

```
let pendingAdditions = {
  hospitals: ['Silencio Hospital','St Judes'],
  licenses: ['poe-tic license'],
  medschools: []
}

let somePendingAdditions = Object.values(pendingAdditions).some(arr => arr.length);
console.log(somePendingAdditions); // true
somePendingAdditions = 
    Boolean(Array.prototype.concat.apply([], Object.values(pendingAdditions)).length);
console.log(somePendingAdditions); // true
```

Pitfalls regarding the second approach noted at: https://stackoverflow.com/questions/60042666/how-to-determine-if-any-arrays-in-an-object-has-an-entry/
Főzőiskola Debrecen, Főzőkurzus Shéfakadémia
Tags: laravel, vue, tailwindcss
Published: 2020-02-03 15:55:05

Ez a website Laravel és VueJS segítségével készült.
A Carol Gasztroműhely az egyik legjobb főzőiskola Debrecenben  főzőkurzus és élményfőzés. Kiválólehetőség cégeknek csapatépítő tréningnek. 

A Carol Gasztroműhely hasonló mint a Shéfakadémia https://carol-gasztromuhely.hu főzőiskola és főzőkurzus programjaival több, olyan felületet szeretne kitölteni, mely képviseli a minőségi fogyasztást, ételben, italban, szolgáltatásban egyaránt. Élményfőzéseink kiváló programként szolgálnak helyi embereknek és a turistáknak egyaránt. Cégeknek nagyszerű lehetőség Csapatépítő tréningeknek.
Simple way to negate a number in CSS
Tags: todayilearned, css, beginners, html
Published: 2020-02-03 15:42:31

This post was originally published on [my blog](https://dzhavat.github.io/2020/02/03/simple-way-to-negate-a-number-in-css.html).

---

I was experimenting with [Custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) a.k.a CSS variables last night. I was trying to create a simple card design for fun to see how things work. At one point I wanted to negate a variable that held a positive number.

My first attempt was:

```css
:root {
  --base-padding: 1rem;
}

.card-image {
  margin: -var(--base-padding);
}
```

Nice try, weirdo, but this doesn’t work! Come up with something smarter. 😝

Well, the “trick” was to use the [`calc()`](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) function and multiply the value of the variable by `-1`.

```css
:root {
  --base-padding: 1rem;
}

.card-image {
  margin: calc(var(--base-padding) * -1);
  /* results to margin: -1rem */
}
``` 

This is actually not a “trick” at all. It’s how math works. Hurray for math! 🎉

The same technique works the other way around as well - converting a negative number to a positive one.

```css
:root {
  --base-top-position: -1rem;
}

.card-image {
  top: calc(var(--base-top-position) * -1);
  /* results to top: 1rem */
}
```

Is there another way to negate numbers in CSS? Let me know in the comments below.

Hope you learned something new.

Oh, and if you’re curious how I used that in my card design...

{% codepen https://codepen.io/dzhavat/pen/rNaXwYX %}
If one knows, "how to use a framework" - it doesn't mean one knows the framework
Tags: javascript, beginners, jquery, react
Published: 2020-02-03 15:24:47

In simple words this post is about, *From the excitement of learning a syntax to diving deeper into the internals of frameworks and to make the right decision for each application.* 

Yes, there are jobs out there that pay if one knows how to use a framework. They are good to start with. But in parallel, if the effort is not put in learning the basics of the language, the engine that runs and the interactivity - it may get hard to build a career by switching to learn the usage of frameworks.

Let's take an instance of jquery vs core-javascript concepts. In my personal observation, jquery experts had more knowledge about jquery than a few javascript developers about javascript. And of course, javascript developers had to leave out a few job options. But in the long run, it is worth it as they get to learn any new framework with much ease and also they feel a lighter loss than a framework expert.

If we take two-way binding or virtual-dom, we should put the effort into learning why they are needed and when. If we get to read, "use redux only when needed", it's good to take the next step in knowing why is it said so.

If we don't do this, frameworks over frameworks will keep the developers rolling from one knowledge base to another.

When enough developers do this, the companies can form a team of core-language developers and not use any frameworks in a lot many scenarios. Many companies take a decision to use a framework because it gives them stability due to the availability of framework-developers.

In the long run, if we create framework developers, it would be an inefficient usage of `developer base`' learning-time as someone who might have put 4-5 years in a framework might see another framework gaining more attention.

This is not against any frameworks, they are needed because we lack in teams that can build the same with the base knowledge of a language alone. In the past, companies have seen instability with the same. Also, they are very much needed in a few scenarios where the requirements match the need.

It was to remind us(especially myself) to learn any core language in depth.

*I am a frontend developer. This may not apply for a few backend scenarios which I might not be aware of. Thanks for reading!*
[VIDEO]Refactoring Endpoints with Relationships in a Swift API 🌚♥️🌝(Swift 5.1/Vapor 3)
Tags: thetealpickle, backend, vapor, swift
Published: 2020-02-03 15:18:03

---
title:[VIDEO]Refactoring Endpoints with Relationships in a Swift API 🌚♥️🌝(Swift 5.1/Vapor 3)
published: true
description: 
tags: #thetealpickle #backend #vapor #swift
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/cj45sxmogr6xkx4fqfhs.PNG
---


PART 2. In this video, I walk through refactoring endpoints to access and create model relationships within a Swift-based API. The Swift API created in this video leverages the Vapor 3 framework. Models naturally interact with other models and in Vapor these model interactions are made possible by creating relationships. There are two types of relationships, one-to-many and many-to-many.

This video is PART 2 of the model relationship videos. Part 1 shows how to create relationships within the models and database.

{% youtube _MYO8VpnkeU %}

Code for this video can be found on @THETEALPICKLE’s GitHub at the cheese-api-swift repository 👉🏾 https://github.com/thetealpickle/cheese-api-swift 

Want to follow along? Get the starter code at the cheese-api-swift repository on the vapor-relationships-start branch 👉🏾 https://github.com/thetealpickle/cheese-api-swift/tree/vapor-relationships-start

Follow me on social media @THETEALPICKLE to stay connected with the Pickle universe 🌎

https://instagram.com/thetealpickle
https://twitter.com/thetealpickle
https://github.com/thetealpickle


<b>Brought to you by JESSICA JEAN JOSEPH © THETEALPICKLE</b>
Quick tip on how to update your projects dependencies (nodejs)
Tags: node, npm, javascript, strapi
Published: 2020-02-03 15:16:05

If you want to keep your project secure, fast and enjoy the latest features of all your dependencies, it's important to keep them regularly up-to-date. since this is just a quick tip and not a full blog post, i won't go into details on why you should update your projects dependencies.

## The problem

What are they used for? Do you really need them? Are they correctly ordered between `dependencies` and `devDependencies`? This may sound a bit obvious but if you're working on a project that you haven't initialized or where people were free to add dependencies, I'm pretty sure that you don't have a full control of what you're using.

To correctly update your dependencies and being able to adapt your code with the potential breaking changes, it's important that your dependencies contain a CHANGELOG file, some documentation or even better a migration guide.

Usually, a lot of dependencies have a `CHANGELOG.md` file at the root of their repository. This file contains the list of the changes (bugfixes / features) released with each new version. If the updates follow the semantic versioning, it'll be easier to predict if an update will be easy or not.

## Updating using npm
There's no viable way of doing this is npm but installing a global package might help, you need to install a new global dependency by running

```sh
$ npm i -g npm-check-updates
```
The to check for an update run the following

```sh
$ ncu -n -u
```
the `-n` finds the newest versions available instead of the latest stable versions while the `-u` means overwrite package file 

> https://www.npmjs.com/package/npm-check-updates

## Updating using yarn

By default, Yarn allows you to upgrade your dependencies in an interactive way. You just have to run `yarn upgrade-interactive` and you'll be prompted with all the possible updates (that follows the versions you've set in your package.json file) you can do.
for example
```sh
$ yarn upgrade-interactive
```


That's all, hope you enjoyed this tip consider to share it with your friends :)