teleren/devto huggingface dataset:
Help with React .map through JSON data.
Tags: react, help
Published: 2020-05-25 02:08:42

I just signed up here to get some help as i'm new to react and this is where reactjs.org suggested i go for help, and i'm not sure if this is the right place to ask questions about code but I have an issue that I can't seem to figure out. 

I have a .json file in one of my directories and i've imported it into one of my .js files. 

I'm trying to set the state to the .json file which i've done successfully. However, I can't figure out how to map through the data and display it in my render method properly. 

    //other react imports
    import data from '../data/portfolio.json';

    class Portfolio extends React.Component {
        constructor(props) {
            super(props);
            this.state = {data}
        }

        render() {     
            return(
                <div>
                    <a href={this.state.data.portfolio[0].url}>
                       <img className="img-fluid" 
                            src={this.state.data.portfolio[0].image} 
                            alt={this.state.data.portfolio[0].site} />
                       <p>{this.state.data.portfolio[0].site}</p>
                    </a>
                </div>
            )
        }
    }

This works fine, but I want to avoid having to create multiple anchor, image and paragraph tags and loop through to display everything. Any suggestions or places I can go to read how to do this with a local .json file? I tried this...

    const myData = this.state.data;
    const listItems = myData.map((myData) =>
      <li>{myData}</li>
    );

This doesn't work though because I think .map is used for arrays online. Should I use a for loop or something else?
Simulando funções de ciclo de vida com useEffect()
Tags: react, reactnative, javascript, webdev
Published: 2020-05-25 02:01:06

Pra quem estudou react antigamente e não vem acompanhando muito bem o desenrolar da lib não está muito "antenado" nas coisas mais iradas que ela tem trazido. Uma das coisas que eu pessoalmente acho mais daora no react ultimamente são os `React Hooks`.

Os hook são formas mais fáceis e menos verbosas de fazer coisas como manipulação de estados dos componentes, controlar ciclos de vida etc, você pode saber mais aqui **https://pt-br.reactjs.org/docs/hooks-intro.html**

Um hook que fez bastante diferença foi o `useEffect`, com useEffect podemos basicamente simular algumas funções de controle de ciclo de vida do nosso componente quando usavamos classes pra faze-los, são essas funções: `componentDidMount`, `componentDidUpdate` e `componentWillUnmount`.

Então Vamos ao código.

Para simularmos o `componentDidMount` e `componentDidUpdate` podemos usar o useEffect da mesma forma e ele funcionará nos dois casos:

```
import { useEffect } from 'react'

useEffect(() => console.log('componente montado ou teve um update'), [])
```

Com o array de dependencias do useEffect vazio ele vai simular o didMount e didUpdate de forma fácil. Pesquise mais sobre o useEffect e verá que ele é bastante útil quando sabemos usar mais dele, principalmente passando variáveis no array de dependências.

Para simularmos `componentWillUnmount` usamos da seguinte forma:
```
import { useEffect } from 'react'

useEffect(() => {
  return () => console.log('componente sendo desmontado :(')
}, [])
```

quando passamos uma função para o return do useEffect, ele executa a função quando desmontar o componente. 

Enfim, fácil, não é ? Recomendo muito você pesquisar mais sobre os React Hooks em geral, será bem útil se quiser se aprofundar mais no React moderno. Te vejo na próxima.
Leetcode - Roman to Integer (with JavaScript)
Published: 2020-05-25 01:48:01

Today I am going to show how to solve the Leetcode Roman to Integer algorithm problem.

Here is the problem:
![problem](https://raw.githubusercontent.com/Urfan196/MyFIles/master/roman.png?token=AMQWY7ABGJTAKEP4M3ZUH626ZMROS)

There are seven symbols in the Roman numeral system. I’m going to map each symbol to its value.

```javascript
var romanToInt = function(s) {
    
    const sym = { 
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }

}
```
I then create a new variable to represent the integer converted from a roman numeral.

```javascript
var romanToInt = function(s) {
    
    const sym = { 
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }
    
    let result = 0;

}
```
If the numerals are descending from left to right, largest to smallest, then they are added together. But if the numerals begin to ascend in order, then the larger number is subtracted by the preceding smaller number. For instance, in XVIV, X and V are added together to make 15. Because the I is followed by a larger number, V, it is subtracted from that number to make 4 and then added to the preceding XV to make 19. 

Based on this rule, I will iterate from left to right.  If the current symbol (cur) is less than the symbol to its right (next), then I will subtract the cur from the next and move 2 characters to the right. Otherwise, I will simply add them.

```javascript
var romanToInt = function(s) {
    
    const sym = { 
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }
    
    let result = 0;
    
    for (i=0; i < s.length; i++){
        const cur = sym[s[i]];
        const next = sym[s[i+1]];
        
        if (cur < next){
            result += next - cur // IV -> 5 - 1 = 4
            i++
        } else {
            result += cur
        }
    }
    
    return result; 
};
```
Explore files under a specific directory in Rails
Tags: ruby, rails
Published: 2020-05-25 01:46:42

---
title: Explore files under a specific directory in Rails
published: true
description: 
tags: ruby, rails
---

If you want to recursively retrieve the file paths under a particular directory, you can use the
Use the Dir class to get the path.

If you want to call it in Rails, you can use Rails.root to get the absolute path where Rails is running on the OS you're running, so you don't have to lead the production or development environment.

execution example

```
Dir.glob("#{Rails.root}/app/models/**/*") do |f
  p f
end

=> "/var/app/models/user.rb"
"/var/app/models/owner.rb"
"/var/app/models/blog".
"/var/app/models/blogs/comment.rb".
```
How to check if a particular method exists in a Ruby class and instance
Tags: ruby
Published: 2020-05-25 01:39:54

---
title: How to check if a particular method exists in a Ruby class and instance
published: true
description: 
tags: ruby
---

Prerequisites.
Ruby: 2.5.1

## Checking the existence of a method for a class

Using method_defined?

```
String.method_defined?(:to_i)
=> true

# I see that there is a to_i method, so I'm going to run it
"1".to_i
=> 1
```

## Does the method exist for the instance?

Using respond_to?

```
"string".respond_to?(:to_a)
=> false

# There is no to_a method so I get a NoMethodError error when I try to run it
```
VS Code Extensions / Shortcuts for Python / Web
Tags: python, vscode, beginners
Published: 2020-05-25 01:34:02

I use Visual Studio Code editor by Microsoft for Python development. I find below shortcuts and extensions particularly very useful during application development. Hope you find them useful as well!

<h4>Python extension for Visual Studio Code by Microsoft</h4> 
With over 20 million installs, this is one of the most popular extensions for Python development in VS Code. Some of the commonly used editor options are:

* Go to Definition (F12) jumps from the current code into the code that defines an object. This command is especially useful when working with libraries and want to learn more about them.
* Peek Definition (Alt+F12), is similar, but displays the definition directly in the editor. 
* To run a specific section of code in Python, highlight the section and press `shift + Enter`. This runs just the highlighted portion of code from the Python file.
* To enable brackets completion and linting - Press `ctrl + shift + p` and type `settings.json` to get the settings file. In settings.json file, add below:
```python
{
    "python.linting.enabled": true,
    "python.autoComplete.addBrackets": true,
}
```
* To get a printable reference of all shortcuts in VS Code: Press `ctrl + shift + p` and type `Keyboard Shortcuts Reference` in the search box. This will take you to the <a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf">shortcuts link</a> containing nice printable version of shortcuts in a pdf format.
* Please note default keyboard shortcuts could be changed using Code > Preferences option.

<h4>Visual Studio IntelliCode by Microsoft</h4>
This is again another popular extension that helps with code completion. Pausing or pressing `ctrl + space` after module name activates and displays list of code completion options.

<h4>Better Jinja by Samuel Colvin</h4>
Jinja code added in the html template usually looks unformatted. To add colorization effect, install <a href="https://marketplace.visualstudio.com/items?itemName=samuelcolvin.jinjahtml">Better Jinja by Samuel Colvin</a>. Then add below association in settings.json file
```python
{
    "files.associations": {
       "*.html": "jinja-html"
    }
}
```

<h4>Flask snippets by cstrap</h4>
<a href="https://marketplace.visualstudio.com/items?itemName=cstrap.flask-snippets">Flask snippets by cstrap</a> provides shortcuts for generating commonly used snippets in Flask and Jinja. Once extension is installed, typing `hw` in the editor generates below snippet:  
```python
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
```

<h4>Python DocString Generator by Nils Werner</h4>
This <a href="https://marketplace.visualstudio.com/items?itemName=njpwerner.autodocstring">Python DocString Generator</a> extension provides a consistent way to provide documentation to Python functions and modules.

<h4>References</h4>
https://code.visualstudio.com/docs/python/editing
Find 3 Dart average using JavaScript function
Tags: javascript, html, css
Published: 2020-05-25 00:55:44

Im stuck on a particular thing. Im trying to calculate the 3 dart average i.e i start with a score of 501 and i hit 180 so after that score my average would be 180, then next throw i hit 100 so after 6 darts i have scored 280 so my 3 dart average would be 140, is there anyway i could use a function or something to calculate average over darts thrown given a score? The best average you can have is 167, start with 501. In 9 darts (3 Rounds) you score 180 - 180 - 141 then normally you could take 501 ÷ 9 (Darts thrown) then multiply by 3 (Rounds, each round you throw 3 darts) to give you a 3 dart average of 167. Thanks in Advance
Compendium a Abstractive Text Summarization using Attention Mechanism
Tags: octograd2020
Published: 2020-05-25 00:52:59


## My Final Project
“Don’t need the full article or text, just require the summary.” I often think while reading an article or a newspaper. During my under graduation I often face this kind of situation. It's such a drag to read the full report if you can get the compendium. Right?

During my under-graduation I thought to automate it. Doing it manually takes a lot of time. So, using the magnificent powers of NLP and Deep learning, I came up with the project Compendium. An abstractive text summarization model, that takes a text and provides its summary.



## Link to Code

Have an Idea?, want to contribute or want to see code behind the magic. The code can be found in the following GitHub repository.
{% github https://www.github.com/soni-ratnesh/compendium %}

## How I built it 
<ul>
<li>The project was built using Pytorch, Spacy and torchtext. Pytorch is used to build the summarization model, while Spacy and torchtext was used to pre-process data.</li>
<li>The summarization model is an Encoder decoder model with GRU cell. Why GRU not LSTM? The choice was made after experimentation. Tried both of them but GRU performed slightly better so GRU it is.</li>
<li>Choosing the data on which to train on was one of the most important decision. As the data is the key factor for this. It's always Garbage In Garbage Out. For better Generalization we used 15000+ News article dataset from <a href=https://www.kaggle.com/sunnysai12345/news-summary>Kaggle</a> for training.</li>
<li>After a few different approaches, finally arrived at Attention Mechanism. Challenging our self to learn and implement it was one of the greatest event.</li>
<li>GitHub Education Pack helped to get a domain for publishing work. </li>
</ul>

## Additional Thoughts / Feelings / Stories
I am really proud of the model. I further want to improve it and make it better and more general.
At last just want to say every locked door has a key you just have to know where to find it. 

Thank you for reading and Happy Coding!!
React custom hooks: a clean approach to fetch
Published: 2020-05-25 00:51:38

# Introduction

Custom hooks are not a React feature, per se; but implementing custom hooks follows the same design pattern of React's common hooks like `useState` and `useEffect`. 

As the React documentation specifies, a [custom hook](https://reactjs.org/docs/hooks-custom.html) is _a JavaScript function whose name starts with ”use” and that may call other Hooks. 

If you're familiar with React, you may be familiar with the following pattern, where a component `fetch`es a some data from a backend service, e.g.

```js
const myComponent = () => {
const [posts, setPosts] = useState([])

useEffect(() => {
  const getPosts = async () => {
    const response = await fetch("my_backend_url")
    const data = await response.json()
    return data
  }
  
  setPosts(getPosts())
}, [])

  return (
    <ul>
      {posts.map(post => (
        <PostPreview key={post.slug} post={post}>
      ))}
    </ul>
  )
}
```

This common pattern can be abstracted into a custom hook, which cleans up the component code.

# Code

Consider the following approach to getting/setting posts. This code would exist in something like `./src/hooks/use-posts.js`.

```js
const usePosts = async () => {
    const response = await fetch("my_backend_url")
    const data = await response.json()
    return data
}
```

Now our component could be re-written to be:

```js
const myComponent = () => {
  const posts = usePosts()

  return (
    <ul>
      {posts.map(post => (
        <PostPreview key={post.slug} post={post}>
      ))}
    </ul>
  )
}
```

# Conclusion

There are many considerations when you're refactoring functional code to improve it. Among those considerations are: _is this easier to follow?_, _does this separate concerns?_, and _does this follow the language's design patterns?_ The custom hook pattern for React is affirmative to all of those considerations. I hope you find this post useful.
How to get ٩(◕‿◕｡)۶ Japanese Emoticons on android
Tags: emoji, japaneseemoticons, textface
Published: 2020-05-25 00:45:48

Japanese Emoticons(Kaomoji) are used to express moods while texting and online discussions, using Japanese characters and grammar punctuations. The word kawaii is derived from the phrase 顔映し Kao Hayashi, which means " one's face is aglow," commonly used to refer flushing or glowing of the face. Kawaii faces are also known as Japanese emoticons, kaomoji, or Kawaii Emoji. It is used by Japanese people for chatting, and over the years, these Japanese emoticons or Kawaii faces became popular all over the world. In kaomoji, more attention is given to the eyes, unlike in Western emoticons. Japanese emoticons have a head or a face, unlike Western emoticons. Kawaii faces can be used to express different feelings like joy, love, anger, etc.. kaomoji can also use to represent animals, birds, activities festivals, etc..

We can also see different categories of emojis such as love kawaii faces, worried kawaii face, super kawaii emoticons, Japanese emoticons, cute emoticons, Lenny face, angel kaomoji, cat kaomoji, etc..

Here are some of the websites you can actually copy and paste Japanese emoticons:

https://www.thekawaiiface.com

It is quite easy. The only thing you need to do is, just click on any Kaomoji for text faces that you want to copy. The moment you click on it, it's automatically copied into your clipboard.

❀◕ ‿ ◕❀
Arrow Functions
Tags: javascript, webdev, react, angular
Published: 2020-05-25 00:19:32

*Note: This is part of my es6 series of posts.*

Arrow functions are a concise anonymous function syntax, and their `this` value is lexically bound to their enclosing scope. (Where the function was defined)

### Single Expression

When the arrow function body is a single expression it is implicitly returned.

```js
var add = (a,b) => a+b;
```

### Single Argument

When the arrow function has only one argument the parens around the parameters can be omitted.

```js
var odd = n => n % 2;
```

### No Arguments

When the arrow function has no arguments you need an empty parens `()`.

```js
var random = () => Math.random();
```

### Multiple Expressions

When the arrow function body has multiple expressions then they must be wrapped in `{}` and the `return` statement may not be omitted.

```js
var shout = s => {
  s = s.toUpperCase();
  s = s + '!';
  return s;
}
```

### Lexical this

The arrow function's `this` value is bound to the enclosing scope, so no more need for `var self = this`.

```js
function Counter () {
  this.count = 0;
  setInterval(() => this.count++, 1000);
}

var counter = new Counter();
```

### Concise Functional Iteration

Arrow functions can be used to write iteration, map, reduce and filter operations quite concisely.

```js
var data = ['one', 'two', 'three'];
var processed = data
  .map(s => s.length)
  .filter(length => length < 5);
```

Happy coding 😃 .
Build your own penetration testing lab with AWS, Kali Linux and OWASP ZAP - Getting started
Tags: aws, security, testing, linux
Published: 2020-05-25 00:18:43

> Build your own penetration testing lab with AWS... or spend ton of money on various ~~expensive~~ scan services.

Hello everyone! 
I've decided to refuse security scan services and build a simple pentesting lab based on [Kali Linux](https://www.kali.org/).  

If you don't have an AWS account - it's the right time to [create](https://portal.aws.amazon.com/billing/signup?nc2=h_ct&src=header_signup&redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start) one!

## EC2 and Kali Linux

#### Few words...  

EC2 stands for Elastic Compute Cloud. In our case we'll use EC2 instance to get our Kali image installed, up and running.

Kali Linux is a Linux distribution based on [Debian](https://www.debian.org/). It's commonly designed for penetration testing purposes, and has a lot of useful tools preinstalled.

### Installation steps

- Login to your AWS account.
- On the home page, either search or select the EC2 service that is located under Compute category.
- On the EC2 Dashboard page, click the "Launch instance" instance button.
- We're looking for Kali Linux image, so, on the left sidebar, choose "AWS Marketplace", then use the search input field at the top - enter "Kali Linux" and hit the Enter/Return key on your keyboard.
- You should see the "Kali Linux" image in the search results.
![AWS Kali Linux image](https://dev-to-uploads.s3.amazonaws.com/i/76b065glpcbjit7vaj34.png)
- Click appropriate "Select" button.
- In the opened modal you see the description of Kali Linux and Pricing Details. Click "Continue".
- At this moment I don't care about best experience, so I choose "t2.micro" just because free tier eligible. Choose the instance type and click "Review and Launch". Clicking the "Review and Launch" button will redirect us to the last step. AWS has some default configuration setup for storage, tags, security groups etc. You can edit those configs if you want.  
- On "Step 7: Review Instance Launch" page you can review your instance configuration. Please make sure your security group allows SSH. 
![EC2 Security Groups](https://dev-to-uploads.s3.amazonaws.com/i/sek6cs7ynxd2d6tgzb5a.png)
- Click the "Launch" button.
- In the opened modal select the "Create a new key pair" option in the dropdown field, enter a key pair name (e.g. kalilinux), and click the "Download Key Pair" button.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/i6s3i3zd0f2ka401w5xx.png)
- Please make sure you have downloaded the key pair file, and click the "Launch instance" button.

That's all! Few moments later you should see new running ec2 instance - just click the "Instances" link in left menu.


## What's next?

In the next post I want to explore the power of OWASP ZAP and investigate to see how can I setup and automate some scans to prevent vulnerabilities. And of course, with beautiful reports and notifications...

If you have an idea that could help me in my research, please share in the comments. Thanks! :)
How to stop and remove all Docker containers
Tags: docker, devops
Published: 2020-05-29 23:47:01

---
title: How to stop and remove all Docker containers
published: true
date: 2020-05-25 00:00:00 UTC
tags: docker, devops
canonical_url: https://www.ankursheel.com/blog/stop-remove-all-docker-containers
---

## Problem

Occasionally, I have needed to stop and remove all the docker containers I am running locally. I got tired of googling for the commands all the time and decided to write a snippet that I could access easily.

## Solution

Before we see how to stop and remove all containers, we need to list all the containers.

### List all Containers

The command to [lists all containers](https://docs.docker.com/engine/reference/commandline/container_ls/) is`docker container ls [OPTIONS]`.

By default, it shows just the running containers and a lot of information that we won’t need. So let’s pass in some options

- **_-a_**: Show all the containers.
- **_-q_**: Only display the numeric ids.

```
docker container ls -aq
```

### Stopping all containers

The command to [stop docker containers](https://docs.docker.com/engine/reference/commandline/container_stop/) is`docker container stop [OPTIONS] CONTAINER [CONTAINER...]`

We can see it takes a space-delimited list of container ids/names to stop. We already have the list of container ids from the previous step. All we need to do now is use a shell expansion trick to pass in the list of all containers.

```
docker container stop $(docker container ls -aq)
```

### Removing all containers

The command to [remove docker containers](https://docs.docker.com/engine/reference/commandline/container_rm/) is`docker container rm [OPTIONS] CONTAINER [CONTAINER...]`

We can see it’s similar to the stop command and also takes a space-delimited list of container ids to remove.

We can use the same shell expansion trick to pass in the list of all containers.

```
docker container rm $(docker container ls -aq)
```

## Conclusion

This makes it trivial to stop and remove all the containers that I have running locally.
Day 5: Basic Javascript
Tags: challenge, codenewbie, javascript
Published: 2020-05-24 23:49:04

Today marks day five of my journey through freeCodeCamp. I feel like I am getting into the flow of the work and just moving forward with the work as best as I can. 

Life has been throwing many distractions and mixed emotions at me during this time period, in just the five days since I have started, a relative has passed, I have travelled to a different state, as well as other small life interruptions. I believe that when a person decides to do something that is going to help them, distractions and life will always try to get in the way and discourage them. Life is a very natural boss that will always check you to see if you really have what it takes, and I welcome the challenge. 

I am currently going over switch functions at the moment, which I can already see working wonders in the logic of games like Hangman or other trivial games that look easy, but require a lot on the logic end. Overall, today was a successful day for studying and I am sure that as I continue to work with Javascript, I will be able to update on any new ideas that I run into.