teleren/devto huggingface dataset:
How to insert random data for testing in PostgreSQL?
Tags: postgres, database, sql, productivity
Published: 2022-04-06 21:14:52

Sometimes you need to have hundreds of thousands or even millions of rows to test the performance of your database and queries because we can't explore performance if we only have 10 rows, so before playing with performance we need to make some test data.

But can't we just use a shell script or a (your favorite language) script, yes you can but try generating 1M rows with your script then save to the database but your script memory will not be able to take 1M rows in memory so you will have to create a stream or generate chunks of data then save to the database or a CSV file then import it to the database, but why all that while you have amazing functions from PostgreSQL to help you.

### The `repeat()` Function

A function that takes two parameters `repeat(string to repeat, number of times to repeat)` to repeat a string.

**Example:**
```sql
INSERT INTO test (stringColumn) VALUES (repeat("Wow ", 3));
```

This will insert a row with a stringColumn with a value of `Wow Wow Wow`

### The `generate_series()` Function

A function that takes two required parameters and an optional one `generate_series(start, stop, increment by [default is 1])` to generate a series of numbers each in a row.

**Example:**
```sql
INSERT INTO test (id) VALUES (generate_series(1, 1000));
```

This will insert 1000 rows each with an id equal to the previous id incremented by one.

### The `random()` Function

A function that generates a random float from 0 to 1.

**Example:**
```sql
INSERT INTO test (id) VALUES (trunc(random()*100));
```

This will generate an id of three digits from 0 to 100 (trunc to make the float an integer).

### ALL TOGETHER:

Let's create a players table:
```sql
CREATE TABLE players (id INT, about TEXT, age INT);
```
Then let's insert 1000 rows with some random data:
```sql
INSERT INTO players (id, about, age) VALUES (generate_series(1, 1000),  repeat('A cool player. ', 2) || 'My number is ' || trunc(random()*1000), trunc(random()*10 * 2 + 10));
```

---

[**Subscribe to my newsletter**](https://amrelmohamady.hashnode.dev/)

I hope you like this article, you can follow my LinkedIn at:
[https://www.linkedin.com/in/amr-elmohamady](https://www.linkedin.com/in/amr-elmohamady)
How Promotions Ruin Dev Careers w/ Shopify's Dir. of Engineering James Stanier
Tags: career, management, podcast, techtalks
Published: 2022-04-06 21:13:43

*We want to make the Dev Interrupted podcast a vital, enjoyable part of your week.* ***Please take 2 minutes and answer our new [Listener Survey](https://www.surveymonkey.com/r/PRYRNC5).*** *It lets us know a bit about you, what you want from Dev Interrupted and what you want from podcasts in general!*

In so many professions, the reward for exceptional work is a promotion to management. Unfortunately, for developers whose programming gets them singled out for promotion, the skills to manage a team have nothing to do with the work that got them recognized in the first place.

James Stanier, Director of Engineering at Shopify, understands the pitfalls of being promoted from an IC to an engineering manager, and began writing as a way to think through the mistakes he himself was making. 

Today, James is an accomplished author; his first book Become An Effective Software Engineering Manager debuted in 2020, and his second book Effective Remote Work was published earlier this year.   

On this week’s episode of Dev Interrupted, James talks about how developers can prepare themselves for a role in management, or alternatively, why they should avoid a career in management altogether. He also discusses why Shopify loves remote pair programming, how to find your voice as a developer and why writing a book can be a spiritual experience.

{% spotify spotify:episode:6OtJ6GUdTySQ6TjbWHotDQ %}

## Episode Highlights Include:
* (4:06) Why so many devs are afraid of becoming managers
* (16:51) The 90 day management test
* (22:46) Remote work has increased dev productivity by default
* (27:47) Why Shopify loves remote pair programming
* (33:01) Finding your voice as a developer
* (41:17) Writing a book can be a spiritual experience

## [You're Invited to INTERACT on April 7th](https://devinterrupted.com/event/interact/)

Join engineering leaders from Netflix, Slack, Stack Overflow, American Express & more at LinearB's virtual engineering leadership conference, [**INTERACT**](https://devinterrupted.com/event/interact/) on **April 7th, 2022.**

**1 day, 20 speakers, 1,000s of engineering leaders - all driven by the Dev Interrupted community.** If you are a team lead, engineering manager, VP or CTO looking to improve your team, this is the conference for you!

[**Learn more here**](https://devinterrupted.com/event/interact/)


![Join INTERACT at https://devinterrupted.com/event/interact/](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2xhtonct1vkpjhrtzfl3.png)
Good leaders create principles, not rules
Tags: leadership, productivity, hr
Published: 2022-04-06 20:18:39

#### Follow me on Linkedin if you like provoking posts about software development. [Let's socialize!](https://www.linkedin.com/in/alexsandro-souza-dev/detail/recent-activity/shares/)

When we analyse why companies create rules, it is not because we have a problem with the top performers. It's the bottom 30% of the crew who need rules. Top performers hate rules. What drives their engagement is autonomy, ownership, and trust from the leaders.

Rules cover specifics, focusing on the instance at hand. We can never create enough good rules to cover every situation. And even if we could, that would still not be the solution.

Principles the other hand, cover generalities, allow adaptation to unforeseen circumstances, don't put you in a box, and enable you to use your best judgment. 

Entrepreneurial individuals work better in high-performance environments based on guiding principles. They don't need thick manuals full of dos and don'ts.

Good leaders teach principles and enable their teams to innovate. They start with trust. Instead of seeing people as problems, they see them as solutions. If you know Price's law, you will make sure not to add measures focusing on the 30% from the bottom.
Stefan Kudla Software Developer
Published: 2022-04-06 20:17:17

Hi, my name is Stefan Kudla and I am a Software Developer. You can find me over at my personal website, usually chattering about Software or Coffee, or maybe even something of slight importance.

I am currently a freelancer with a focus on full stack web development, though am currently looking for full time positions.

My Socials:

[LinkedIn](https://www.linkedin.com/in/stefankudla/)

[Instagram](https://www.instagram.com/stefankudla/)

[Facebook](https://www.facebook.com/stefan.kudla.software.developer)

[Github](https://github.com/stefkudla)

[My Website](https://stefankudla.com/)
Website without images?
Tags: webdev, python, django, beginners
Published: 2022-04-06 20:14:01

**A website without images would probably be the worst thing on the Internet today.**

And even with that fact, some developers do not know how to add images to a website.


Here is how to do that using the django admin panel.

Let's use a model class name profile.

```
 class Customer(models.Model):
  user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
  name = models.CharField(max_length=200, null=True)
  email = models.CharField(max_length=200)

```

First thing we have to do is to add image field to the class

```
 image = models.ImageField(null=True, blank=True)

```

We have to add the pillow package, the python Imaging Library  is a free and open-source extension library for Python that adds support for accessing, processing, and saving a wide range of image file types.

We can the install the pillow package by running this command

```
 pip install pillow 

```
We can proceed by adding the data to the database by running the migrations 

```
 python  manage.py makemigrations
 python  manage.py migrate

```

The next step is to update the media url and root. By doing this, we are telling django where to store the images. You should add this to the settings.py file
```
 MEDIA_URL = '/images/'
    
 MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')

```

We should head to the site's urls.py file and import some packages 

```
 from django.conf.urls.static import static
 from django.conf import settings
```



This is how it should look like. 

```
 from django.contrib import admin
 from django.urls import path, include
 from django.conf.urls.static import static
 from django.conf import settings
    
 urlpatterns = [
     path('admin/', admin.site.urls),
     path(' ', include('store.urls')),
    ]
   
```


Then we add this to the urls.py file. This is to add a route for the images

```
 urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

```
After this,we can upload the image using the django admin panel.

Finally, we can render the image on the html file.

```
 <img class="thumbnail" src="{{profile.image.url}}">

```

**Bonus Tip**

What if the image was deleted or missing. We would not want the entire website to suddenly stop working. 

There are two ways of going around this error

**1. Add a property decorator to the model class**

```
 @property 
    def imageURL(self):
       try:
        url = self.image.url
       execpt:
        url = ""
       return url

```
 **2. Use an IF statement**

```
   {% if product.image %}
       <img class="thumbnail" src="{{profile.image.url}}">
   {% else %}
       <img class="thumbnail" src="{% static 'images/placeholder. png %}">
   {% endif %}
```
useReducer Hook Use Cases In React
Tags: react, usereducer, hooks, state
Published: 2022-04-06 20:04:30

I want to present you in this post some use cases for useReducer hook.

These are three. 

## Toggle

When we want to toggle state, being state a boolean, we can do:

```javascript
import {useReducer} from 'react'

export const useToggle= (initialState=false)=>{
  const [isSomething, toogleIsSomething]= useReducer(state=> !state, initialState)
  return [isSomething,toggleIsSomething]
}
```

So whenever we want to use this hook we can do:

```javascript
function SomeComponent(){
  const [isSome, toogleIsSome]=useToggle()
  return ...
}

export default SomeComponent
```

## Update

Another use case is when we want to update state, we can do so:

```javascript
import {useReducer} from 'react'

export const useUpdate= (initialState={})=> {
  const [state, updateState]= useReducer((state, obj)=>({...state, ...obj}), initialState)
  return [state, updateState]
} 
```

We can use it like this:

```javascript
function AnotherComponent(){
  const [state, updateState]= useUpdate({c:3})

  const someHandler= ()=>{
    updateState({a:1,b:2}) // after that state will be {a:1, b:2, c:3}
  }

  return ...
}

export default AnotherComponent
```

## Dispatch

Then we have the typical use case where we pass an action as a second parameter to the reducer function and we get a dispatch function as a result:

```javascript
const reducer=(state, action)=>{
  switch(action.type){
    case 'UPDATE':
      return {...state, ...action.payload}
    default:
      return state
  }
}

function ThirdComponent(){
  const [state, dispatch]= useReducer(reducer,{c:3})

  const someHandler= ()=> {
    dispatch({type:'SOMETHING', payload: {a:1, b:2}})
  }

  
  return ...
}

export default ThirdComponent
```

If you come with another use case not presented in this post please it would be nice if you leave it in the comments.

Thanks.
Relational Algebra operators cheat sheet
Tags: database, productivity, dbms, relationalalgebra
Published: 2022-04-06 19:46:59

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob5xyrr9ftb7ms3w6atg.png)
Hi! I wrote this cheat sheet about all most used operators/symbols in Relational Algebra:
https://medium.com/@lorenzotinfena/relational-algebra-operators-symbols-cheat-sheet-529b49dd8c3f
React 18 killer feature
Published: 2022-04-06 19:37:49

Probably you already heard about the release React v18.0
I wish to introduce you to a new killer feature of the release. 

Let’s take a look at this example. 

```javascript
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

async function fetchSomething() {
  await new Promise((res, rej) => {
    setTimeout(res, 100);
  });
}

function Counter({ count, flag }) {
  useEffect(() => {
    console.log("render Counter");
  });
  return <h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>;
}

function App() {
  const [count, setCount] = useState(0);
  const [flag, setFlag] = useState(false);

  useEffect(() => {
    console.log("render App");
  });

  function handleClick() {
    setCount((c) => c + 1);
    setFlag((f) => !f);
  }

  return (
    <div id="ttt">
      <button id="b" onClick={handleClick}>
        Next
      </button>
      <Counter count={count} flag={flag} />
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector("#container"));
```
Just one button counter. And `handleClick` handler set state for flag and count.

React is smart lib and intentionally doesn't render components twice, despite in the handler we update state twice. Because React batches event handlers. 

But what if we a bit change `handleClick` function and add some async magic here

```
async function fetchSomething() {
  await new Promise((res, rej) => {
    setTimeout(res, 100);
  });
}

function handleClick() {
    fetchSomething().then(() => {
      setCount((c) => c + 1); // Causes a re-render
      setFlag((f) => !f); // Causes a re-render
    });
}
```

And if you run again the code, you most probably came across with double rendering components, `useEffect` tells you in the console. This is because React can't batch state changes. What is the reason? Asynchronous handlers run **after** the event in a callback, not **during**. Obviously, all async operation is non-blocking and executes after the main stack. 

In React 18 this issue is solved, you just need to replace in the code `ReactDOM.render` to `ReactDOM.createRoot`

```
ReactDOM.createRoot(document.querySelector("#container")).render(<App />);
```

createRoot enables **Concurrent Mode**. Now your application can be more productive and doesn't trigger re-rendering after each state changes within one event handler, which is great!
This is how **Automatic batching render** feature works.

I Hope, I brought you some useful content.

Follow me on 🐦 [Twitter](https://twitter.com/modelfak) if you want to see more content.
Automating the Git commit message prefix
Tags: programming, git, bash, tutorial
Published: 2022-04-06 19:24:07


If you’re a programmer you probably **love automating** the daily tasks you do daily, don’t you? Well, if you don’t you probably should.

The current project I work on has a specific Git Branching model that follows the Jira tasks number. In a nutshell, here are the requirements: when I tackle a story/feature task, it has a number, let’s say TASK-1. You move the ticket into in-progress and you also create a first sub-task called “Implement” or “Fix” or something similar.

If you’re like me and like to see the process visually, here’s how it looks:

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

In addition to the branching model above, the commit messages must follow the following rule for the prefix: MainTask/SubTask: [commit message]. For example for the task in the flow above, the commit message can be TASK-1/TASK-2: Write the first draft.

For me, this was the most cumbersome thing, mainly because I want to commit often, not have a single commit with all the finished code, so whenever I did a commit I had to look up the story number and the sub-task I am working on.

Let’s see how we can automate this prefix.

## Part 1 – Git Hooks and config

Git is very extendible: you can have various custom Key-Value configurations for each local repository or for the global Git system itself. We’re gonna be using some custom Git configurations to suit our automation.

[Read the rest of the tutorial here](https://pacurar.dev/automating-the-git-commit-message-prefix/).
How to generate CSS overview report on your page
Tags: tooling, webdev, javascript, css
Published: 2022-04-06 16:31:28

Have you heard of CSS Overview in Chrome DevTools? It's a preview feature allowing you to easily check styling on your page and improve them! In the generated report you can see general stats about your page, all used colors, eventual problems with insufficient color contrast ratio, used fonts, and media queries. And everything just in a few clicks and seconds. How to do so?

1. Open Chrome DevTools
2. Go to the page you want to test
3. Open Chrome DevTools 
4. Click 3 dots in the right up corner
5. Choose More Tools > CSS Overview from the dropdown
6. Click `Capture overview`

After a few seconds you'll receive the full report containing 5 sections:
- Overview summary
- Colors 
- Font info
- Unused declarations 
- Media queries.

![Example CSS Overview report from Chrome DevTools](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/maqfr1urgtdpolu9kanu.png)

Each section is self-explanatory but there are some details worth mentioning. 

First of all, the colors section. You can use it to check all colors used on your webpage. If any of them is incorrect (e.g. is outside of your color palette) you can just click the color tile and Chrome DevTools will display you the list with all elements using the given color. Each element on this list is also clickable, so you can easily navigate to that in the Elements tab (and change it if needed). Super nice and simple!

The next interesting thing is a list of elements with an insufficient color contrast ratio. It's an extremely important factor in making your webpage accessible for everyone. Also, this tile is clickable. So - you can go to the element in the Elements tab and fix it (you can read in my [previous article](https://dev.to/domizajac/how-to-use-chrome-devtools-to-find-a-color-fixing-insufficient-color-contrast-ratio-on-your-html-element-546k) how to do so).

Font info and Media queries sections are quite similar. You can easily detect all fonts/media queries used on your webpage (with a number of occurrences), review them and go to the Elements tab to change them if needed. Much more useful than sounds from the article.

Last but not least, check the Unused declarations tab. Removing not needed code makes your code cleaner, less vulnerable to mistakes, and just better. Also, it has a positive impact on performance. Definitely, worth checking.

The CSS Overview should be your best friend in web development. Improving consistency and styling of your webpage, removing unneeded code, fixing problems with accessibility - all those aspects are super important in creating great webpages. Let Chrome DevTools help you and check this feature today!
HttpParams Builder for Angular
Tags: angular, typescript, codereview, javascript
Published: 2022-04-06 18:59:40

Greetings,

Today I was revisiting the code of an Angular project I'm working on, and I went through the following piece of code in a service class:

```typescript
  import { HttpParams } from '@angular/common/http';

  buildParams(filter: any) {
    let params = new HttpParams();

    if (filter.uf) {
        params = params.append('uf', filter.uf);
    }

    if (filter.cidade) {
        params = params.append('cidade', filter.cidade);
    }

    if (filter.pagination) {
        const pagination = filter.pagination;

        params = params.append('sort', 'cidade,asc');

        if (pagination.pageNumber) {
            params = params.append('page', pagination.pageNumber);
        }

        if (pagination.pageSize) {
            params = params.append('size', pagination.pageSize);
        }
    }

    return params;
  }
```

As you may know, the `HttpParams` is an immutable class used to declare the query params passed on a http request using `HttpClient`. 

And because of the `HttpParams` immutability aspect, its instance doesn't change, instead, every time I call `.append()` a new instance is created. So I have to reassign the `params` variable with the new instance.

`params = params.append('uf', filter.uf);`

Although necessary, it doesn't look very nice. So I came up with a builder to keep things cleaner, and turn the code above in to the this:

```typescript
import { HttpParams } from '@angular/common/http';
import { HttpParamsBuilder } from 'http-params.builder';

buildParams(filter: any) {
    const builder = new HttpParamsBuilder();

    builder
      .append('uf', filter.uf)
      .append('cidade', filter.cidade);

    if (filter.pagination) {
        const pagination = filter.pagination;
        builder
            .append('sort', 'cidade,asc')
            .append('page', pagination.pageNumber)
            .append('size', pagination.pageSize);  
    }

    return builder.build();
  }
```

In my opinion, it looks more concise. Here's the implementation of the `HttpParamsBuilder`:

```typescript
import { HttpParams } from '@angular/common/http';

export class HttpParamsBuilder implements IHttpParamsBuilder {
  private params: HttpParams;

  constructor() {
    this.params = new HttpParams();
  }

  append(param: string, value: any): this {
    if (value) {
      this.params = this.params.append(param, value);
    }
    return this;
  }

  build(): HttpParams {
    return this.params;
  }
}

interface IHttpParamsBuilder {
  append(key: string, value: any): this;
  build(): HttpParams;
}
```

Let me know your thoughts!
Web3 Enthusiasts Have a Home: MetaPunk
Tags: web3, meta, forem, watercooler
Published: 2022-04-06 18:58:40

---

series: Forem Community Highlights

---

If you were hanging around earlier today, you might have seen that DEV suffered some partial downtime due to a DNS configuration issue. We were back online promptly, but these things are never fun.

This post has nothing to do with that — but it does seem thematically relevant. **Today, I want to highlight a growing Forem called [Metapunk](https://www.metapunk.to)**.

***

## **[Check out the MetaPunk Community 🦙🚀](https://www.metapunk.to)**

Metapunk is a community of Web3 and NFT traders, developers, and enthusiasts in general. It’s a community celebrating innovations in decentralized technology taking part in a decentralization-first Forem Network.

**If you post about Web3 on DEV, you’ll get a mixed back of enthusiasm and skepticism** — which I think is perfectly healthy. However, if you’re in on this technology and want to connect and learn, it is absolutely fabulous that [Metapunk](https://www.metapunk.to) exists as an option. This is why we are pushing Forem to complement DEV in any of these specialized spaces. DEV will always trend towards the mean in software advice and enthusiasm, which is not strictly what Web3 folks need to further their dialog and learnings. 

Of course, Web3 posts are welcome here, but we very much encourage joining and cross-posting to [MetaPunk](https://www.metapunk.to). I hope to see you around. 😋 

***

One last thing. You’ll notice **"Sign up with Forem"** as an option alongside GitHub and email. This is a service we now offer to most seamlessly navigate the ecosystem and manage your identity. We want you to be able to **bring your full self without having to bring your full data**, so making this distributed ecosystem as straightforward as possible in the long run is really important. Create a [Forem account](https://account.forem.com/) and connect it with your DEV account [via your settings](https://dev.to/settings). 🙂

Happy Coding and Collecting!