teleren/devto huggingface dataset:
What is Shadow DOM??
Tags: todayilearned, webdev, html, css
Published: 2020-08-04 14:23:30

Shadow DOM is basically a sub-tree of DOM elements, which is included during rendering of the document but not included in the main document DOM. In other words, the content of a Shadow DOM is a different document, which is merged with the main document to create the overall rendered output.

Take an example of slider: 
```html
<input id="foo" type="range">
```
![Slider](https://dev-to-uploads.s3.amazonaws.com/i/5kmjkj3byacbx7anqjls.png)

The thumb on the slider moves, when you have not written any css or javascript. 

If you do inspect element on the slider you might see something like this: 
![inspect slider](https://dev-to-uploads.s3.amazonaws.com/i/gmmus3dhd88xf69145z8.png)

Now, to enable Shadow Root you need to:
1. inspect element
2. click on the gear icon in the top right corner
3. Go to Elements
4. enable `Show user agent shadow DOM`

Now, try inspecting element again. 
Do you see this?
![shadow-root](https://dev-to-uploads.s3.amazonaws.com/i/bo034tu6ouy8u3f3ighg.png)

You can override the default styles and tweak some beautiful features!

You could try it for `<audio>` and `<video>` HTML5 tags.

This is the link, I referred to understand. 
https://glazkov.com/2011/01/14/what-the-heck-is-shadow-dom/
How to show your template code in 11ty blog posts
Tags: jamstack, webdev, html, writing
Published: 2020-08-04 14:21:19


If you write a technical blog and use 11ty (or Jekyll ... or just use Liquid or Nunjucks) as your static site generator of choice you might run into a conundrum: *How do you show Liquid or Nunjucks template code in your code blocks?*

Whether you use the official syntax highlighting plugin, a custom PrismJS plugin or something else you'll run into this issue. You might think your PrismJS plugin is acting up. You might think 11ty is hiding content from you. You might not even know what to Google! I've been there and I've also helped a couple other people figure out the root cause and fix it.

It's not readily obvious what's causing this issue or how to fix it. The issue is that Liquid and Nunjucks are trying to interpolate and render the tags you put in your highlight block. To make this work, we need to tell the templating engine that it needs to *NOT* fetch the data and render.

To make this work, you need to wrap the tags (or everything) in the `raw` paired shortcode.

## The Default Behavior for Liquid and Nunjucks

Let's take a simple example of a showcasing a template loop. Either using markdown's built-in syntax for code blocks or using [the official syntax highlighting plugin](https://github.com/11ty/eleventy-plugin-syntaxhighlight), we get the same response. 

### A code block that looks like this:

```twig
{% highlight 'html' %}
    {% for currentPost in collections.posts | limit(3)  %}
       {{ post.title }}
    {% endfor %}
{% endhighlight %}
```

### Will render an output of this:

![A code block that renders 3 post titles instead of the code](https://dev-to-uploads.s3.amazonaws.com/i/byg85azbq8usu58o8c9y.png)


**WOOOOPS!**

That's not what we want! That's just a list of posts... but it *IS* what should be rendered by those tags... Imagine it were something less obvious. Imagine you had a conditional expression? It might not show anything. Imagine you had template syntax that didn't work in the current context. Your terminal would light up with errors and you might not know why.

## How do we fix a template engine like Liquid or Nunjucks from doing it's job?

We use a tag provided by both languages to fix this specific issue. The `Raw` tag will take any string and tell the templating engine that this is not to be rendered as a template tag or variable.

If we insert the `raw` tag, our code will render as a code block that contains template syntax, not a rendered list of post titles.

```twig
{% raw %}
    {% highlight 'html' %}
        {% for currentPost in collections.posts | limit(3)  %}
           {{ post.title }}
        {% endfor %}
    {% endhighlight %}
{% endraw %}
```
We now have exactly what we want! 

It took me a lot of research to figure this out when I first started having this issue. It's also, surprisingly a frequently asked question for me. It's a relatively small use case, so there's not a lot of content around it, so Googling isn't great. Hopefully folks will find this and not give up on technical blogging because of it!
Otimizar queries Like %termo% no MySQL
Tags: database, mysql, performance
Published: 2020-08-04 14:15:05

Precisei montar uma API para um autocomplete e a busca precisava ser em qualquer parte do texto:

```
select `pessoas`.* from `pessoas` where `nomeArtistico` like '%Claudinho%' order by `ultima_atualizacao` asc limit 200
```

Essa query tava demorando ~700ms para rodar.


Decidir usar o fulltext do MySQL:

Adicionei o index
```
ALTER TABLE pessoas ADD FULLTEXT(nomeArtistico)
```

E a query:

```
select `pessoas`.* from `pessoas` where MATCH(nomeArtistico) AGAINST('Claudinho') order by `ultima_atualizacao` asc limit 200
```

O tempo pra rodar caiu pra ~19ms

A forma como a busca é feita é diferente e os resultados também, mas para a regra de negócio da minha aplicação resolveu e com um tempo bem menor :)

Nesse artigo tem uma explicação mais detalhada:
https://www.devmedia.com.br/mysql-fulltext-search/14040
Debug Bootstrap 4 breakpoints with Sass
Tags: saas, bootstrap
Published: 2020-08-04 14:13:33

Use this block of sass code to add a tiny indicator in the bottom left corner of the browser that will show the current active breakpoint whenever the class "debug" is added to the body tag.

```
body {

  &.debug {

    &:before {
      position: fixed;
      bottom: 0;
      left: 0;
      color: white;
      z-index: 99;
      padding: 10px;

      @include media-breakpoint-down(xs) {
        content: 'to xs';
        background: yellow;
      } 
      @include media-breakpoint-between(xs, sm) {
        content: 'xs to sm';
        background: navy;
      } 
      @include media-breakpoint-between(sm, md) {
        content: 'sm to md';
        background: black;
      }
      @include media-breakpoint-between(md, lg) {
        content: 'md to lg';
        background: green;
      }
      @include media-breakpoint-up(lg) {
        content: 'from lg';
        background: red;
      }
    }
  }

}
Let's discuss: How do you write your commits?
Tags: discuss, git
Published: 2020-08-04 14:12:07

<center>Originally posted [here](https://www.linkedin.com/feed/update/urn:li:activity:6696413701064409089/)</center>

--- 

A subject that I always see in conversation circles with other developers is about ways to improve the writing of commit messages and how to make them more declarative so that other people can understand what happened in the course of the software development.

I always consult the following guides when I find myself in doubt:
https://chris.beams.io/posts/git-commit/
https://www.conventionalcommits.org/en/v1.0.0/

What format do you and your team use in your projects?

Ps: Remembering that it doesn't exist a right or wrong way, but choices that suit the needs of the team.
A.I. Learns to play my Game
Tags: machinelearning, gamedev, unity3d, csharp
Published: 2020-08-04 14:11:13

I made A.I. play my game. Few days back I made a game in 48 hours - Perfect Speed - and I tried to teach A.I. to the player so that it plays on its own. I basically used Neural Networks to do it. Here's the link if anyone is interested.

Watch the video - https://youtu.be/YcFiEEydGPU

Play the game - https://sashbros.itch.io/perfect-speed
How to locate all usages of a method in PHP code with Bash and Git
Tags: bash, git, php
Published: 2020-08-04 13:59:11

---
title: How to locate all usages of a method in PHP code with Bash and Git
published: true
description: Very useful for refactoring
tags:  ['bash','git','php']
//cover_image: https://direct_url_to_image.jpg
---

Using Git grep you can locate code fragment very, very fast. **Much faster than any IDE.** So I made a very simple script to help me refactor my code.

## Code

Create a file `find-usage.sh` with the following content
```BASH
#!/bin/bash
git grep -C2 -p -E "(-[>]|::)$1\("
```

make it executable with
```BASH
chmod +x find-usage.sh
```

It will locate usage like `$object->method()` as well as `Object::staticMethod()`.

## Usage

```BASH
find-usage.sh methodName
```

Output:
```
>_bin/find-usage.sh getName
app/Models/Addworking/User/Concerns/User/HasLogs.php=trait HasLogs
--
app/Models/Addworking/User/Concerns/User/HasLogs.php-    {
app/Models/Addworking/User/Concerns/User/HasLogs.php-        $this->log()->create([
app/Models/Addworking/User/Concerns/User/HasLogs.php:            'route'         => optional($request->route())->getName() ?? 'n/a',
app/Models/Addworking/User/Concerns/User/HasLogs.php-            'url'           => substr($request->fullUrl(), 0, 254),
app/Models/Addworking/User/Concerns/User/HasLogs.php-            'http_method'   => $request->getMethod(),
--
```

---

Leave a like and a comment if you need help using it.
Why we need Context API - ReactJs
Tags: react, javascript
Published: 2020-08-04 13:59:00

We all heard new feature in ReactJS which is Context API, when we hear this thing we get into a conclusion that what the hell is this, but it's pretty easy to understand.

**Why we need Context API ?**

Whenever we have props needs to be sent to each and every child of parent component we do it by sending prop name assigning it to prop value.

like this in render
for eg :
```javascript
return (<
<Mycomponent props1={1} p2={2} ...
<Mycomponent2 props1={1} p2={2} ...
...
</>)
```


But when we use Context API we need not send every prop with its value on each child component.

**When to Use Context API :**
When we get into a situation where we need to send all the props of parent to its child deep down till last child

**How to use this ?**
There are two things in Context API

1.Provider - This should be used in Parent component, for every child component this acts as value provider, and every component acts as consumer to this Provider.

Syntax : 
```javascript
<Provider value={state}>
{children}
</Provider>
```

2. Consumer - This should be used in every child component to access global context values.

Syntax :
```javascript
<Consumer>
{value => /* render something based on the context value */}
</Consumer>
```
One annoying difference between python versions 3.5 and 3.6
Tags: python, programming, raspberrypi
Published: 2020-08-04 13:55:54

---
title: One annoying difference between python versions 3.5 and 3.6
published: true
description: A little code snippet showing how useful format strings are
tags: python,programming,raspberrypi
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/g6kgfea8hxahykljx2yi.jpg
---

Back in the ancient time, the olden days, all the way back in March of 2019, there was python 3.5.7.

Back in those days there were no f-strings. No, if you wanted to interpolate your variables into a string the closest you could get to f-strings was this:

``` python
circumference = 19
radius = circumference/math.pi/2
area = math.pi*radius*radius
circledata = 'circumference: {circumference}, radius: {radius}, area: {area}'.format(**{'circumference':circumference, 'radius':radius, 'area':area})
```
Behold the abomination!  What a mess.

Now? Oh now! What a wonder that has been bestowed upon us. THE F-STRING. Behold!

``` python
circumference = 19
radius = circumference/math.pi/2
area = math.pi*radius*radius
circledata = f'circumference: {circumference}, radius: {radius}, area: {area}'
```

Succinct and marvellous.

Why should I bring this up? Well, upon mine laptop I am blessèd with python 3.7. Yet. YET! My raspberry pi suffers in the gutter, hope lies dashed upon the pavement, with python 3.5.
69: What is the bug in front-end development
Published: 2020-08-04 13:51:39

##*QUESTION: My curiosity never stops*

* What is the purpose of learning JS grammar
* why does the bug happen? 
* I wondered why it matters to solve bugs, in frontend development, 
* Why does it happen while creating? 
* What sort of accidents would it be possible to happen?

------------------


###**LET'S FOCUS ON THE FRONTEND DEVELOPMENT BUGS FIRST!** 
 
This is an informative post, which I got an idea from this article :::::     [How to Get Rid of Frontend bugs
](https://medium.com/javascript-in-plain-english/how-to-get-rid-of-frontend-bugs-c09a64ceee9a)


------------------


1. Content Bugs: Missing or invalid data when not handled properly can lead to bugs such as broken images, links that lead you to 404s, empty tooltips, and typos.

2. Functional Bugs: Forms that don’t submit, buttons that do nothing, requirements that are not fulfilled, and 500 pages stop users from reaching their goals.

3. Visual bugs: When interfaces look broken it sometimes (overflow) gets considered as functional bugs as well. Text overflows, alignment, and cropped interfaces all have a great impact on the user experience.

4. Accessibility Bugs: Often overlooked, popular bugs include keyboard navigation issues, missing alternative texts, and color contrast issues.

5. Internationalization Bugs: Famously known for RTL problems, wrong currencies, missing content, truncation, and date formats.

6. Performance Bugs: Images that take forever to load, or even worse pages that don’t render until the user already leaves.

7. Browser Compatibility Bugs: All of the IE memes and jokes do not come without a reason. Occasionally, features work on some browsers but not for others.

8. Security Bugs: Generally thought as a backend problem, yet on the frontend, you are also subjected to security threats. Especially, when you use third parties that inject javascript that has the same powers as your own javascript.

9. Usability Suggestion: Users might be facing a challenging user experience that they think the feature doesn’t actually work, and hence stop using your application as well.
Understanding JavaScript Promises
Tags: javascript
Published: 2020-08-04 13:44:27



# 1. Need for Promises

When we send a network-request, we have to wait for some time to get response from the server.

But as JavaScript is a synchronous-language, it does not wait to receive a response after some time with normal function call.

Hence, Promises are introduced. Promises gives a promise to code written after it, to provide value after some time.

# 2. Promise Creation

`Promise()` constructor is used for Promise creation.

## Syntax

```javascript
new Promise(Executor-Function)		// returns "promiseObj"
```

### Executor-Function

should take 'two functions' as parameters - 

1. `resolve()` - called when the asynchronous task completes and returns the 'result'
2. `reject()` - called when task is failed, and returns 'reason of failure' which is typically a 'error object'

```javascript
const promise1 = new Promise((resolve, reject) => {
    // do something asynchronous
    //
    // resolve(someValue)
    // or
    // reject('reson for error')
})
```



## Example

```javascript
const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('foo')
    }, 300)
})

promise1.then((value) => {
    console.log(value);			// foo
})

console.log(promise1)			// [object Promise]
```



# 3. Promise Consumption

```javascript
const promise1 = new Promise()

const res = promise1.then(res => res.json()).catch(err => console.log(err));
// .then() 	 step after result is received
// .catch()  way to process error, if error happened

// Chaining
const res = promise1
.then(value1 => modify1(value1))
.then(value2 => modify2(value2))
.then(value3 => modify3(value3))
.catch(err => console.log(err))
```



# 4. Making functions returns a Promise

To provide a function with promise-functionality, have it return a promise-object

```javascript
function myAsyncFunction(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest() 
    xhr.open("GET", url) 
    xhr.onload = () => resolve(xhr.responseText) 
    xhr.onerror = () => reject(xhr.statusText) 
    xhr.send() 
  });
}
```



#  5. Async Functions

Async Functions are instances of the `AsyncFunction` constructor, and `await` keyword is permitted within them.

The `async` and `await` keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

`try{ } catch(e){ }` block is used to process fulfilled (`try{}`) and failed (`catch(e){}`) requests

```javascript
// 1. function returning promise
function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

// 2. Async function
async function asyncCall() {
  console.log('calling');
  try {
      const result = await resolveAfter2Seconds();
      console.log(result);		// fulfilled
  } catch(err) {
      console.log(err)			// rejected, or any other err
  }
}

asyncCall();	  // expected output: "resolved"
```
Matt's Tidbits #76 - A long-overdue feature
Tags: mattstidbits, android, tidbittuesday
Published: 2020-08-04 13:43:18

[Last week I shared some moving tidbits.](https://medium.com/@matthew.b.groves/matts-tidbits-75-moving-tidbits-5e1cfbefbe9a) This time, I wanted to tell you about an exciting upcoming feature of Android 11!

Last week I attended an interesting online meetup sponsored by multiple Android Google Developer Groups (GDGs), where two of Google's best-known developer advocates presented on upcoming features of Android 11:
https://www.meetup.com/Google-Developer-Group-of-the-Capital-Region/events/271595586/

One of the upcoming features that is the most exciting to me (you'll know I must be an Android developer after you learn what it is) -
...is the ability to tell if the keyboard is currently visible or not.

Believe it or not, this is something that has been missing since the beginning of Android, and only possible to find out through fairly janky/inconvenient means.

However, Android friends, the wait is over!
This tweet demonstrates how you can use this (IME is short for "input method editor" - a slightly more generic way of referring to a keyboard):
{% twitter 1230598177511788545 %}

Here's the API documentation for this new capability of the WindowInsets class: https://developer.android.com/reference/kotlin/android/view/WindowInsets#isvisible

The best news of all though is that they are working on adding this to AndroidX - which means that this functionality will be backported (TBD how far) to older versions of Android!
{% twitter 1230600015493521409 %}

If you've been an Android developer for a while, you've likely endured this, so this is a real cause to celebrate! 🎉

I'm curious - how have you worked around this missing API in your app? Let me know in the comments! And, please follow me on Medium if you're interested in being notified of future tidbits.

*This tidbit was discovered on July 30, 2020.*
Change Window.print() paper orientation
Tags: javascript
Published: 2020-08-04 13:39:04

Hello. Today we will see how to change the orientation of the Window.print () paper with js. To do this, you need to inject style into your document.

```javascript
var css = '@page { size: landscape; }',
    head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');

style.type = 'text/css';
style.media = 'print';

if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);

window.print();

//don't forget to find and remove style if you don't want all you documents stay in landscape
```
I open-sourced my Nuxt.js blog
Tags: vue, nuxt, opensource, github
Published: 2020-08-04 13:30:48

I've implemented my new website/blog using Nuxt.js and deployed it on Netlify. [Telmo](https://twitter.com/telmo) inspired me with his fantastic clean-coded project to create my own. He built the blog [telmo.im](https://telmo.im) with Next.js(React) and markdown files. 
Which is really sexy in my opinion. That's the short story.

In detail, I wanted my personal blog and with **zero knowledge about React** I looked into Telmo's [GitHub](https://github.com/telmogoncalves/telmo) Repo like a cow would look into the clockwork. But ok, it can't be that difficult, so I was curious about which dependencies he used and decided for me to start from scratch with a new Nuxt.js project. 

Of course, there are some excellent headless CMS that I could use. But I found it a little over the top for a small blog like mine. It was also my wish to write new blog articles with markdown files, which then appear automatically. I chose [@nuxt/content](https://content.nuxtjs.org/) for this kind of job.

If you use the Node Package Manager, then can you inject it directly in your project with:

```bash
npm install @nuxt/content
```

**Here are some features:**
- Blazing fast hot reload in development
- Vue components in Markdown
- Full-text search
- Support static site generation with nuxt generate
- Powerful QueryBuilder API (MongoDB like)
- Syntax highlighting to code blocks in markdown files using PrismJS.
- Handles Markdown, CSV, YAML, JSON(5)
- Extend with hooks

That sounds fantastic to me and is more than what I wanted. 
I highly recommend taking a look at the official documentation to get the stone rolling.
It's the first time I using it, and let me tell you it's freaking amazing. **Thank you, Telmo for the inspiration**.

---

## Repository

You can find the repository here, and if you want to contribute to the project, you are very welcome to open pull requests.

If you want to use my project to code and build your own website, then go for it.

👉 [Open Github](https://github.com/webnoobcodes/webnoob.dev)
اسپرین کا استعمال ہارٹ اٹیک میں کیا واقعی اس کا استعمال فائدہ مند ہے؟
Published: 2020-08-04 13:27:25

اسپرین کا استعمال ہارٹ اٹیک میں ایک بہت اہم ٹاپک ہے کیونکہ بہت سے لوگ اسکے فوائد اور نقصانات کے بارے میں شبہات کا شکار رہتے ہیں۔ اس وقت میرے ساتھ کانفرنس میں موجود پاکستان کارڈیک سوسائٹی کے سربراہ پروفیسر فروز میمن موجود ہیں جانتے ہیں کہ ان کے کیا نظریات ہیں اسپرین کے بارے میں۔

اس حوالے سے ہم نے کچھ پروفیسرز کی رائے لی جو ہم آپ سے شیئر کر رہے ہیں۔