teleren/devto huggingface dataset:
What are some of your favorite blogs?
Tags: discuss, askdev, watercooler
Published: 2021-02-11 13:52:27

---
title: What are some of your favorite blogs?
published: true
description: Trying to find some great personal blogs
tags: [discuss, askdev, watercooler]
//cover_image: https://direct_url_to_image.jpg
---

I have been trying to keep track of others' personal blogs by bookmarking them whenever I stumble across a good article, and I try to return every once in a while to see if they have come out with something new. The process of finding those gems on the internet is difficult sometimes. My "process" of finding them is to try and click on personal blog posts that come up on Google searches, so I feel behind the curve sometimes on reading quality content written by individuals. I am curious if anyone else does something similar to support smaller, independent, or personal blogs. Please share them if you do! Some of the blogs that I frequent are:

- [Last Week in AWS](https://www.lastweekinaws.com/)
- [Robin Wieruch's blog](https://www.robinwieruch.de/)
- [Troy Hunt's blog](https://www.troyhunt.com/)
- [Yan Cui's blog](https://theburningmonk.com/)
- [Andree Toonk's blog](https://toonk.io/index.html)
- [Dominik Braun's blog](https://dominikbraun.io/)
- [Gergely Orosz's blog](https://blog.pragmaticengineer.com/)

(Okay some might not be very small, but I still enjoy them and only recent discovered them!)
How to measure the time javascript function with performance.now()
Tags: performance, javascript, beginners
Published: 2021-02-11 13:50:41

Sometimes, we want to know how is the performance or time spend in some function or process, it can be solved using performance.now().

performance.now() help us to get time in milliseconds, and we can measure the time between some function complete his process.

## Using performance.now
We can take the current performance.now() and compare with the same when our function finishes the process, like my example.

```javascript
function getUsers() {
  console.log("Start...")
  let from = performance.now();
  setTimeout(() => {
    console.log("Getting users..")
    let to = performance.now()
    let total = from - to;
    console.log(`Total miliseconds ${total}`); 
  },3000)
}
// Total miliseconds -3003
```

If you want to learn more about it please go free to read more in 
- https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
- https://developers.google.com/web/updates/2012/08/When-milliseconds-are-not-enough-performance-now?hl=en
Refetch active Apollo queries in PWA Studio on user action
Tags: javascript, graphql
Published: 2021-02-11 13:39:33

In some use cases you need to refetch your GraphQL queries on a user action. To do this you need to tell your `<query>` component to refetch the data. Triggering this can be hard to do from a different part of your code base.

**As an example:**
I have a B2B webshop. The customer is on the product page and can see regular/general prices. But when he logs in the product info/prices need to update to reflect his special info/prices.

There is no easy way to do this besides either doing a page reload that will force reload the whole page and queries or use Apollo's `client.resetStore()` but this will reset the whole store and refetch all active queries.

To do this more surgical we can use something like this snippet.
```
// refetchQueriesByName.js

const findQueries = (manager, names) => {
    const matching = [];
    manager.queries.forEach(q => {
        if (q.observableQuery && names.includes(q.observableQuery.queryName)) {
            matching.push(q);
        }
    });
    return matching;
};

export const refetchQueriesByName = (names, client) => {
    return Promise.all(
        findQueries(client.queryManager, names).map(q =>
            q.observableQuery.refetch(),
        ),
    );
};
```

Implementation
```
// packages/peregrine/lib/talons/SignIn/useSignIn.js

import { refetchQueriesByName } from 'PATH_TO/refetchQueriesByName';

    const handleSubmit = useCallback(
        async ({ email, password }) => {
            setIsSigningIn(true);
            try {

                ...

                // Place somewhere after 'const destinationCartId = await retrieveCartId();'


                // These names are the actual names you declared in your graphql files
                await refetchQueriesByName(
                    [
                        'productDetail',
                        'relatedProducts',
                    ],
                    apolloClient
                ); 

                ...

})
```
React Portfolio in 5 minutes
Tags: react
Published: 2021-02-11 13:36:52

In the job market today, it's always nice to show prospective employers your chops.

**Problem**
Website design is an art, a serious art. It takes a long time to 'get there' so... We'll bypass that part and borrow from what's freely available. 

**Use Free Templates**

Here's a nice free [Landing Page](https://github.com/issaafalkattan/React-Landing-Page-Template) template for React.

- Open Visual Studio Code (VSC) to a new folder named LandingPage.
- Click on Terminal/New Terminal
- Type in this command
```
git clone https://github.com/issaafalkattan/React-Landing-Page-Template.git
```
- Open VSC Code to that folder just installed. File/Open Folder
- You should see this:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/z6q0mth69aa75o76k5ou.jpg)
- Click on Terminal/New Terminal
- Type in these commands:
```
npm install 
npm audit fix
npm run start
```
Do you see this?

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

Congratulations! You now have a landing page which you can begin customizing following the patterns already there. 

Tips:
[GitHub](https://github.com/) is the goto place for all open source software. It is the incubator of many of the [NPM packages](https://www.npmjs.com/search?q=keywords:react) we find. It's probably the best place to look for [free React Templates](https://github.com/search?q=free+react+template).
 

JWP2021 React New Portfolio
Amazing image placeholders with blurhash
Tags: react, typescript, javascript
Published: 2021-02-11 13:25:49

Few weeks ago I was playing around with [Wolt](https://wolt.com/en) iOS app, I was really impressed by how the app handled image load and placeholders. After looking around I finally found [Blurhash](https://blurha.sh)

## Why would I need it?

Blurhash can help with transforming boring image placeholders into something more.

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

<i>[source](https://blurha.sh/)</i>

## Using with TypeScript and React

#### Install

```bash
yarn add blurhash
```

#### Encode an image
```ts
import { encode } from 'blurhash';

const loadImage = async (src: string): Promise<HTMLImageElement> =>
  new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = (...args) => reject(args);
    img.src = src;
  });

const getImageData = (image: HTMLImageElement): ImageData => {
  const canvas = document.createElement('canvas');
  canvas.width = image.width;
  canvas.height = image.height;
  const context = canvas.getContext('2d');
  context.drawImage(image, 0, 0);
  return context.getImageData(0, 0, image.width, image.height);
};

const encodeImage = async (url: string) => {
  const image: HTMLImageElement = await loadImage(url);
  const imageData: ImageData = getImageData(image);
  return encode(imageData.data, imageData.width, imageData.height, 4, 4);
};
```

#### Store blurhash alongside your images
When storing images to S3 bucket, I usually run encode function on the image from S3 and store it alongside the image url in the database so that it's easier. 

Personally I store image in it's own object representation as follows:

```json
...
"image": {
  "url": "https://project-uploads.s3.amazonaws.com/i/...",
  "blurhash": "LKO2?U%2Tw=w]~RBVZRi};RPxuwH"
}
...
```

#### Using with React

After storing the hash on the server, it's quite easier to use it with React without any manual decoding with [react-blurhash](https://github.com/woltapp/react-blurhash).

```jsx
import { BlurhashCanvas } from 'react-blurhash';

<Blurhash
  hash='<image_hash>'
  width={400}
  height={300}
  resolutionX={32}
  resolutionY={32}
/>
```

<i>Note: you can also decode the hash manually, checkout [blurhash docs](https://github.com/woltapp/blurhash) for more details</i>

## Experiment online!

There's an online generator available if would like to try it out yourself.

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

Happy Coding 🎉
Django image resize on the fly
Tags: django
Published: 2021-02-11 13:14:20

####Init
Django model with image field

####Purpose
Resize image to some template size (typed size)

####Short
* Catch original image from field
* Resize it through `PIL` and save to `BytesIO` *output*
* Send `output` to `ContentFile`
* Send `ContentFile` to `File`
* Run `self.avatar.save(<name>, file, save=False)` in model save method

####Detail
ResizeImageMixin

```
import uuid
from PIL import Image
from io import BytesIO
from django.core.files import File
from django.core.files.base import ContentFile
from django.db import models


class ResizeImageMixin:
    def resize(self, imageField: models.ImageField, size:tuple):
        im = Image.open(imageField)  # Catch original
        source_image = im.convert('RGB')
        source_image.thumbnail(size)  # Resize to size
        output = BytesIO()
        source_image.save(output, format='JPEG') # Save resize image to bytes
        output.seek(0)

        content_file = ContentFile(output.read())  # Read output and create ContentFile in memory
        file = File(content_file)

        random_name = f'{uuid.uuid4()}.jpeg'
        imageField.save(random_name, file, save=False)
```
models.py
```
class User(Base, AbstractUser, ResizeImageMixin):
    def __str__(self):
        return f'{self.username}'

    def save(self, *args, **kwargs):
        if self.pk is None:
            self.resize(self.avatar, (200, 200))

        super().save(*args, **kwargs)
```
Splunk - Calculate duration between two events
Published: 2021-02-11 13:12:52

If you are monitoring your application with Splunk, you can easily create some cool dashboards to see quickly what append. And, in some cases, you want to know how much a treatment took.

To do it, you have to do a **transaction** following the next model
```
[search] | transaction [common value between events] startswith="[key=value of a parameter of the first event]" endswith="[key=value of a parameter of the second event]" 
```

<br/>

### Example

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

With this example, we want to check the duration between the log L1 and the log L4. And our common value is the id of the transaction. 

So our search will look like :

```
[search] | transaction transactionId startswith="step=P1" endswith="step=P4" 
```
Following the same process, you can check the duration between P1 and P3, P2 and P3 ...

<br/>

### Result
The result of this request will contain the two logs and a new field: **duration**.

Knowing that, you can :
* display the value with the others
* do some stats with 
```
...| stats max(duration)

...| stats min(duration)

...| stats avg(duration)
```
* display it in a table
```
...| table duration
```
* use this request in a dashboard
* ...

<br/>

---

<br/>

I hope it will help you!
How to Make an .ico File Using the macOS Terminal
Published: 2021-02-24 14:16:26

---
title: How to Make an .ico File Using the macOS Terminal
published: true
date: 2021-02-11 13:03:36 UTC
tags: 
canonical_url: https://mjswensen.com/blog/how-to-make-ico-file-macos-cli/
---

Suppose you have an icon or logo at multiple resolutions and would like to combine them into a single `favicon.ico` file for your website. These are the commands you need to get up and running from the comfort of your own terminal.

## Step 1: install ImageMagick

Check out the [ImageMagick downloads page](https://imagemagick.org/script/download.php) for instructions on how to get it running on your machine. Personally, I like to use containerization to keep my Mac free from extraneous software that I rarely use, so I’ll install ImageMagick in a Docker container instead (make sure you have Docker installed):

```
docker run -it --rm -v /absolute/path/to/icons/directory:/workdir -w /workdir ubuntu
```

This command will drop you into a `bash` session on the container. From there, it’s easy to get ImageMagick installed:

```
apt update
apt upgrade
apt install -y imagemagick
```

Tip!

ImageMagick has a dependency on `tzdata`, so you will be prompted to configure your time zone upon installation. Since this is an ephemeral installation, you can just type `1` for each prompt to get through the installation process quickly.

## Step 2: create the file

ImageMagick gives us a handy `convert` command that makes the process super easy:

```
convert input-file-16x16.png input-file-24x24.png input-file-32x32.png input-file-64x64.png favicon.ico
```

This will create the desired `favicon.ico` file.

## Step 3: verify the .ico file

ImageMagick also provides a nice utility called `identify` for inspecting our file to ensure it is formatted as we expect.

```
identify favicon.ico
```

The output should look something like this:

```
favicon.ico[0] ICO 16x16 16x16+0+0 8-bit sRGB 0.000u 0:00.000
favicon.ico[1] ICO 24x24 24x24+0+0 8-bit sRGB 0.000u 0:00.000
favicon.ico[2] ICO 32x32 32x32+0+0 8-bit sRGB 0.000u 0:00.000
favicon.ico[3] ICO 64x64 64x64+0+0 8-bit sRGB 24838B 0.000u 0:00.000
```
Daily Developer Jokes - Thursday, Feb 11, 2021
Tags: jokes, dailydeveloperjokes
Published: 2021-02-11 13:00:17

---
title: "Daily Developer Jokes - Thursday, Feb 11, 2021"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Thursday%2C%20Feb%2011%2C%202021"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1259ab8700f.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q___: Why was nobody given food at the developer conference?

___A___: It was a serverless function!
 -->
Use Rails `link_to_unless_current` for navigation links
Tags: ruby, rails, webdev
Published: 2021-02-11 14:58:58

---
title: Use Rails `link_to_unless_current` for navigation links
published: true
date: 2021-02-11 13:00:00 UTC
tags: ruby,rails,webdev
canonical_url: https://boringrails.com/tips/rails-link-to-unless-current
---

We’re all familiar with the classic Rails `link_to` helper. But did you know there is a `link_to_unless_current` variant?

It works just link `link_to` except that it doesn’t create a link if the browsers current URL is the same as the link target.

![](https://boringrails.com/images/link_to_unless_current.png)

## Usage

Simply replace `link_to` with `link_to_unless_current`. If you are not already on the page, a normal `<a>` tag will be rendered. If you are on the page already, only the text will be rendered.

```erb
<nav class="flex flex-col space-y-1">
  <%= link_to_unless_current "Dashboard", dashboard_path %>
  <%= link_to_unless_current "Team", teams_path %>
  <%= link_to_unless_current "Projects", projects_path %>
  ...
</nav>
```

When you are on `/dashboard`, this template will output:

```erb
<nav class="flex flex-col space-y-1">
  Dashboard
  <a href="/teams">Teams</a>
  <a href="/projects">Projects</a>
  ...
</nav>
```

You can also pass in a block to render (instead of the link name). This can be unless for making shared views. For instance, you could make a partial with actions for a `Post`.

```erb
<%= link_to_unless_current "+ Comment", new_comment_path do
  link_to "Back", posts_path
end %>
```

## Other Variants

As you might expect, there are other variants like `link_to_if` and `link_to_unless` if you want to specify your own conditional logic for rendering a link or not.

You might want to show a list of all `Post`s, but if you are logged in as an admin, the title should be a link to an edit page.

```erb
<% @posts.each do |post| %>
  <%= link_to_if @user.admin?, post.title, manage_post_path(post) %>
<% end %>
```

## Additional Resources

Rails API Docs: [UrlHelper#link\_to\_unless\_current](https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to_unless_current)

Rails API Docs: [UrlHelper#link\_to\_if](https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to_if)

Rails API Docs: [UrlHelper#link\_to\_unless](https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to_unless)

* * *
[![](https://boringrails.com/images/twitter-banner.png)](https://twitter.com/_swanson)
How We Developed a Smart Vault
Tags: security, android, ios
Published: 2021-02-11 12:58:38

We developed a smart vault that lets you keep all the confidential information away from prying eyes. Truster is the most convenient variant for providing the maximum level of protection.

▫️  multi-accounts: you can create as many accounts as you want on one device
▫️  offline mode: the client can view, create, edit, delete records even without the Internet
▫️  data synchronization algorithms work like a charm. Data appears on another device and neither the server nor even the mobile client knows what kind of data it is
▫️  the data is encrypted and the version of the decrypted data and even encryption keys are not stored anywhere - the data belongs only to the user, no one even has the technical ability to find out the user's data
▫️  it is possible to change the master password - in this case, all user data will be re-encrypted

With Truster all the passwords, credit cards, secret documents, and notes you have will be kept in one place.
 
Try Truster 👉🏻 https://apps.apple.com/ru/app/truster-private-holder/id1548676597
Credit Card input with auto-dash in Vue
Tags: vue, creditcard
Published: 2021-02-11 12:44:36

Hey Dev.to community!

Recently when I was working on a project I encountered a very good problem (yes problems are good)! What I simply wanted to do was to create a field for credit cards with auto-dashing. Meaning that I wanted a dash (-) character between every 4 digits. I've searched through the net but people were overcomplicating the matter and finally, I've got to do it myself :)))). Here is the Codepen that I am sharing with you of the solution I found out and thought it might be useful for some people as well. I didn't add anything extra except for a small SCSS so the field doesn't look so crappy :). _To be honest, I hate when people add a lot of unnecessary stuff to a simple code snippet. It makes it confusing!_.

{% codepen https://codepen.io/AdnanBabakan/pen/zYoKoQx %}

So here is the simple explanation:

- Obviously, you need an input field! I made a simple text field since I don't need a number field. You can later make it to only accept numbers. The `pattern` and `inputmode` are only for mobiles to understand that they should bring up a numeric keyboard. You can ignore these two attributes if you want. Max length is 19 which is 16 + 3. 16 digits for the card number and 3 dashes maximum. I've bound this input to a Vue data called `creditCardNumber`.
- This is the step everything happens! In order to make changes, we need to watch the `creditCardNumber` property. First, we get the real card number. The real card number only consists of digits without dashes. Be careful! If you don't implement this step the watch will dive deep into an infinite loop! Next, we split the real number using anything from 1 character to 4 characters using RegEx. Now we have an array that we can join by dash character! Finally, we replace the dashed number with the current one and we are done!

Keep in mind I've simplified the problem. You can limit the field to numbers only using extra RegEx or other methods.

I hope this comes in handy someday for someone!

BTW check out my Vue cheatsheet if you are starting to learn Vue:

{% link https://dev.to/adnanbabakan/vue-cheat-sheet-1-194a %}
How to visit a page that is on my computer with Cypress
Tags: cypress, testing, automtion, e2e
Published: 2021-02-11 12:22:02

## Learn how to test an HTML page that is only in your local environment

Today's **“Pinch of cypress”** is inspired by a question from [**Rafael Barbosa**](https://www.linkedin.com/in/rafael-barbosa--/).

Thanks for the question, Rafael!

With **Cypress**, if you want to test a page that is only available on your computer, that is, it is not available via the internet, you can use the relative path of the page in the `cy.visit()` command.

Let's look at an example of an application that simulates Twitter.

```js
// cypress/integration/sampleTwitterApp.spec.js

describe('Tweets', () => {
  beforeEach(() => cy.visit('../../Tweets/index.html'))

  it('tweet using a custom command', () => {
    cy.get('.tweet')
      .its('length')
      .then(numberOfTweetsBefore => {
        const newTweet = 'Yay, custom commands with Cypress!'

        cy.tweet(newTweet);

        cy.get('.tweet')
          .its('length')
          .should('be.gt', numberOfTweetsBefore);
        cy.get('.tweet')
          .last()
          .should('contain', newTweet);
      });
  });
});
```

As you can see, instead of passing an URL to the `cy.visit()` command, I am giving it the relative path `../../Tweets/index.html`, and my test works as if I was visiting a page on the web. 😄

Short post, but hopefully useful.

👋 See you next time!
___

Any thoughts about the series?

I'm looking forward to hearing your feedback!

___

This post was originally published in Portuguese on the [**Talking About Testing**](https://talkingabouttesting.com/2021/02/11/como-visitar-uma-pagina-que-esta-em-meu-computador-com-cypress/) blog.
___

Would you like to learn about **test automation with Cypress**? Get to know my online courses on [**Udemy**](https://udemy.com/user/walmyr).