teleren/devto huggingface dataset:
The parable of the turkey: or, The way things have always been done
Tags: programming, codequality
Published: 2019-06-26 23:41:34

*Cover photo by Randy Fath via Unsplash*

### The story goes:

A young couple, happily married, is celebrating their first Thanksgiving together. The bride wants to cook her husband her family's classic turkey recipe, and asks her mother for the recipe.

Her mother sends her the recipe, and the woman cooks it to perfection. Even the breast-meat is perfectly tender and juicy. However, at the end, her husband remarks: "Darling, where are the legs? I always liked those best."

"There on the side," she tells him.

He picks around the bird, and he seems still confused, so she points them out to him. He asks, "but love, why are they shaped like this? They don't look like drumsticks to me. They're all... squashed-y?"

She says, "It's in the recipe. You take the legs off, take the bones out, and cook the meat on the side."

He still doesn't understand, but the turkey was very tasty, so he leaves it be.

---

The next day, the woman calls up her mother and asks, "So mom, about that turkey recipe. Why do we take the bones out and cook the meat on the side?"

Her mother replies, "Hm, I don't actually know why. Your grandmother just always did it that way, and it's her recipe."

---

The mother and grandmother are having a pleasant brunch one morning, and the question of the turkey comes up once more.

"Oh, right," says the mother. "Ma, I gave my daughter your turkey recipe, and she asked about the turkey legs."

"What about them?" asked the grandmother.

"Well, why do we cut them off, take the bones out, and cook the meat on the side?"

The grandmother bursts into gales of laughter. "I did that when you were a kid because my pan was too small to fit the whole turkey!"

---

At least, that's how it was related to me. [There are many variations.](https://www.snopes.com/fact-check/grandmas-cooking-secret/)

![A boston terrier in a turkey costume riding a roomba.](https://media.giphy.com/media/348lrWhJAUiuhkcePl/giphy.gif)
*I couldn't find a good way to transition here. I'm making the best of it.*

You've probably sussed out the moral of the story by now. But just to make sure we're all on the same page:

## Doing what has always been done without knowing *why* is not a good idea.

Imagine that the young woman had never asked, but instead had to hack some other rig together for her turkey. In several generations, what would this recipe look like? I don't think it would be quite as tasty if all those hasty fixes had been passed down as "I don't know why it works, don't touch it" over the generations.

So if you see some code, and you don't know how it works, you'll get a tastier... program? if you figure it out. It might be on [StackOverflow](https://meta.stackoverflow.com/questions/361904/what-is-stack-overflow-driven-development) or in your legacy codebase full of technical debt, but consider it your job to *learn* what it's doing.

Don't fall for the trap of [copy-paste driven development](https://www.alejandrodu.com/2016/04/copy-paste-based-development.html)!
🇦🇺🦘 Looking for Events in Australia? 🦘🇦🇺
Tags: irl, meta, eventsinyourcity, opensource
Published: 2019-06-26 23:21:20

I was reading about the latest initiative from the DEV team on IRL.dev this morning

{% link devteam/introducing-a-new-initiative-irl-dev-6ck %}

And thought it'd be a great time to raise awareness to some of the other more general event lists I know of in Australia 🦘.

If you're looking for a list of Microsoft-centric **user groups** check out this list maintained by Microsoft MVP [Loryan Strant](https://mvp.microsoft.com/en-us/PublicProfile/4032157?fullName=Loryan%20%20Strant):

{% github loryanstrant/anzusergroups %}

But if **conferences** are more your jam then take a look at the Dev Events list maintained by [Readify](https://readify.net):

{% github readify/devevents %}

_Psst: I've created [a website view of it if you don't want to read Markdown](https://oz-tech-events.aaron-powell.com/)_

Both of these lists allow for anyone to submit PR's with updates, just check out the number of contributors on each repo!

Hope to see you at an event down under! 👊
Clean architecture - Your approach
Tags: explainlikeimfive, help, architecture
Published: 2019-06-26 23:07:06

I've been looking into how to implement "clean architecture" in my projects. I like the idea of it but I've found it hard to visualise it. The examples I am looking at are simple "Counter" apps (using React with Typescript) and the setup seems overkill. The approach will obviously become more and more beneficial as the project grows.

## The Question

I'd like to hear from other developers; 
- Who has experience using clean architecture practices. What are the pros and cons?
- What was your "aha" moment, when everything started making sense?
- What resources did you use to help you learn the fundamentals of clean architecture?
- How would you explain it to a 5-year-old?
Why you might need to type check your code
Tags: typescript, strongtyping, javascript
Published: 2019-06-26 22:51:38

How many times have you had your code say, 'this is undefined' or 'that is not a function at so and so'? How long does it take you to even find the source of these errors? let alone fix them.

One of the worst things is finding out that you have a runtime error even though you haven't written any incorrect code. Sometimes, It can take a lot of sleepless nights to realise that you've made a type error, that you assigned an object of class Dog to a variable that should be an object of class Car.

such errors can usually be avoided by using type checking. What is type checking you ask? Well, (Very) simply put, you use data types like `int`, `char`, `MediaStream`, etc. while defining variables, functions, and other things and these data types are then used to check whether the variables with the right data types are being used. So if you were to assign an object of class Car to an object of class Dog, you should get an error, provided, the two types are incompatible.

Look, I get it. Strong typing increases the verbosity of your code. Nobody likes writing class names like `SessionUtilDataTokenizer` over and over again. Even coming up with proper names can be daunting at times (that is a topic for another time). 

![naming variables joke](https://pbs.twimg.com/media/CTsivppWsAAj8vz?format=jpg&name=small)

By using strong typing, you can avoid most (IMO) type errors at compile time and get rid of them one by one. I think that is definitely more convenient than pulling out your hair trying to figure out what exactly the error is.

## Oh! and did I tell you about IntelliSense?

IntelliSense is a general term for a variety of code editing features including code completion, parameter info, quick info, and member lists. 
Simply put, It helps you remember which function or property is available on what variable, its type and what it does. This way, you don't need to have everything in the back of your head.

![intellisense gif](https://code.visualstudio.com/assets/docs/editor/intellisense/intellisense.gif)

At the end of the day, you are responsible for any bugs that creep into your code, but type checking can help you reduce them.
Translate your browser extension in seconds
Tags: showdev, javascript, showweb, chrome
Published: 2019-06-26 22:19:06

---
title: Translate your browser extension in seconds 
published: true
description: Quickly translate your browser extension in seconds.
tags: #showdev, #javascript, #showweb, #chrome
---
![](https://thepracticaldev.s3.amazonaws.com/i/auj1bos16fpfau4z9q6g.gif)

Hey 👋,

If your reading this you probably came for the same reason, I did in the past. How do I easily translate my browser extension to other languages?

Well as part of my startup [Helperbird](https://www.helperbird.com) I needed to translate the browser extension to other languages to increase the reach. So I looked at different solutions and found one promising GitHub repo but it wasn't perfect.

With Chrome or Browser extensions, you have a folder layout like this.

```bash
_locales/{{languageCode}}/messages.json
```

Where the original one by [Thomas Brüggemann](https://www.npmjs.com/package/translate-extension-json) while great doesn't fit in into the browser extension development flow.

So I forked the extension and rewrote it, to make it for browser development (Also dont worry, I will be adding feature to the original master) . So if you're a browser extension developer. You can do the following now.

## Installation

```bash
npm install -g translate-extension-json
```


## Usage

You need a [Google Translate API Key](https://cloud.google.com/translate/).

```bash
translate-extension {{apiKey}} {{location of json file}} {{Translate from}  {{Tanslate too,Tanslate too,Tanslate too,}}
```

e.g.

```bash
translate-extension-json iuOHAEbo9H788d34h93h4dioue2I locales en es,fr
```

This would translate all strings in `_locales/en/messages.json` (relative to current folder in the shell) from English to Spanish and French, based on the Google Translate API language codes.

The target languages list is optional. When not present, it will be translated to all languages supported by Google Translate.



# See it in action.

![alt text](https://github.com/Helperbird/i18n-translate-json/raw/master/demo/kap.gif "Demo")


If you liked this project and guide, you can follow me here.

- [Twitter](https://www.twitter.com/robertjgabriel)
- [Github](https://www.github.com/robertjgabriel)


The node module code is [here](https://www.npmjs.com/package/translate-extension-json) and the Github source is [here](https://github.com/Helperbird/i18n-translate-json)
Get the Raise — Determine your value and get promoted in tech
Tags: career, webdev
Published: 2019-06-26 22:14:04

---
title: Get the Raise — Determine your value and get promoted in tech
published: true
description: How to determine your value and get promoted as a software engineer
tags: #career #webdev
---

This week, three people asked me about salary negotiation.  

I'm shit at negotiation  
But I can tell you what I've learned in 10 years of full-time tech work.  

Become visible.  
Visible people find more opportunities than invisible people.  

I've received exactly one raise that wasn't driven by me.  
I was moved between teams and my new manager immediately bumped me up $10k.  
Turns out he was embarrassed by how little I was being paid.  

That was a wake up call.  

That year I started creating training materials and giving conference talks.  
I made industry relationships and asked them what their compensation looked liked.  

I learned that I was still 25-35% under market.  
So I asked for it and got it.  

This would not have happened if I hadn't been proactive.  
I would have remained unaware and waiting.  

It's not a company's job to serve your career.  
Companies exist to make money.  
Part of that equation is keeping expenses low  
And you are an expensive expense.  
You need to be retained for as little as possible.  
It's your job to set that number.  

If you're waiting for a raise —  
Expecting someone else to notice and evaluate your work —  
Stop.

Be visible.  
Meet people.  
Ask them about money.  
And go get it.  

💸 @chantastic


P.S.

This is from my weekly newsletter.
[Subscribe](https://tinyletter.com/chantastic) if you'd like to get short thoughts on software, career, and family in your inbox.
How often do you restart your computer?
Tags: discuss
Published: 2019-06-26 21:06:38

---
title: How often do you restart your computer?
published: true
description: Discussion about how often you restart your computer or kill tabs.
tags: discuss
---

I abuse my computers. I'm terrible. I hate restarting and I hate closing tabs.

{% twitter 1143985978685575168 %}

My policy is this, when my computer gets to be slow enough to annoy me I'll finally restart it.

I'm the worst.

What's your policy?
SwiftUI Observations and Early Notes
Tags: podcast, swift, swiftui
Published: 2019-06-26 20:48:48

I put together a new episode of the CompileSwift podcast in which I talk about the new SwiftUI and dive into some of the details. For example, did you know that you can use SwiftUI views in existing applications and vice versa? Do you want to know more?

[You can find the episode here on Anchor](https://anchor.fm/compileswift/episodes/SwiftUI-Observations-e4eqnl)
What's the plan to monetise Devto?
Tags: discuss
Published: 2019-06-26 20:28:21

---
title: What's the plan to monetise Devto?
published: true
description: 
tags: #discuss
---

Wondering what the plans are to make this site pay its way? Just to put it out there: my preference would be to pay a monthly subscription. I don't want my data sold or the advertising jerks to get hold. 

I think we all understand you have servers to run, offices to rent, electricity bills to pay... Happy to pay my way.

This is a good thing - don't fuck it up.
Saving form data to multiple records in Yii2
Tags: php, yii, beginners
Published: 2019-06-26 20:00:07

# Big mystery
Last time I was write a CMS in Yii2 where user have own profile with personal information and relationships to terms.
Updating user profile is not problem in Yii2 but when I want updating profile and terms relationships it was a mystery.

# Simplicity is a key
So I created [Yii2 model](https://www.yiiframework.com/doc/guide/2.0/en/structure-models) which represents user edit personal form.
To constructor I was pass User which is [ActiveRecord](https://www.yiiframework.com/doc/api/2.0/yii-db-activerecord)

I want to save all user profile details, remove all terms relationships and create new ones. 

```php
class EditPersonalForm extends Model{

    public $user;

    public $name;

    public $events;

    public function __construct(User $user, $config = [])
    {
        parent::__construct($config);

        $this->user = $user;

        // user details
        $this->name = $user->getName();

        // terms details
        $this->events = $user->getEventsList();
    }

    public function save($runValidation = true)
    {
        $userProfileUpdated = $this->updateUserProfile($runValidation);

        $this->updateUserEvents();

        return $userProfileUpdated;
    }

    public function updateUserProfile($runValidation)
    {
        $this->user->scenario = $this->scenario;
        $this->user->load(Yii::$app->request->post(), $this->formName());

        return $this->user->save($runValidation);
    }

    public function updateUserEvents()
    {
        TermRelationship::deleteAllEventsByUserID($this->user->getId());
        $this->createTermRelationships($this->events, 0);
    }

    private function createTermRelationships($termsID, $termType)
    {
        foreach ($termsID as $termID){
            $data = array(
                'termID' => $termID,
                'termType' => $termType,
                'userID' => $this->user->getId()
            );

            (new TermRelationship($data))->save();
        }
    }
}
```
I complete the form fields by giving property value in `__construct()`.
New instance of edit form model is created in controller action and passed to view.

Also what I gonna do in controller is load data from request by standard Model `load()` method and save edit form hence saving user details and his relations with terms.

```php
// standard controller action

if ($editForm->load(Yii::$app->request->post()) && $editForm->save()) {
    //success message
    
    return $this->refresh();
}
```

That would be enough, greetings plum!
¿Cuál es la diferencia entre is_single() e is_singular()?
Tags: funciones
Published: 2019-07-01 19:56:46

---
title: ¿Cuál es la diferencia entre is_single() e is_singular()?
published: true
tags: Funciones
canonical_url: https://kungfupress.com/cual-es-la-diferencia-entre-is-single-e-is-singular/
---

La función **is_single()** devuelve **true**  si el contenido actual es una entrada única, un **post**.

La función **is_singular()** devuelve **true**  si el contenido actual es una entrada, página, custom post type, etc. Cualquier tipo de contenido, pero que sea único. Devuelve **false** si el contenido actual es una página de categoría, etiqueta o un listado cronológico de entradas.

Ambas tienen en común que se utilizan para variar el comportamiento o el aspecto de la página actual en función del tipo de contenido que se está cargando.

Ten en cuenta que, si no hay contenido, también devuelve **false,** así que no te confíes pensando que tienes una pila de artículos por delante cuando en realidad no hay nada.

![Keep Calm. I am single.](https://kungfupress.com/wp-content/uploads/2019/06/keep_calm_iamsingle.jpg)

Un ejemplo para que lo veas más claro: 

```
if ( is_singular() ) { 
  //carga un script y una hoja de estilos 
  wp_enqueue_script( … ); 
  wp_enqueue_style( … );
} else { 
  // carga un paginador
}
```

La función is_single() tiene dos funciones hermanas de utilidad similar: 

- is_page(): si el contenido actual es una **página** única.
- is_attachment(): si el contenido actual es un **enlace** único (no creo que nadie use esto a estas alturas) 

La función **is_singular()** no tiene hermanas, pero si tiene varias “contrarias”:

- is_category()
- is_tag()
- is_archive()
- is_author()
- is_search()
- is_tax()

A toda esta “familia» tan numerosa se les llama **Conditional Tags** y todas aceptan un parámetro que puede ser de tipo entero, cadena o array para poder ser más específicos en la búsqueda:

- En el caso de is_single() y sus hermanas se le puede pasar el ID concreto del contenido, el slug o un array de identificadores o slugs. 
- En el caso de is_singular(), y sus contrarias, se puede especificar el tipo de contenido concreto o un array de tipos de contenido.

Por otro lado, no sé si has caído en la cuenta de que estas funciones tal como las ves tienen utilidad en las plantillas de los temas, pero no en un plugin.

Desde un plugin tienes la misma funcionalidad a través de la clase **WP_Query** que incorpora todos estos métodos: is_single, is_page, is_archive, is_preview, is_author, is_category, is_tag, is_tax, is_search, is_feed, is_comment_feed, is_404, is_attachment, is_singular.

### Referencias

- [Diferencia entre is_page(), is_single(), is_singular() y posibles usos.](https://www.proyectoalfa.es/diferencia-is-page-single-singular-wordpress/)
- [WordPress Codex: Conditional Tags](https://codex.wordpress.org/Conditional_Tags)
- [WordPress Codex: Class Reference / WP_Query](https://codex.wordpress.org/Class_Reference/WP_Query)
Introducing a New Initiative: IRL.DEV
Tags: meta, eventsinyourcity, irl, opensource
Published: 2019-06-26 19:44:05

As was discussed in this post yesterday, meeting up irl is awesome.

{% link https://dev.to/awwsmm/dev-conference-2fb9 %}

No, we aren't (yet) announcing a first conference, but we are introducing an initiative to help our community members organize and bridge the online-offline gap.

The such community-led event actually happened last night in New York City, with support from DEV staff but not officially run by us. Some of us were in attendance and it was absolutely awesome. It got us really excited about this going forward.

We had speakers we recognized from the community, and lots of familiar faces. We also had new faces who were being introduced to DEV for the first time. (Speakers are absolutely not necessary for a great meetup by the way, feel free to organize less structured gatherings).

![](https://thepracticaldev.s3.amazonaws.com/i/er7r1kjmzbmrl44cluij.png)

If you would be interested in organizing a meetup in your city, visit our new website:

# **[✨ IRL.DEV ✨](https://irl.dev)**

We expect organizers to be able to commit to managing their meetups on an ongoing basis and being in touch with us to help enriching, inclusive events.

This new website is an open source project, and because it is separate from our main mothership, contribution should be fairly low-barrier. As of now it is mostly designed for accepting applications to organize events, but we can evolve it together to be a hub for information about how the community is organizing itself.

Bridging the online-offline gap in creative ways will be a fun project all in all. 😄

{% github https://github.com/thepracticaldev/irl.dev %}

It's a Gatsby site, which is an experiment in a different approach for our team and it should be a lot of fun to see where this goes. @aspittel lead the way in making this happen.
Help needed regarding apache kafka golang
Tags: help, kafka, go
Published: 2019-06-26 18:20:33

Hi all, I am currently working on Apache Kafka using go/golang confluent library. I have some doubts regarding consumer and its APIs.

1. I am using pause and resume APIs of the library and doing manual commits. Let's say, I send 100 messages and without committing, I paused consumer and resume it afterward. I notice it didn't consume those 100 messages again but it started consuming the latest messages. Is this an expected behavior? If yes, is there a way to consume those 100 messages again.

2. When I am resuming the consumers, after some processing, I am doing manual commit. I noticed the return offset committed is -1001 for a partition. I am not able to understand why it is happening and what it means? Did I lose all the data or the commit failed?

3. Can someone please explain to me auto.offset.reset - latest and earliest?


Thanks
React - Updating self-dependent state
Tags: react
Published: 2019-06-26 18:13:06

---
title: React - Updating self-dependent state
published: true
description: How to update state that depends on the current state
tags: react
---
In React, sometimes we need to update a state value taking into account the current state.

For example, if we are writing a Poll app and we have a button or another component to update the number of votes, we can do something like this:

```js
incrementVotes = () => {
  const currentVotes = this.state.votes;
  this.setState({
    votes: currentVotes + 1
  });
};
```

The above code could work, but considering that `setState()` is an asynchronous function, a better solution is to send a function to `setState()` as follows:


```js
  incrementVotes = () => {
    this.setState(prevState => {
      return {
        votes: prevState.votes + 1
      };
    });
  };
```

**Update**

With the first approach, we have the risk that our `state` does not update immediately, for example if our votes count is 10 and we have a user that is too fast clicking the button, we could have two calls to `incrementVotes()` in which the value of `this.state.votes` is the same and in the end we have a final value of 11 when the correct value should be 12.

Maybe there is a thin probability of this occurring but this is a good way of protecting our application of this kind of bugs.