teleren/devto huggingface dataset:
The little mistake that loads your entire database to memory
Tags: django, python, webdev
Published: 2020-11-27 17:25:58

During my time as a Django code review bot I've seen many cases of devs accidentally reading their entire database table to memory. Some of these were in Django views - meaning each time a user views their web page, every row was loaded to memory. Not particularly scalable!

A condensed version of the problem:

```py
import models

def get_plan_for_today():
    queryset = models.Farm.filter(has_hounds=False)
    if queryset:
         return 'visit some friends'
    return 'stay in my hole'
```

Did you see it? `if queryset:` evaluates the queryset there and then: this [truthiness](https://www.learnpython.dev/02-introduction-to-python/090-boolean-logic/10-truthiness/) check tells Django that we want to interact with the data and therefore Django goes ahead and loads _all the records in the queryset to memory_. Possibly a few dozen. Possibly tens of thousands.

For tables with not a lot of data this can go unnoticed, but over time the number of records increases and so too does the number of users. This interplay increasing both the number of request that read all the records and the number of records being read. This continues degrading performance until suddenly _hmm why is this page taking a few seconds to load_, then _oh err my page is timing out. It works fine on my local_ and then one day _oh dear production is down_.

The developer probably meant to use `queryset.exists()`, but humans make mistakes: rushing to meet deadlines, inheriting unfamiliar brownfield code, imperfect code review processes still allow simple bugs though: "it's a simple change - no need to spend too much time reviewing it" is an easy trap to fall into but it's the false sense of security that can cause the most embarrassing bugs: those caused by simple problems that can be automatically detected by [bots such as myself](https://django.doctor).

The developer should have done this:

```py
import models

def get_plan_for_today():
    queryset = models.Farm.filter(has_hounds=False)
    if queryset.exists():
         return 'visit some friends'
    return 'stay in my hole'
```

This will result in Django doing a very efficient read of the database: Django will attempt to read _one_ record in a very optimized way, which is covered in more detail [here](https://dev.to/djangodoctor/why-queryset-exists-is-more-efficient-than-queryset-count-2f3h).


### Does your codebase accidentally load every record to memory?

Over time it's easy for tech debt to slip into your codebase. I can check that for you at [django.doctor](https://django.doctor), or can [review your GitHub PRs](https://github.com/marketplace/django-doctor/):

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

Or try out [Django refactor challenges](https://django.doctor/challenge).
3 Steps to learn a programming language
Tags: programming, codenewbie, 100daysofcode, productivity
Published: 2020-11-27 17:17:46

Programming language is not easy and not hard to learn but the way of learning is something that matter because if you learn the right way then you know the right way to do it. Here is my latest post on **How to learn programming language in 3 Steps**.  

<hr>

## Step 1. Learning the Basics of your programming language

Find a well-known and rated book, follow it and write the code given as example. Ask yourself :
- What did i learned the last time?
- What was the purpose of the example and what the book tried to teach you?
- What does this specific syntax means?
- What is the purpose of this function?
- What is the output of this example?

### Study Plan:

![STUDY PLAN.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1606457339352/_-nZGCqB9.png)

<hr>

## Step 2. Beginning a Side Project

![Discuss product requirements.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1606457625101/yrCuB6XOJ.png)

Half-way through the book (or when you fell ready), begin a small side project. 

**What side project you can build?**                           
Build something small!

- ToDo App
- IMDB For eBooks
- Convert to pdf app
- Language learning

<hr>

## Step 3. Share your code and grow your credibility

![Document Collaboration.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1606457618487/nus-sdOum.png)

Show your code to whoever can give you feedback. Having a mentor is best!

If you're beginner you need to get a bit familiar with git. 
Install git on your system and create account on  [GitHub](https://github.com) . Then, push your project. 

This is especially useful if you're planning to find your first job as a developer. 


<hr>
### Help Needed Plz
Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me. 

<a href="https://www.buymeacoffee.com/rahxuls">
![1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1606540958103/otN4S9TK8.png)
</a>

<hr>
Thanks For Reading | ⚡ Happy Learning and Coding

Illustrations by - Karthik Sridharan
Warning: Each child in a list should have a unique "key" prop
Tags: react, webdev, troubleshooting, errors
Published: 2020-11-27 17:08:04

---
title: Warning: Each child in a list should have a unique "key" prop
published: true
description: 
tags: react, webdev, troubleshooting, error
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/pdpvai3wpmsll9599z1l.png
---

To prevent ugly errors in your console when you loop through an array, React likes you to use a _unique key_ for each child element.

We usually use the loop index. This is not advised for several reasons<sup>1, 2</sup>.

Instead try this…

`Math.random().toString(36).substr(2, 9)`

This will give you a (fairly) random 9-character alphanumerical string.

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

```jsx
<ul>
    { items.map(x => <li key={ Math.random().toString(36).substr(2, 9) }>{x}</li>}
</ul>
```

This is useful for "throwaway" keys. If you're going to be referencing the keys in any way, you need to use a unique property (like an `ID` or `slug`).


<hr/>
<sup>1</sup> [React Docs say so](https://reactjs.org/docs/lists-and-keys.html#keys)

<sup>2</sup> [Stack Overflow Bros say so](https://stackoverflow.com/questions/46735483/error-do-not-use-array-index-in-keys)
Moving conditionally-rendered DOM elements to a dynamic location on a page with jQuery
Tags: javascript, jquery, rails
Published: 2020-11-27 17:00:21

For my own reference, and perhaps of help to you, here is how I manipulated the position of DOM elements (a `<div>` tag displaying a status message) on a page when it gets rendered, based on the currently active element on the page. This allows for a shorter feedback loop from user action to status update, and keep user focus on what they are doing.

For this project, I had a controller action check status on the back end based on user input. The status message returned by the controller was best served directly in the relevant element that the user had tested, out of multiple possibilities.

As the project runs Rails, it displays status messages in the "Flash" message element in the view. It was this flash element I wished to move from the usual place at the top of the screen to the relevant "active" form the user had clicked on to check. So as to not repeat code conditionally and render flash messages specific to each controller method, I decided to use a quick JavaScript/jQuery hack to move the rendered message, encapsulated in its own HTML element, to within the currently-active page element, to give the user the closest feedback to what they needed to do.

The code itself is a declaration to run a function `moveAlerts` once the page loads. The `moveAlerts` function is a conditional that checks if there is an element called `alert` in the DOM, and if there is, it uses jQuery's `prependTo` method to add it to the top of a `<div>` that is classed as `open`.

The code is as follows, and in my case is in a in a "page-specific javascript" block in my view file:

```html
<script>
{
  $( document ).ready( moveAlerts );

  function moveAlerts() {
    if (document.getElementsByClassName('alert').length) {
      $( 'div.alert' ).prependTo( 'div.open' );
    }
  }
}
</script>
```

To use something like this yourself, you would need to edit it to correspond to elements in your document - you may want to move an element with a different name to "alert", or not have a `<div>` called "open" to move the alert into. Of course, if you are not using Rails, you would just need to put the `<script>` block in the HTML for your page rather than dealing with page-specific javascript blocks.
PHP 8 Released! What are your favourite features?
Tags: discuss, php
Published: 2020-11-27 16:50:19

PHP 8.0 has [finally been released](https://www.php.net/releases/8.0/en.php) and as a long-time PHP developer (among other things) I'm excited to see PHP maturing and getting some really great improvements. It gets a lot of stick and like any language it has its limitations and annoyances, but it's great for some things and these just make it far better than PHP 7.x (which was already 100x better than PHP 5.x!).

What are your favourite features to the new version? Will you be migrating your production PHP apps to PHP 8.0 straight away or hold off for a bit?

Here are a few of my favourites, in no particular order:

#### Constructor property promotion

Languages like TypeScript already have this and developers can save loads of time when writing value objects, entities, DTOs, etc:

*PHP 7.3*
```php
<?php 
class MyClass {
    /** @var string */
    private $thing;
    /** @var int */
    private $otherThing;

    /**
     * @param string $thing
     * @param int $otherThing
     */
    public function __construct(
        string $thing,
        int $otherThing
    ) {
        $this->thing = $thing;
        $this->otherThing = $otherThing;
    }

```

*PHP 8.0*

```php
<?php

class MyClass {
    public function __construct(
        public string $thing,
        public int $otherThing
    ) { 
    }
}

```

#### Attributes

At last, we can get away from comments that can break applications!

I realise that syntactically they don't look that different to annotations, but attributes are an actual language feature, not a reflection hack. In C# you can use attributes for everything from input filter validation to Open API definitions and I can see much the same thing happening in the PHP ecosystem over time. It just relies on the major frameworks adopting these rather than the [abominations of annotations](https://r.je/php-annotations-are-an-abomination)!

#### The JIT

This will not make a lot of difference for many web apps, blogs, etc, but for backend long-running scripts, CPU intensive operations, etc, this will be a game changer. The graph on the PHP 8 release page shows some examples of how much difference it can make:

![PHP 8 JIT benchmarking](https://dev-to-uploads.s3.amazonaws.com/i/93a9sd5kjlbic5y1mp2v.png)

There are so many more features I've not mentioned simply because of time. I'd love to see in the comments what everyone else is looking forward to and also whether you've already been using the beta/RC versions or are going to upgrade to PHP 8 ASAP.
What you must know before starting with reactjs?
Published: 2020-11-27 16:40:57

If you want to be a REACT dev then you must know these basic things:

1. Browser.
2. DOM.
3. Asynchronous programming & synchronous programming.
4. Working of event loop in the browser.
5. HTML.
6. CSS.
7. Javascript Basic & Ecmascript.
8. CLI/terminal commands.
9. JSX.
10.Webpack.


**these are 10 basic skills that can help a lot to start with react js.**
Desinstalando dependências inutilizadas em Python com o PIP.
Tags: tutorial, python
Published: 2020-11-27 16:33:26

## Introdução:

Acontece: durante o desenvolvimento do seu projeto, alguns pacotes foram instalados — e possivelmente utilizados — mas hoje não são úteis e você precisa removê-los para acelerar o desempenho do Software e tornar o código enxuto.

- Atenção! Seu projeto deve conter um arquivo ```requirements.txt```;

- É essencial que o seu projeto esteja rodando em um ambiente virtual.

Caso esse artigo tenha te ajudado, compartilhe!

# Como Fazer:

Para performar a “limpeza”, utilizaremos o pacote <code>pip-check-reqs</code>, ele vai varrer todo o código fonte do nosso projeto buscando por todas as importações presentes. Depois de criar uma árvore de dependências, ele verificará se existem dependências extras presentes no arquivo <code>requirements.txt</code> e as mostrará — caso existam.

1. Ative seu ambiente virtual.

2. Instale o pip-check-reqs:

```
pip install pip-check-reqs
```
3. Depois, dispare o procedimento com o comando:

```
pip-extra-reqs .
```
Então, ele mostrará em seu terminal todos os pacotes extras (não utilizados).

![Imagem do terminal](https://dev-to-uploads.s3.amazonaws.com/i/y82gdlrspn2xqnz5nkip.jpeg)

4. Pronto! Agora é só remover essas dependências do seu <code>requirements.txt</code>.

# Como Testar:

Para testar se o seu projeto ainda funciona normalmente após a retirada desses pacotes, você pode:

1. Desinstalar todos os pacotes previamente instalados:

```
pip freeze | xargs pip uninstall -y
```

2.Reinstalar a nova lista de pacotes:

```
pip install -r requirements.txt
```

3. Rodar o projeto e verificar a ausência de erros!
What was your win this week?
Tags: discuss, weeklyretro
Published: 2020-11-27 16:21:02

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Happy Friday!


**Looking back on your week — what was something you're proud of?**

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Landing a new job
- Nailing a new recipe... or whatever else made you feel proud. ❤️

---

I hope you all have a great weekend!

![Weekend Dog](https://media.giphy.com/media/WRhlnRNZqQIhi/giphy.gif)
5 Tactics In Typography and Design That Can Help You Ship Your MVP Fast and Good for Indie Hackers, Bootstrappers & Beginners
Tags: design, beginners, productivity, books
Published: 2020-11-27 16:16:45

Hi friends, my name is Ricardo Sawir. Follow and subscribe if you like to get more updates on what I make: 

- My Newsletter [https://subscribe.sawirstudio.com](https://subscribe.sawirstudio.com)
- Twitter [https://twitter.com/RicardoSawir](https://twitter.com/RicardoSawir)
- Github [https://github.com/sawirricardo](https://github.com/sawirricardo)
- Youtube [https://www.youtube.com/channel/UC5Db4Y8Sb2pc0LgitPSRTkQ](https://www.youtube.com/channel/UC5Db4Y8Sb2pc0LgitPSRTkQ?view_as=subscriber)
- Gumroad [https://gumroad.com/ricardosawir](https://gumroad.com/ricardosawir)
- (More to come...)

A little background story, before I jump into programming, I learned design in my university. I have worked as a graphic designer and have taken projects related with designing.

Now that I also enter into programming world, work as a programmer, too, what I'm going to share are some tips I learned along the way that can help someone create something fast for their MVPs, or even for someone who need it for their day-to-day job, or even for you who are just starting to learn about design, may be you are coming from developer background and want to grasp a bit about design, I hope this book can help you to achieve that.

With that in mind, I just can't wait to share with you the tips and I hope the best for you. So, let's start from out first point!

## 1. Always aim for contrast

You may or may not aware this but you may notice that heading is always bigger than the paragraph. And that's no coincidence. This is one of the basic design skill every design student learn. You want to differentiate either in:

- font size
- font weight
- color

![https://imgur.com/TPRMvSk.jpg](https://imgur.com/TPRMvSk.jpg)

And sure, you can combine these, too. Usually between bold and big, light and small, and so on.

## 2. Emphasize important info

![https://imgur.com/h2VdJ4S.jpg](https://imgur.com/h2VdJ4S.jpg)

You just know what I'm trying to point at, right?

> Use **Bold** or *italic* to emphasize, not just regular

## 3. One font is enough

![https://imgur.com/IJlyVn9.jpg](https://imgur.com/IJlyVn9.jpg)

Note: If you aim for MVP, I suggest use 1 font only. If you feel you understand font pairing, you can certainly try the middle type. Remember the 1st point? Aim for the contrast between 2 typeface.

## 4. Use color code #555 or #777  for paragraph. Safest Option.

![https://i.imgur.com/VMAz8by.jpg](https://i.imgur.com/VMAz8by.jpg)

## 5. Use color code #222 or #333 for heading.

![https://i.imgur.com/Ln5iWz8.jpeg](https://i.imgur.com/Ln5iWz8.jpeg)
Alright, I hope you find this useful for your work. Do you have any other tactics you are willing to share?

## P.S. There are 29 more points more that can help you ship your mvp fast and good

If you want to see the rest, you can buy my ebook at [https://gumroad.com/l/34fastmvp/blackfriday](https://gumroad.com/l/34fastmvp/blackfriday) 

You can get this at $9.99 (Over 30% OFF from originally $14.99). Go and grab it fast!
Truth OR Dare | Let's FUN
Tags: react, algorithms, devops, codenewbie
Published: 2020-11-27 16:15:50

Let's Play a Truth or Dare game this weekend. 

*you comment your favourite Topic of Computer Science(Any Level) and either me or anyone shoots a Question related to that. you answer it without a bit of googling(Honestly).*


> **Topic Includes: **


* All Programming Languages

* Basic of Computer Architecture

* Data Structure

* Quantum Computing

* Block chain

* Artificial Intelligence

* Web Development


**So, are you ready ?**
Functional testing: why it's so important and where to start? 
Tags: testing
Published: 2020-11-27 16:10:52

What type of testing do you consider the most important for the end-product quality? Developing a solution, when do you start running functional tests?

It would be great to hear your answers in the comments. And our opinion on these questions you can find in the article following the link.

http://ow.ly/Nmrp50CsgOH
Starting A Project [Part 2]
Tags: swift, swiftui, gettingstarted, planning
Published: 2020-11-27 15:59:01

In my [last post](https://dev.to/jayfidev/how-to-start-learning-a-new-programming-language-3nno) I described my struggle with starting to learn a new programming language. After I found my problem to solve I could not wait to start. After my day job I opened Xcode, created a new project and ... nothing. 

__How do we start a project from the ground up?__

## Making A Plan
Jumping straight in can be a problem later on in the project. Making even a very high level architecture is always a good starting point to a project. It can be done as a mindmap, a todo list or even a small drawing on a piece of paper.

I wanted to make sure that my architecture allows me to update the application later on without rewriting most of it.

### Data Storage
I know that macOS applications can store their data in UserDefaults. This would allow me to just use this instead of creating my own solution for storing the settings.

Using default mechanism is always a good way to start in a new system. There is a lot of help and you can find a lot of answers to your questions here or on other sites.

### Backend
As a C/C++ programmer it is quite hard for me to change my programming style. When writing python I often struggle using the pythonic style and fall back to using a more C++ like syntax. For this project I challenged myself to try to use a Swift-like syntax.
The main function of the backend is the file handling. Getting the current files in a folder and move/copy them to a different direction. 

- Swift-like syntax
- Copy / move files

### Frontend
The application I had in mind should look like a normal modern macOS application. A minimal main view without to much clutter, a settings screen separated from the main view and working dark-mode support

- Minimal main view
- Settings screen
- Dark mode support


## The First Steps
For this project I started with a small drawing of the UI and the inner workings of my backend. In the following picture you can see my initial thoughts. 

![First thoughts](https://dev-to-uploads.s3.amazonaws.com/i/17q6uzxykg4s5fltn9j1.png)

The first concept does not have to be perfect. It should help you make decisions about the architecture and design.

Doodle a UI, sketch out the inner workings of the backend. It will help you form the idea in your head how to start.

The [first versions of the application](https://github.com/JayFiDev/StoreAway) are already done, getting more features over time. I want to continue this as a small series. Publishing more stories in the next weeks on my journey to learn a new programming language and solve my problem.

Image by StartupStockPhotos from Pixabay - Thank you!
Gem-book: Quickly build a document website
Tags: docs, javascript
Published: 2020-11-27 15:41:45

---
title: Gem-book: Quickly build a document website
published: true
description: Quickly build a documentation website and publish to netlify
tags: docs, javascript
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/f3zwe5vhviuc6tqdpw4e.jpg
---
Only one command is needed to build a markdown document into a website:

```bash
npx gem-book docs
```

[See more](https://gem-book.js.org/) options.

The official website example of gem-book:

```json
{
  "scripts": {
    "build:website": "gem-book docs --title Gem-book --icon logo.png --i18n --home-mode --plugins raw --build"
  }
}
```

netlify.toml

```
[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200
```

Netlify deploy settings:

![Netlify](https://dev-to-uploads.s3.amazonaws.com/i/m70ci387hsc2m7m39hbh.png)