teleren/devto huggingface dataset:
Centring an element on a page
Tags: css, learning, webdev
Published: 2020-09-07 14:47:36

There are no doubt multiple ways of centring an element on a page using CSS, but here I present 2 different techniques that are straightforward and easy to implement.  You could use these techniques for centring a login box, or an information message, etc. in the middle of a page.

![Vertically and Horizontally Centred divs](https://dev-to-uploads.s3.amazonaws.com/i/zndbi6mhsc0esyd16r2f.png)

## Implementation

To center a couple of `div`s, I've defined them on the page as follows:

``` html
<div class="centered1">I am centered div 1.</div>
<div class="centered2">I am centered div 2.</div>
```

There's nothing special about these `div`s apart from they have the classes `centered1` and `centered2` respectively.

### Technique 1

The class `.centered1` uses an absolute position for the `div` and sets it to display 50% from the top and 50% from the left of the page.  The margin of the `div` is then set to `margin: -200px 0 0 -250px;`. Since the `div` is 500px across and 400px wide, this margin has the effect of moving the div 250px left and 200px up, making it display in the center of the page.

``` css
.centered1 {
    position: absolute;
    width: 500px;
    height: 400px;
    top: 50%;
    left: 50%;
    background-color: goldenrod;
    margin: -200px 0 0 -250px;
}
```

### Technique 2

The second technique is almost the same as the first, but this time I haven't used the `margin` to position the `div` in the middle of the page.

As previously, I've set the position to `absolute` and given the `div` a width and height.  I've set the `top` and `left` properties to 50% to move the top left corner of the `div` to the centre of the screen.

Finally, I use a transformation to move the center of the `div` to be on the center of the page. `transform: translate(-50%, -50%);`.  Again, the result is that the component is displayed in the center of the screen.

``` css
.centered2 {
    position: absolute;
    width: 300px;
    height: 200px;
    top: 50%;
    left: 50%;
    background-color: red;
    transform: translate(-50%, -50%);
}
```

## Further Thoughts

Here, I've shown two simple techniques.  I could probably have created the same effect using FlexBox or a Grid layout, or probably a number of other ways.  If there are any different techniques that you use, please leave a comment below.

## Acknowledgements

<span>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thought Catalog</a> on <a href="https://unsplash.com/s/photos/center?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>
Search box filter object type data using hooks
Published: 2020-09-07 14:41:38

I make a note app I want to add search box filter data, anyone can add a note and the list of note he will filter using search filter box these all component function component using hooks.. so many try to handle this issue but I can't so please suggest me any solutions 

---screenshots--

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9rqtpjtxlt71oq55ooz9.png)![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yp6iztsm13emwcjv5q6v.png)
GreenSock (GSAP) animation basics
Tags: css, animation, greensock, gsap
Published: 2020-09-07 14:34:55

### What exactly is a tween?

The first time I heard the word "tween", I wasn't totally sure what it meant. Simply put, a tween is a sequence of frames. In a digital context, basically a tween is an animation.

### So how do we make them?

Luckily for us, lots of libraries exist to help us utilize tweens in the browser. One such library is GreenSock. Today, we will learn about `.to()` and `.from()`, and get you tweening in no time.

Firstly, grab GreenSock from a CDN, and place it in a `<script>` tag in your HTML. Remember to place it before your normal javascript file. 
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js">
</script>
```
*Check the latest version on their homepage greensock.com.*

The CDN will provide you with a gsap object which you can `console.log(gsap)`, and take a look at the various methods it provides. Today, we will be looking at tweens from the "core" property.

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

## **.to()**

Our first tween is `gsap.to()`. It takes two parameters.

1. The target - It can be a normal CSS selector.
2. An object containing properties and values to animate.

```javascript
gsap.to("svg:last-child", {
  duration: 1,
  x: 100
});
```

If you don't specify a unit value, gsap will animate pixels. The default duration time is 0.5 seconds. 

One important note is that values on `.to()` will be the final position of the tween, while CSS values will be starting position.

{% codepen https://codepen.io/JamesGeorgeWilliams/pen/JjXMwaZ default-tab=js,result %}

## **.from()**

Being the opposite of `.to()`, our gsap values will be the starting point, and our CSS positions will be the destination. Let's animate background colour. When using double-barreled property words, we use the camelCasing naming convention to declare them in gsap.

```javascript
gsap.from(".square", {
  backgroundColor: "green",
  delay: 2,
});
```
Using a *delay* of 2 means the animation will begin 2 seconds after the page loads.

## **.fromTo()**

### I thought we were only going to look at two tweens?

Well, technically yes. `.fromTo()` as you can imagine is a combination of both. Remember how our CSS defined our start or end position before? This tween allows us to define both in gsap. Here, we pass an object for both our *from* and *to* values. 

With `.fromTo()`, we add our special properties like *duration* to the 2nd object, which is our *to* properties/vars.

```javascript
gsap.fromTo(
 ".square", 
 { x: 50 }, 
 { x: 0, duration: 1 }
);
```

GreenSock is a really powerful animation library. While there is a paid tier, lots of functionality is available for free to use in your projects. It is also possible to use the paid tier functionality on *codepen.io* for free. I hope this post helped you get started with tweens. Stay tuned for further tutorials.
Express Autodocs - A GitHub Action to generate documentation (Submission)
Tags: actionshackathon, showdev, opensource, javascript
Published: 2020-09-07 14:21:30

I am glad to announce my submission to the GitHub Actions Hackathon 😄

Are you tired of **maintaining** documentation for your APIs?

Express AutoDocs is a GitHub action that solves this problem.

## Submission Category:
**Maintainer Must-Haves**

## My Workflow
Express AutoDocs scans your codebase for express API definitions and automatically generates the documentation and deploys it to a GitHub branch.

Example Repo - [MERN_SHOPPINGLIST](https://github.com/Pika1998/MERN_shoppinglist)

## YAML File
Here's how you can integrate Express AutoDocs in your workflow.
 
```yml
# This is a basic workflow to help you get started with Express AutoDocs Action

name: Express AutoDocs.

# This specifies when the action should occur
on:
  push:
    branches: [master]

jobs:
  generate_docs_job:
    runs-on: ubuntu-latest
    name: Generating Docs
    steps:
      # this step checks out the master branch of your repo using checkout action.
      - name: Checks out the repository
        id: checksout-repository
        uses: actions/checkout@v2
        with:
          repository: ""
      # this step generates the docs
      - name: Generating Docs.
        id: reading-file
        uses: Pika1998/express-autodocs@v0.0.1
      # Use the output from the `hello` step
      - name: Get the output time
        run: echo "The time was ${{ steps.reading-file.outputs.time }}"
```

For a detailed configuration, checkout the official repository

{% github pika1998/express-autodocs %}

## Additional Info

Easily Pass API Info using JSON in comments
**Example**
```js
/*  
{
    "description":"Checks for token and gets the logged in user",
    "inputs":{
        "x-auth-token":"The JWT Token in header"
    },
    "label":"Public",
    "outputs":{
        "user":"The user object stored in database",
    }
}
*/
router.get("/user", auth, (req, res) => {
  User.findById(req.user.id)
    .select("-password")
    .then((user) => {
      res.json(user);
    });
});
```
## Output Format

Supports two output formats `markdown` and `standard`
Default output example:
![Output 1](https://dev-to-uploads.s3.amazonaws.com/i/6anlhj2pgecppptozi7d.png)

## Easy CI/CD Integration

It is very easy to maintain the documentation website since the action deploys the output to a GitHub branch which can be easily set up as a deployment branch using Github pages, Netlify, etc.


Checkout on [GitHub MarketPlace](https://github.com/marketplace/actions/express-autodocs)

# 💖👨‍💻 It was fun and enlightening to participate in the actions hackathon.
Growing up, what were the most influential pieces of sci-fi media for you?
Tags: watercooler, discuss, scifi, inspiration
Published: 2020-09-07 14:18:55

I recently stumbled across this image of The Jetsons and it was like a blast from the past. I remember how much I used to enjoy watching this show on Cartoon Network as a kid. The future looked fantastic! Flying cars and robot maids and what not? I also absolutely loved Transformers when it first came out. It was absolutely mind-blowing to me!

![](https://media.giphy.com/media/R9zXHWAHyTjnq/giphy.gif)

Now that I look back, I realize how much sci-fi media shaped my perception of the future. There wasn't a lot of dystopian media back then, at least not that I remember watching or reading about. As I got older, however, I got into some dystopian sci-fi stuff as well, like The Hunger Games and Snowpiercer.

So what were your favorite pieces of sci-fi media while growing up? List your top 3 at least! How do you feel about them now? I'd love to know!
Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True in Python?
Tags: python, beginners, codenewbie, ddsry
Published: 2020-09-07 14:13:01

Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True in Python Programming Language by DDSRY? 



- Python and many language llike it return one of the operands to their boolean
expressions rather than just True or False.



- This means that if you did False and 1, then you get the first operand False, 
but if you do True and 1, then you get the second(1).
How to detect scroll to bottom in an iframe Angular 8 / JS / JQuery
Tags: html, angular, javascript, jquery
Published: 2020-09-07 14:07:53

Detecting if scroll reached the bottom is never too easy. Because it mostly depends on how to style it. But while in an iframe the story id different. Below is how i did in any iframe.

# Requirement

I had to create a end user license agreement screen where the agreement is served from backend and in frontend i will show the HTML. Obviously iframe was natural option because website styles will not interfere with the agreement styles.

**I had to enable the agree button only when the user had scrolled down to the end of the iframe**

# Solution
This is how i did it. Below is the html part of the code.
```
<iframe id="user-license" #iframe style="overflow:hidden;height:90%;width:100%"
            height="90%" width="100%" frameborder="0" wmode="transparent"></iframe>
```
In anguale component ts i added the content like below,
```
@Component({
  selector: 'app-end-user-license',
  templateUrl: './end-user-license-popup.component.html',
  styleUrls: ['./modal-components.component.css', './end-user-license-popup.css']
})
export class EndUserLicensePopupComponent implements OnInit {
  // Get the iframe element reference
  @ViewChild('iframe', {static: false}) iframe: ElementRef;

  userLicense = '';
  isLoading: boolean;
  enableAccept: boolean;

  constructor(
    private http: HttpService) {
  }

  ngOnInit() {
    this.isLoading = true;
    /* Get the end user license */
    this.http.get('/terms-and-conditions/')
    .then((res: any) => {
      this.isLoading = false;

      // Get the iframe's document reference
      const doc =  this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;

      // Open the doc and add html in it
      doc.open();
      doc.write(res.html);
      doc.close();
      const self = this;

      // Add scroll event
      doc.addEventListener('scroll', function(event) {
        console.log('event: ', event);
        const iframe = self.iframe.nativeElement;
        if (Math.ceil($(iframe.contentWindow).scrollTop())  === $(iframe.contentWindow).height() - $(iframe.contentWindow)[0].innerHeight) {
          // Set true
          self.enableAccept = true;
        }
      }, false);
    })
    .catch(err => {
      console.log(err);
      this.isLoading = false;
    });
  }
}
```
As you can see below is the important one line that detects if scrolled till the end. You can use either contentWindow or contentDocument. This will give access to the document inside the iframe.
> if ($(iframe.contentWindow).scrollTop()  === $(iframe.contentWindow).height() - $(iframe.contentWindow)[0].innerHeight)


Scroll events are always a huge problem. This was a simple solution that i came up with. Always print the event in console to check its keys and get the required data. Hope it helps and Let me know you thoughts in the comments.
Today I Learned: Number of Ways to Make Coin Changes
Tags: python, algorithms, webdev, beginners
Published: 2020-09-07 13:57:25


# Problem Statement

Given an array of unique positive integers representing coin denominations and a single positive integer n representing a target amount of money, implement a function that returns the number of ways to make change for that target amount. 

# Sample Input & Output

```
n = 6
denominations = [1, 5]
```

# Sample Output
```
2 # 1x coin 5 + 5x coin 1 and 6 x coin 1
```

# Code #1

```python
def number_of_ways_to_make_changes(n, denominations):
    ways = [0] * (n + 1)
    ways[0] = 1

    for denom in denominations:
        for amount in range(1, n + 1):
            if amount >= denom:
                ways[amount] += ways[amount - denom]

    return ways[n]

```

# Notes
* Assumption: if n is 0, means there is 0 coin combination available. 

# Credits
* Algoexpert for the problem statement. 
* Ibrahim Rifath for the cover image (https://unsplash.com/photos/OApHds2yEGQ).
JavaScript vs TypeScript
Published: 2020-09-07 13:53:30

Both JavaScript and TypeScript are used to create interactive web applications.  They are both widely known languages.  But before mentioning their differences, let's first introduce each.


# What is JavaScript?

JavaScript is an open-source, scripting language.  It was developed at Netscape in 1995.  The developer Brendan Eich wrote the prototype in 10 days.  It was initially called LiveScript.  It was then renamed to reflect Netscape's support of Java within its browser.  A year later, Netscape submitted JavaScript to the European Computer Manufacturers Association (ECMA).  

Originally, it was meant to be a client-side language.  But is was soon discovered that it was suited to be a server-side language as well.  Along with HTML and CSS, it is the one of the core technologies of the internet.  It's continued acceptance is made evident with the fact that after almost 25 years, it still continues to have an open standard.  The current version of JavaScript, ECMAScript, was release in 2020.  It also has a huge development-community following.

```javascript
const message = 'Hello World!";
console.log(message);
```


# What is TypeScript?

TypeScript is an object-oriented, programming language.  It was developed by Microsoft in 2012.  It was designed for development of large web applications.    

TypeScript is more of a super set of JavaScript.  Since TypeScript compiles into JavaScript, all JavaScript code is valid in TypeScript.  But TypeScript has additional features.  It is a strong typed programming language.  TypeScript is considered to simplify code, making it easier to read and debug.  It is also easy to learn and implement for JavaScript programmers. 

Like JavaScript, TypeScript has also been used to develop both client-side and server-side code.  It is also open source.

```javascript
const message:string = 'Hello World!";
console.log(message);
```


# Advantages of JavaScript over TypeScript

* JavaScript has a vast number of frameworks and libraries that TypeScript does not have.

* JavaScript is best for smaller projects.

* JavaScript is an interpreted language, so it does not take time to compile like TypeScript.

* JavaScript does support abstract classes

* JavaScript has a large programming community.


# Advantages of TypeScript over JavaScript

* TypeScript offers static typing.

* TypeScript highlights compilation errors while it is being developed.

* TypeScript was developed for large projects.

* TypeScript supports object-oriented classes and modules.


# Conclusion
Although JavaScript is more widely used than TypeScript, TypeScript has been gaining in popularity.  Since TypeScript depends on JavaScript, it can never replace JavaScript.  TypeScript can, however, influence how developers write web applications.  If a developer is working on a small coding project, JavaScript is ideal.  However, if it is a large scale project, then TypeScript will be preferred.
Quick tip about function vs function*
Tags: javascript, quicktips, function, generator
Published: 2020-09-07 13:35:21

What is `function *` ?

It's **generator function** which returns a **Generator object**.
**Generators** are intricately linked with iterators.

But what is a **generator function** ?

It's a **function** that can stop *midway* and then *continue* from where it stopped !

```typescript
function * generatorExample() {
  let counter = 0;
  yield `First step ! ${counter}`;
  counter++;
  yield `Second step ! ${counter}`;
  counter++;
  console.log('No yield, the function is done');
}

const generator = generatorExample();
console.log(generator.next().value); // First step ! 1
console.log(generator.next().value); // Second step ! 2
console.log(generator.next().value); // No yield, the function is done
```

The **Generator object** offers a `next()` function that you can call to go further into the next *step* of the **generator**.

You can check [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) for more information.

That's it, make good use of it !

---

I'm not a native English speaker so, thanks in advance if you want to improve my article with correct syntax/grammar/sentences.

I can accept all kind remarks :)

Cover by [Wolfgang Rottmann](https://unsplash.com/@quadratmedia) on [Unsplash](https://unsplash.com/photos/yjF6EZGvKys)
Found a New UI Library for Vue: PrimeVue
Tags: vue, ux
Published: 2020-09-07 13:01:32

Okay, so first off, this is NOT an ad. I really found this UI library great and wanted to share it. This post contains details about this lib and my thoughts, so let's take a look.

## How I Found It

So one day I was bored and wanted to find some UI libraries for Vue to play with, and I actually found A LOT. I didn't even look at these libraries at that time, and they're just gathering dust in my bookmarks bar. And these days I'm looking for some UI libs to use, and I found the bookmarks I've added earlier. I opened almost every one of them and found only this very useful AND I haven't seen this one before. So I took a closer look at it, and found it is great.

## What's Packed

There's 60+ components that you can use out-of-the-box, including autocomplete, markdown editor, rating, tables, upload, menus, charts, inplace editing and even terminals! Best of all, it has shipped 33 built-in themes, including 4 Bootstrap-based themes, 8 material-based themes, 12 PrimeOne Design themes, and 9 legacy themes. All themes includes dark themes. And finally, it's responsive!

## My thoughts

I think this library is very useful is that it has packed the two major design systems in one library, so you don't need to switch between libraries. What I really like is the rich components, and some of them are very useful. I have not tried this theme yet, but I guess it will be easy to setup and use.

PrimeVue's GitHub: <https://github.com/primefaces/primevue>

PrimeVue's website: <https://primefaces.org/primevue/showcase/#/>

So, what do you think about this library? Let's discuss about it!
Diferenças entre Observer Pattern e Producer/Consumer Pattern
Tags: designpatterns, padroesprojeto
Published: 2020-09-07 13:32:03

Normalmente essa é uma questão utilizada em uma entrevista técnica. 
Mas afinal, existe diferença? Porque olhando superficialmente parecem o mesmo. 
Começando com a definição do padrão Observer, existe um objeto chamado de subject que tem observadores e onde,para toda mudança nesse objeto os observadores são notificados. Nesse caso, a notificação é instantânea, em inglês chamada de <i>"per object syncronization"</i>
Para o padrão Producer/Consumer ou Publisher/Subscriber a única sincronização necessária é que o consumer fique aguardando quando não existem notificações no buffer e o Producer aguarde quando o buffer estiver cheio, mas a <i>"per object syncronization"</i> não é necessária. O Produtor (producer) pode gerar vários objetos de mudança antes que o consumidor (consumer) as consumam e este pode consumir tudo de uma vez. Enfim, para esse caso a notificação imediata não é necessária e o Producer não precisa saber quais são seus seguidores.