teleren/devto huggingface dataset:
grepdef: a quick way to search for definitions in code
Tags: vim, grep, javascript, php
Published: 2020-08-18 21:34:38

---
title: grepdef: a quick way to search for definitions in code
published: true
date: 2020-08-15 21:18:50 UTC
tags: vim,grep,javascript,php
canonical_url: https://payton.codes/2020/08/15/grepdef-a-quick-way-to-search-for-definitions-in-code/
---

I live inside my code editor all day and something that I need to do pretty often is to search for the definition of a symbol (a variable, constant, or function). For example, I might be debugging a problem in a JavaScript file when I come across this code:

```
//...
let newData = translateDataFromRaw(rawData);
//...
```

I need to see `translateDataFromRaw` to understand how it works. How can I do this?

If I’m using an IDE or a project covered by a tags file, I can use the magical “jump to definition” feature. This is usually the best option as it is fast and nearly always accurate. However, if I’m using a simple code editor that does not have a “jump to definition” feature, or if the feature is still indexing my project (this can take quite a while sometimes), or if I want to find that function on the command-line for some other purpose without having to open up an IDE, then this will not work. What are my other options?

I could use `grep` to search my files for the string `translateDataFromRaw` and then find the definition from among the results. This works well and is pretty simple, unless that function is used in a lot of places. If there are hundreds of results, it may take me forever to find the one I want.

To help with this situation, I wrote a little command-line tool called [grepdef](https://github.com/sirbrillig/grepdef). With it, I could just run `grepdef translateDataFromRaw` and I’ll instantly get the grep result for the definition.

```
$ grepdef translateDataFromRaw
./src/translators.js:function translateDataFromRaw(data) {
```

It’s way faster than “jump to definition” on some of the projects I work with. I even have it integrated into my editors with the plugins [vim-grepdef](https://github.com/sirbrillig/vim-grepdef) and [vscode-grepdef](https://github.com/sirbrillig/vscode-grepdef).

## How does it work? 

It’s basically the same as the `grep` technique I described above, except that it has two advantages:

First, it uses a regular expression to find symbol definitions unique to a specific code language. This can definitely be inaccurate, but in my experience it’s close enough.

Second, it uses [ripgrep](https://github.com/BurntSushi/ripgrep) which is blazingly fast.

All together, `grepdef` saves me hours of development time. Maybe it will help you too?

Right now it only supports two language types: PHP and JavaScript/TypeScript, but it’s built to be easily extensible to other languages. Please [suggest them as issues](https://github.com/sirbrillig/grepdef/issues/new)!
How to Dump a Database using DBeaver
Tags: database, mysql, dbeaver
Published: 2020-08-15 21:06:29

This article is no longer available for free.

You can still get access to it with a small fee [here](https://letsremote.lemonsqueezy.com/checkout/buy/5e7e161a-0b32-4d37-8b5f-e35b98dfa8e7?discount=0).

Thank you for understanding,
Bilal
Create your own Markdown Previewer with React
Tags: beginners, codenewbie, react, javascript
Published: 2020-08-15 20:47:40

When I was starting to learn how to code I never thought I could do my own Markdown Previewer. I thought it was too advanced and that it would be impossible to do it on my own. But later I learned that it is quite simple, I mean it is not simple to parse Markdown code, but we can use packages to do all the hard work for us. And only care about the styling.

And that's what we're gonna be building today, in this tutorial, I'll be using React, but it can be easily done with vanilla js.

## 1. Create your React project
On your terminal type the following commands:
```
npx create-react-app markdown-previewer
npm install --save react-markdown
```
The first command will generate our app, and the second command will add react-markdown to our dependencies. The react-markdown is the dependency that will parse markdown to jsx for us.
## 2. Planning and Creating our first components
Our App is gonna be very simple, the UI will be divided into 2 panels. The left one being the input, and the right one being the output.

So let's create them. On your src folder create both components, with MarkdownInput being a ***textarea*** and the MarkdownOutput a ***div*** tag. Inside App.js let's add markdownInput to our state, then assign it with an empty string, like so: 

```javascript
this.state = {
	markdownInput: ''
}
```

Every time a user types on the form we want to update the markdown input value, to do so let's create a function that sets the state for us.

```javascript
handleChange = (evt) => {
	this.setState({ markdownInput: evt.target.value});
}
```

Now let's pass it down as a prop to the MarkdownInput component and also pass markdownInput to our MarkdownOutput component. On App.js inside the render function:

```javascript
<MarkdownInput handleChange={this.handleChange} />
<MarkdownOutput source={markdownInput} />
```

On MarkdownInput.js, add the handleChange function:

```javascript
handleChange = (evt) => {
	this.props.handleChange(evt);
}
```

And inside the render function, add a textarea element and add a onChange event listener.

```javascript
<textarea onChange={this.handleChange}></textarea>
```

On MarkdownOutput.js, import the ReactMarkdown component from react markdown:

```javascript 
import ReactMarkdown from 'react-markdown';
```

And inside the render function, add a div element wrapping the ReactMarkdown component. To our ReactMarkdown component render our markdown we need to pass our markdown to the source prop:

```javascript
<div>
	<ReactMarkdown source={this.props.source} />
</div>
```

And that's it! Now, all we need to do is to add our styles. Here's the [link](https://github.com/JesseSousa/markdown-viewer-react) to my repository in case you want the same styles that I'm using.
Check how green your web project is
Tags: actionshackathon
Published: 2020-08-15 20:42:25

[Instructions]: # (To submit to the GitHub Actions x DEV Hackathon, please fill out all sections.)


### My Workflow
Ever wondered, how much carbon gets produced every time someone visits your site? You can now do that, and track the changes in the effects on the environment on every push or PR! With the help of [website carbon](https://www.websitecarbon.com/) and their API, you can get a badge in your README and an artifact on every workflow run on where your projects currently sit.

Here is how the badge can look like:
![Demo of badge](https://green-action.vercel.app/api/card?p=99)

### Submission Category: 
DIY Deployments


### Yaml File or Link to Code
(Don't forget to edit any parts that you want, especially the URL and the branch)
```yaml
name: Website green-o-meter

on:
  push:
    branches: main

jobs:
  update-stats:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@master
        with:
          persist-credentials: false 
          fetch-depth: 0
      - name: green-website
        uses: filiptronicek/green-action@main
        env:
            URL: https://dev.to # Your measured URL
      - name: Commit files
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git commit -m "Update carbon image" -a
      - name: Push changes
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: main # Branch to push to
```
All the code:
{% github https://github.com/filiptronicek/green-action %}

### Additional Resources / Info

Used GitHub projects:
{% github https://github.com/actions/upload-artifact %}
{% github https://github.com/ad-m/github-push-action %}
{% github https://github.com/vercel/ncc %}

Help with the project:
I learned a lot from implementations of GH Actions by {% user yo %}
(check him out, he's an awesome developer)
[Reminder]: # (Submissions are due on September 12th (11:59 PM PDT) and winners will be announced on September 23!)
Project Patterns and Tools - Configuring EditorConfig
Tags: editorconfig
Published: 2020-08-15 20:40:39

Following the previous post, today we are going to configure EditorConfig on VSCode.

That tool can help us to change the code format settings for the IDE configuration.

But how does it work? EditorConfig is a file format and collection of text editor plugins for maintaining consistent coding styles between different editors and IDEs.

Also, this plugin attemps to override user or workspace settings with settings found in .editorconfig files. No additional or vscode-specific files are required.

So, let's start to set it up.

![alt text](https://media.giphy.com/media/3o84sJXOIrnjvlwnF6/giphy.gif "Time to learn")

The first thing we need to do is install the EditorConfig for VS Code extension.

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

When the installation has finished, we can right click on the file explorer and select the "Generate .editorconfig" option.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/21jvvgzlw1avr61fb44h.gif)

We will create a file named ".editorconfig" with the following content.

**Editoconfig Content**

root = true

[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = false

That file contains the configuration we want to use to keep our code with the same format for our team.

We can find indent style, indent size, charset, insert final newline and a lot of different options.

Now, we are going to change the option *trim_trailing_whitespace = false* to *trim_trailing_whitespace = true* and add a new option like this *end_of_line = lf*.

*trim_trailing_whitespace = true* will remove any whitespace characters preceding newline characters.

*end_of_line = lf* will control how line breaks are represented.

As a result of our change the file should be like this now:

root = true

[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = false
end_of_line = lf

Finally, to make sure our code uses the new format properly, we need to open the project's files and save them again.

That's it!

From now, our code will be formatted with this rules and we can use the same configuration for our team, doesn't matter if they are using VS Code or other IDEs. The only thing we need to do is configure EditorConfig for them using the same configuration file.

If you would like to go deep in EditorConfig check it out at [editorconfig.org](https://editorconfig.org/).

In the next post, I'm going to show how to configure ESLint for VSCode to make our code and life a little bit better.

That's it, folks!

Thanks for reading and I hope it's been useful for you. Please do comment your questions and suggestions.
Fastify Autoroutes
Tags: webdev, node, javascript, typescript
Published: 2020-08-15 20:14:20


Plugin to handle routes in fastify automatically based on directory structure.

## :file_folder: **[GitHub Repository](https://github.com/GiovanniCardamone/fastify-autoroutes)**

## :newspaper: **[Full Documentation](https://giovannicardamone.github.io/fastify-autoroutes/)**

## :rocket: Install

```sh
npm install --save fastify-autoroutes
```

## :blue_book: Usage

### Register plugin

```js
const fastify = require('fastify')
const server = fastify()

server.register(require('fastify-autoroutes'), {
  dir: './<autoroutes-directory>', // relative to your cwd
})
```

### Create file in autoroutes directory

```js
//file: `<autoroutes-directory>/some/route.js`
//url:  `http://your-host/some/route`

export default (fastifyInstance) => ({
  get: {
    handler: async (request, reply) => 'Hello, Route'
  },
})
```

### Using typescript support for module

```typescript
//file: `<autoroutes-directory>/some/route.ts`
//url:  `http://your-host/some/route`

import { FastifyInstance } from 'fastify'
import { Resource } from 'fastify-autoroutes'

export default (fastify: FastifyInstance) => <Resource> {
  get: {
    handler: async (request: FastifyRequest, reply: FastifyReply) => 'Hello, Route!'
  }
}
```

### Accepts params in autoroutes

> :information_source: file/directory name must follow syntax `:paramName` or `{paramName}`

```js
//file: `<autoroutes-directory>/users/{userId}/photos.js`
//mapped to: `<your host>/users/:userId/photos`

export default (fastifyInstance) => ({
  get: {
    handler: (request, reply) => {
      reply.send(`photos of user ${request.params.userId}`)
    }
  },
})
```

## :arrow_forward: Route module definition

Method specification for attributes is available here: [Method specification](https://www.fastify.io/docs/latest/Routes/#full-declaration)

> :information_source: attributes `url` and `method` are dynamically provided

Allowed attributes mapped to Http methods in module:

- delete
- get
- head
- patch
- post
- put
- options

## :arrow_forward: Skipping files

to skip file in routes directory, prepend the `.` or `_` charater to filename

examples:

```text
routes
├── .ignored-directory
├── _ignored-directory
├── .ignored-js-file.js
├── _ignored-js-file.js
├── .ignored-ts-file.ts
├── _ignored-ts-file.ts
├── ignored-js-test.test.js
└── ignored-ts-test.test.ts
```
> :warning: also any `*.test.js` and `*.test.ts` are skipped!

this is useful if you want to have a lib file containts functions that don't have to be a route, so just create the file with `_` prepending character

## :page_facing_up: License

Licensed under [MIT](https://github.com/GiovanniCardamone/fastify-autoroutes/blob/master/LICENSE)
How to create awesome illustrations? 
Tags: discuss, beginners
Published: 2020-08-15 20:11:46

Well well, this weekend I chose to do something new. Apart from writing code I enjoy gardening, painting and reading. But I did something interesting today. I used the Adobe Illustrator to design my first illustration. It is a very minimal and small planter. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/uv556h1grab3aug6qqoh.jpg)

My key learning was that patience is the ultimate goal to get started here. I really enjoyed doing this. ♥️

Any awesome resources to create and learn more of it? I wanna explore more here!
Why Exploding Salsa Reminded Me of Software Development
Tags: anecdote
Published: 2020-08-16 16:50:46

---
title: Why Exploding Salsa Reminded Me of Software Development
published: true
date: 2020-08-15 20:07:17 UTC
tags: anecdote
canonical_url: https://myowenopinion.com/post/dev/exploding-salsa/
---

Yesterday my wife was making salsa in the blender. She put all the ingredients in, put the lid on, and went to turn it on. Our blender has got a few extra buttons, and I use it more often, so I went to help. We got the blender going, salsa was looking great, but in a classic case of too many cooks in the kitchen, I gave the blender one extra pulse AFTER my wife had removed the lid.

Oh the carnage.

Salsa all over the countertops, on the wall, on the curtains, down our clothes, and covering our daughter. Salsa everywhere. It was a mess.

A great deal of clean-up later we managed to finish making the salsa, but what does that have to do with software development?

How many times have you called a method on an object before it was initialized? Or while it was in a bad state? Or before it was implemented? Or written to shared memory without locking your mutex? Or perhaps going the other way, what happens when an object isn't updated when another one changes, and the whole system gets out of sync?

There are patterns to help prevent most of these errors, just like if my blender had a lid sensor, but I've seen so many related bugs over my career that the similarity made me smile.

And then I got out of the kitchen.
Resolvendo problema de CORS para consumir a api do IGDB
Tags: javascript, vue
Published: 2020-08-15 19:56:21

Depois de muito penar para achar essa solução, à encontrei em [heroku cors-anywhere](https://cors-anywhere.herokuapp.com).

Basta adicionar o prefixo https://cors-anywhere.herokuapp.com ao endpoint do igdb e pronto. problema de CORS resolvido.

![image code](https://i.ibb.co/2qqZ4mL/cors.png)
Code to generate the Map of India using Node.js
Tags: node, javascript, github, programming
Published: 2020-08-15 19:47:31

Hello :wave:

I am [Vinit Shahdeo](https://www.linkedin.com/in/vinitshahdeo/), a Software Engineer from India. Yesterday on 15<sup>th</sup> August, India celebrated its 74<sup>th</sup> Independence Day. At midnight, I got an idea to write a code in **JavaScript**(*Node.js*) to generate the **Map Of India**. I've already seen code snippets in C/C++ which do the same but found nothing using JavaScript so far. With this spirit, I opened VSCode and started smashing my keys and finally ended up having a Node.js script to generate the Map of India.

{% twitter 1294487868455284736 %} 

In this article, I'm trying to explain the obfuscated [code](https://github.com/vinitshahdeo/Map-of-India/blob/master/src/index.js) which does the magic.

```js
const MAGIC_STRING = "TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBLOFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"
```

The above encoded string is basically a binary sequence converted to ASCII in which alternating characters stores how many times to draw space and how many times to draw an exclamation mark(`!`).

[![Map Of India using Node.js](https://dev-to-uploads.s3.amazonaws.com/i/nadxvicq2loi2gb30fa4.png)](https://vinitshahdeo.github.io/Map-of-India/)

Here's the [link](https://github.com/vinitshahdeo/Map-of-India) to the GitHub repository.

{% github vinitshahdeo/Map-of-India %}

Say Hi on Twitter([@Vinit_Shahdeo](https://twitter.com/Vinit_Shahdeo))!

Thanks **:)**
[Day 4] Installing and configuring nginx
Tags: ubuntu
Published: 2020-08-15 19:36:04

Hello guys!

It's time for me to set up a WWW server on my VPS! I will both set up nginx and secure it by adding an SSL certificate.

## Installing nginx

This one is pretty straight-forward.

```ssh
sudo apt update
sudo apt install nginx
```

## Firewall

Next thing is to allow nginx to connect outside the server. I need to update UFW settings. First thing is to check up what nginx rules I should allow connecting through the firewall:

```ssh
sudo ufw app list
# Output
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH
```

I will allow `Nginx Full`:

```ssh
sudo ufw allow "Nginx Full"
```

Now I should be able to see default nginx page when I hit the IP address of my machine:

![Default page served by nginx on my machine](https://dev-to-uploads.s3.amazonaws.com/i/hjxxxdp8utxmj00fhy26.png)

I will skip here part of configuring a domain for nginx. I followed [this Digital Ocean](https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-20-04#step-5-%E2%80%93-setting-up-server-blocks-(recommended)) — only step 5.

## SSL

I followed instructions from [this tutorial](https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-20-04) on Digital Ocean, all the steps that are written up there. In step 4. I chose that nginx should redirect all requests to secure HTTPS version.

---

That's all for today's session. In the next one, I want to set up a database. See you tomorrow!

## References

* https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-20-04
* https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-20-04

---

Cover image: <span>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NeONBRAND</a> on <a href="https://unsplash.com/s/photos/internet?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>
Accessibility for the web - why we should use semantic HTML
Tags: webdev, tutorial, javascript, beginners
Published: 2020-08-15 19:34:38

In the last article we talked about one of the `assistive technologies` designed to help people with disabilities access the web: `screen readers`. If you remember, we said that `screen readers` translate the info they see on the screen into audio and/ or Braille output. But in order for this to work, developers need to make sure the `HTML` can be read and translated by the screen readers.

One of the simplest steps a developer can take in order to make their page/ application accessible for everyone is to use semantic HTML as much as possible. But what is that? Is it any different from regular `HTML`?

The answer is no. `Semantic HTML` is markup that describes its meaning very clearly. For example, elements like `header`, `table`, `section` or `article` are very clear about their content while `div` or `span` say nothing about what they might have inside. Since 2014, `HTML4` got upgraded to `HTML5`. With the new version, many semantic elements were added so writing accessible code become so much simpler than before. Unfortunately, even today we can see  lot of `non-semantic` markup in the wild.   Consider the following example:

```javascript
<div>
   <div>This is a list</div>
    <br>
     <span>First item</span>
      <br>
     <span>Second item</span>
      <br>
     <span>Third item</span>
   </div>
</div>
```
This is of course an exaggeration but a very clear example of not so friendly screen readers code. Although we wrote valid `tags`, they're not used for the purpose they're intended (we're trying to create a `list` using `divs` and `brs` instead of using the correct elements). Now look at the correct example:

```javascript
<section>
  <h2>This is a list</h2>
   <ul>
     <li>First item</li>
     <li>Second item</li>
     <li>Third item</li>
   </ul>
</section>
```
When the screen reader encounters the second example, it's very clear that the user it's looking at a section of a web page and that inside the section we have an unordered list - things that are impossible to understand from the first example. 

Semantic HTML doesn't require any additional effort compared to non-semantic HTML, especially if you use it right from the beginning of your project. A quick list of `semantic` elements:

```javascript
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>
```

This doesn't mean we should never use `divs` or `spans` or other elements that don't convey their meaning very clearly, but if you care about making your application accessible to everyone, you should definitely use `HTML5` as much as possible. Besides a larger number of users, other advantages of `semantic HTML` is that the code is simpler, easier to read and more maintainable (think about only about all the `ids` and `classes` you could avoid using while trying to make `non-semantic` elements be more specific; for example, someone could write something like `<div id=header></div>` instead of `<header></header>`). 

*Image source: Goran Ivos/ @goran_ivos on Unsplash*
What is the difference between dot notation and this : [''] while using an object in javascript
Tags: discuss, javascript
Published: 2020-08-15 19:06:03

---
title: What is the difference between dot notation and this : [''] while using an object in javascript
published: true
description: 
tags: #discussion #javascript
//cover_image: https://direct_url_to_image.jpg
---
Apparently for some weird reasons I have been getting a bug on a web app and replacing it from dot notation to [''] solved it. 

Observe:

from:
```
item.price = quantity * normal_price;
```

to:
```
item['price'] = quantity * normal_price;
```