teleren/devto huggingface dataset:
JavaScript Interview Question #22: How `toString` works in JavaScript?
Tags: beginners, javascript, codenewbie, webdev
Published: 2021-02-24 16:50:02

![js-test-22](https://learn.coderslang.com/js-test-22.png)

Let's try to apply a generic `toString` function to a regular JavaScript array. What’s the output? 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In the first line, we’ve saved the function `Object.prototype.toString` into the constant `toString`. This function is called whenever the object has to be converted to a string.

Most objects provide an overridden implementation of the `toString` function. For example, an array will look like a comma-separated list of all values it holds.

The default behavior of `Object.prototype.toString` is to return a string of the format `[object "TYPE"]`. The "TYPE" is substituted with the actual type of the object. In our case, it’s `Array`.

So, with `toString.call(arr)` we call the original implementation of `Object.prototype.toString`. 

---

**ANSWER**: the string `[object Array]` will be printed to the console.

[Learn Full Stack JavaScript](https://js.coderslang.com)
Scan AWS IAM Keys In A Commit
Tags: aws, security, cloudopz, devops
Published: 2021-02-24 16:24:54

### - Sometimes developers add their env file to git commit which contains AWS Access key, to avoid this, we can use git HOOK to check personal key first and use merge_request pipeline job to check before merging the commit to branch

---

## What’s In This Document 
- [How to scan all AWS keys](#-How-to-scan-all-AWS-keys)
- [Test A Commit](#-Test-A-Commit)

---

### 🚀 **[How to scan all AWS keys](#-How-to-scan-all-AWS-keys)**
https://github.com/vumdao/scan-iam-keys/blob/master/scan-iam-keys.py

```
#!/usr/bin/env python
import boto3
import subprocess as sub
import re
import threading


def get_commit_change_content():
    output = sub.check_output(["git", "show"])
    return output


def scan_iam_access_keys():
    iam = boto3.client('iam')
    users = iam.list_users()['Users']
    commit_change = get_commit_change_content()

    def check_key(the_key):
        if re.search(the_key['AccessKeyId'], str(commit_change)):
            print(f"Detect {the_key['AccessKeyId']}")

    def check_user(the_user):
        user_name = the_user['UserName']
        print("Get keys")
        access_keys = iam.list_access_keys(UserName=user_name)['AccessKeyMetadata']
        for key in access_keys:
            check_key(key)
        print(f"Done {user_name}")

    for user in users:
        user_thread = threading.Thread(target=check_user, args=(user,))
        user_thread.start()


if __name__ == '__main__':
    scan_iam_access_keys()
```

### 🚀 **[Test A Commit](#-Test-A-Commit)**
- Create text file eg. [sample.txt](https://github.com/vumdao/scan-iam-keys/blob/master/sample.txt) which contains an AWS key
- Run test
```
⚡ $ ./scan-iam-keys.py 
Detect AKIAZUFR7JW2ZBEOKUVR
```

## **Notes**:
- For offline way, we can use the pattern `(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}` to  scan the repository or the commit changes

<h3 align="center">
  <a href="https://dev.to/vumdao">:stars: Blog</a>
  <span> · </span>
  <a href="https://github.com/vumdao/">Github</a>
  <span> · </span>
  <a href="https://vumdao.hashnode.dev/">Web</a>
  <span> · </span>
  <a href="https://www.linkedin.com/in/vu-dao-9280ab43/">Linkedin</a>
  <span> · </span>
  <a href="https://www.linkedin.com/groups/12488649/">Group</a>
  <span> · </span>
  <a href="https://www.facebook.com/CloudOpz-104917804863956">Page</a>
  <span> · </span>
  <a href="https://twitter.com/VuDao81124667">Twitter :stars:</a>
</h3>
Starting with Flutter: showing markdown
Tags: markdown, flutter, dart, beginners
Published: 2021-02-24 16:21:49

Markdown is awesome, you can show rich text without using that ugly http code. On Flutter you have a great package to use to show markdown: [flutter_markdown](https://pub.dev/packages/flutter_markdown).

It is extremely easy to use in its basic "mode" but we'll also show some advanced features.

### Installation

That's a no-brainer, just add to your pubspec.yaml:

```dart
dependencies:
  flutter_markdown: ^0.5.2
```

and do a good old

```dart
$ flutter pub get
```

then import the package like this:

```dart
import 'package:flutter_markdown/flutter_markdown.dart';
```



### Showing a file

We'll use the text file on [this repository](https://github.com/mxstbr/markdown-test-file) (all credits to [mxstbr](https://github.com/mxstbr)), so we'll create a FutureBuilder and http to get text and give it to our Markdown renderer widget:

```dart
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.red,
        ),
        body: Center(
          child: FutureBuilder(
            future: getTextData(),
            builder: (context, snapshot){
              if(snapshot.hasData){
                //HERE we need to add the text renderer
              }
              return Container();
            }
          )
        ));
}

Future<String> getTextData() async{
    String url = 'https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/TEST.md';
    var response = await http.get(url);
    return response.body;
  }
```

To show the markdown content we just need to return this iwdget inside the builder:

```dart
return Markdown(data: snapshot.data);
```

the result will be this:

![Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5n8p6nhcffvrkzmhcal.png)

the widget is already scrollable, if we need to add it to a scrollable parent we should use `MarkdownBody`.

### Some advanced features

This package also includes:

- Image support in form of URL, absolute file or resources
- Selectable text
- Emoji support
- AutoLink support

and more.

There, your natural evolution of WYSIWYG is here, you are welcome.
React - how to make left-side animated menu
Tags: react, javascript, webdev, css
Published: 2021-02-24 16:13:04

Hey there! 👋 😊

In this post, I want to show you a left-side animated menu that I created recently.

__Before we start__, I would highly recommend you to check out __runnable example__ for the solution on our website:
[React - how to make left-side animated menu](https://dirask.com/posts/React-how-to-make-left-side-animated-menu-jmyONj)

Final effect:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpbi1ubqak6r911sgzr4.png)

Below I present you how to create this simple customized left-side menu that displays list of different kind of food 🍒🥦🍟 on click event.

In the solution, I've used a modern approach that involves the use of functional components and React hooks. In this case `useState` hook stores the state of my side menu if it's visible or not.

There is also some styling in the example, which I recommend you carefully analyze and change as you want. You can also modify the runnable example [here](https://dirask.com/posts/jmyONj) and create your own left-side animated menu with no need to use any additional tools. 😊

Practical example:
```jsx
import React from 'react';

const buttonStyle = {
  padding: '10px 20px',
  border: '2px solid #3085d6',
  borderRadius: '5px',
  background: '#3085d6',
  boxShadow: '5px 5px 5px grey',
  textShadow: '1px 1px 1px black',
  fontWeight: '900',
  color: 'white'
};

const commonStyle = {
  position: 'fixed',
  top: 0,
  bottom: 0,
  padding: '5px',
  border: '1px solid #0657FF',
  borderRadius: '0 30px 30px 0',
  background: '#C9E5FF',
  width: '280px',
  transition: '0.5s',
  overflow: 'hidden'
};

const visibleStyle = {
  ...commonStyle,
  left: '0'
};

const hiddenStyle = {
  ...commonStyle,
  left: '-300px'
};

const liStyle = {
  margin: '10px',
  padding: '5px',
  border: '2px solid #3085d6',
  borderRadius: '5px',
  background: '#5fa8ed',
  boxShadow: '5px 5px 5px grey',
  textShadow: '1px 1px 1px black',
  fontWeight: '900',
  color: 'white',
  listStyle: 'circle inside'
};

const App = () => {
  const [visible, setVisible] = React.useState(false);
  return (
    <div style={{ height: "200px" }}>
      <button style={buttonStyle} onClick={() => setVisible(true)}>
        Show
      </button>
      <div style={visible ? visibleStyle : hiddenStyle}>
        <button style={buttonStyle} onClick={() => setVisible(false)}>
          Hide
        </button>
        <div>
          <ul>
            <li style={liStyle}>Fruits 🍏🍌🍒</li>
            <li style={liStyle}>Vegetables 🥕🥦🍅</li>
            <li style={liStyle}>Fast Food 🍕🍟🍔</li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default App;
```
You can run this example [here](https://dirask.com/posts/jmyONj)

Leave a comment to let me know what you think! 😊💬
_____________
## Write to us! ✉
If you have any problem to solve or questions that no one can answer related to a React or JavaScript topic, or you're looking for a mentoring write to us on [dirask.com -> Questions](https://dirask.com/questions)
Chainlink Launches Off-Chain Reporting (OCR), a Major Scalability Upgrade
Published: 2021-02-24 15:54:42

We’re excited to announce that after over a year of development and numerous security audits, Chainlink Off-Chain Reporting (OCR) has officially launched on mainnet, marking a major milestone and improvement in the scalability of Chainlink’s decentralized oracle network.

Chainlink OCR significantly improves the efficiency of how data is aggregated by Chainlink oracles, reducing gas and operating costs by up to 90% and generating a 10x increase in the amount of real-world data available to smart contract applications. Read more about the launch here: http://chn.lk/2ZJ3Wuk
Remove unused npm modules from package.json
Tags: node, depchecknpm, npxdepcheck, removeunusednpmpackagejson
Published: 2021-03-04 05:28:21

---
title: Remove unused npm modules from package.json
published: true
date: 2021-02-24 15:50:55 UTC
tags: NodeJS,depchecknpm,npxdepcheck,removeunusednpmpackagejson
canonical_url: https://poopcode.com/remove-unused-npm-modules-from-package-json/
---

[Depcheck](https://github.com/depcheck/depcheck) is a tool for analyzing the dependencies in a project to see: how each dependency is used, which dependencies are useless, and which dependencies are unused from package.json. To identify the unused package, just run *npx depcheck* in the project root directory.

```
> npx depcheck


npx: installed 146 in 88.761s
Unused dependencies
* express-validator
```

Next step is to [uninstall the npm packages](https://poopcode.com/how-to-uninstall-npm-modules-in-node-js/) using *npm uninstall* command.

```
npm uninstall express-validator
npm WARN retina-backend@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

removed 2 packages and audited 626 packages in 12.337s

24 packages are looking for funding
  run `npm fund` for details

found 24150 vulnerabilities (24147 low, 3 high)
  run `npm audit fix` to fix them, or `npm audit` for details
```

The post [Remove unused npm modules from package.json](https://poopcode.com/remove-unused-npm-modules-from-package-json/) appeared first on [Poopcode](https://poopcode.com).
Responsive Message Feed
Tags: html, css, javascript
Published: 2021-02-24 15:38:28

A responsive landing page for a fictional app: a feed of rants from around the world/country/city/local.

UI: photo, rant title or user's name, the message with some effects.

Future changes: Btn(vote +/-), shareBtn, viewCounter, userId, messageId. etc...

Link to the scrim: https://scrimba.com/scrim/cB8k3DHw

Link to the pen: https://codepen.io/iamserda/pen/MWbrapw

API: JSONPlaceholder
Tech: vscode, html, css, javascript, es6+

Photo from Unsplash. I have provided a link to the photographer's unsplash page. 

Interface mostly built dynamically via DOM manips.

- iamserda
Cool json git diff command
Tags: bash, git, productivity, todayilearned
Published: 2021-02-24 15:36:23

`git diff` is great but kinda sucks when reporting about deep keys updates in JSON files, because it only shows the last key, and not the whole object path to the updated key

```console
$ git diff HEAD~1 -- file.json
...
-       "name": "John Doe"
+       "firstName": "John",
+       "lastName": "Doe"
...
```

But by combining [`gron`](https://github.com/tomnomnom/gron) with `git show $rev:$path`, we can have a very pretty output that tells which keys have been updated, and it's almost valid JS!

```console
$ diff <(git show HEAD~1:file.json | gron) <(gron file.json)
< json.users[0].owner.name = "John Doe";
---
> json.users[0].owner.firstName = "John";
> json.users[0].owner.lastName = "Doe";
```

I found that too elegant not to share. Have fun scripting!
My Journey To Flatiron School and Coding
Tags: beginners, devjournal, codenewbie
Published: 2021-02-24 15:07:31

Hi! My name is Kyle Samuel. I’m a professional musician from Austin, Texas. I recently got married and moved to Alexandria, VA with my wife. We are living with my sister-in-law and our four-year-old niece. I am in a band called All Get Out. We are on Equal Vision Records, currently working on a new album, and waiting out the pandemic along with everyone else!

2020 started out with a month-long tour of the country followed by a beautiful honeymoon in Thailand. Upon landing back in the States, our expectations of the year were subverted. Suddenly, my profession was shut down, with no gigs available due to COVID-19 closing anything that would resemble a venue. I always knew I wanted to do music for a living, and I picked up the guitar at 13 with that in mind. So, having gone straight out of high school into the life of a working musician, I was initially confused about how to proceed. Continuing to hone my craft proved satisfying for a season, but the good feelings would not last long, and I settled into a depression borne from losing my “thing” in life.

Fortunately, depression turned to introspection, which led me to think about all the interests I had prior to music, particularly computers. I made myself very familiar with my family’s Macintosh (and later, PC) from a very early age, probably four or five. My brother and I built our own computers in middle school, and would relentlessly tinker with the BIOS and other files in the pursuit of the ultimate framerate on Counter-Strike. It was a passion that ultimately got left behind because of my other passion.
Mulling this over, I finally landed on coding as the perfect harmony of my interest in music and computers. Music in its composition resembles coding in its arrangement of form, theory, and art; The left and right brain cooperating to a much larger end. It also often involves collaboration, a consensus on what any given song or project “is”, and, of course, communication. I felt that same passion start to ignite in my chest that drove me to music at 13.

Fast forward to now, today is my first day at Flatiron School. I’ve spent months preparing for today, and thankfully, I’m feeling confident and ready for whatever comes. 

Kyle Samuel
Aspiring Coder, Musician
React Table - the "bread and butter" of any business app
Tags: react, javascript
Published: 2021-02-24 14:46:10

I'm sure any of you developing business apps have got to a point where data need to be displayed in a tabular format. If you develop using React a great React Table component is a must to have. The React Table components are complex components, difficult to develop and maintain. Luckily there are several components available - both open source and commercial ones. 

ReactDataGrid is a great, mature, enterprise ready [react table](https://react-table.io/) component which comes in two editions: Community and Enterprise. 

It has lots of great features and what's really important, a powerful [API](https://reactdatagrid.io/docs/api-reference) which allows you to cover really complex use cases.

Give it a spin and let us know how it goes!
Katas, Github and Terminal. Oh my!
Published: 2021-02-24 14:44:19

How I am using codewars.com to help me understand JavaScript, also using it for terminal and github practice. This post is for beginners who are struggling with understanding whatever programming language they are learning. My first ever “blog” but I wanted to share this because it has helped me a lot. 

If you don’t know what codewars is, it is a site where you can practice your programming knowledge. They give you an empty function to fill out that will solve a problem. Codewars is HARD, don’t jump right into it. Here are some tips that will help you get started on the easier ones. Goto the left nav bar and click on katas. Make sure your language is selected (can set this up when you signup so you don’t have to select every time) and sort by most completed. Start with the 8kyu’s. The lower the number, the harder the kata. Start with the fundamentals track. If you can, try to organize the problems you are working on into groups. For example, if you are working on arrays, do a few problems that are just arrays. There are soooooo many ways to get the same thing done, and there are so many methods we can use to help, so repetition is important. 

Are you just freezing up at every kata? If you are spending more than 20 minutes trying to figure out the answer, goto the solution. Either google the solution “(kata name) codewars” or just hit unlock solution. Spend some time analyzing the answer. Try to understand why they did it that way, and remembering the syntax will help. A lot of these will require memorization of certain methods, but the more you do the same type of problem, the easier it is to remember. A lot of these katas are just insane word problems. If I feel like it’s too insane or too mathy, I’ll just try a different kata. My wife, who is currently learning JavaScript with me, has gotten such a confident boost from doing all these katas. She used to freeze up, mind blank, filled with intense imposter syndrome. Now she is completing katas on her own, refactoring them to one liners, and pushing solutions to github. Like a straight up G.

After I have the solution ready to go, I open up my terminal (git bash bc I am on Windows), cd into my codewars folder, mkdir a new folder for the kata, touch main.js will create a new JavaScript file in that folder. Then “code main.js” will open up that new file in my editor! Pretty cool.. (I have my github repo in the codewars folder already) so all I have to do is paste the instructions and solution into the js file, save it, then back to terminal. 

Git add .

Git commit -m “kata name”

Git push

Boom, our solution is now on our github! (There are a few more steps if you are doing this for the first time) 

I used to hate codewars because it just made me feel kind of dumb. Now I can’t get enough of them. So far I have completed 123 katas and it has really solidified my understanding of JavaScript. If anyone needs help with any of this, please reach out to me, we can practice over a discord call. I would be more than happy to help you with codewars, git/github, or terminal.
Hướng dẫn Reset MySQL Or MariaDB Root Password
Published: 2021-02-24 14:38:55

Reset MySQL or MariaDB Root password.
First, stop the database server.

If you use MySQL, type the following command and hit ENTER key.

$ sudo systemctl stop mysql
For MariaDB:

$ sudo systemctl stop mariadb
Next, restart the database server without permission-checking using the following command:

$ sudo mysqld_safe --skip-grant-tables &
Next, login to your MySQL/MariaDB server as root user:

$ mysql
At the mysql> or MariaDB [(none)]> prompt, run the following command to reset the root user password:

UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
Replace password in the above command with your own password.

Then, type following commands to exit from the mysql console.

FLUSH PRIVILEGES;
exit
Finally, shutdown the running database server that you started earlier with --skip-grant-tablesoption. To do so, run:

$ sudo mysqladmin -u root -p shutdown
You will be asked to enter your mysql/mariadb root user password that you set in the previous step.

Enter password: 
[2]- Done sudo mysqld_safe --skip-grant-tables
Now, start mysql/mariadb service normally using command:

$ sudo systemctl start mysql
For MariaDB:

$ sudo systemctl start mariadb
Verify if the password has really been changed using the following command:

$ sudo mysql -u root -p
Chúc các bạn thành công!
Day 58 Of 100DaysOfcode: More About Algorithm
Tags: womenintech, 100daysofcode, codenewbie, beginners
Published: 2021-02-24 14:36:52

Todays I completed 58th day of #100daysOfCode and #python learning. Like yesterday today also continued to learned more about SQL properties(CROSS JOIN, UNION, UNION ALL, INTERSECT, EXCEPT) from [Datacamp](https://campus.datacamp.com/courses/joining-data-in-postgresql/set-theory-clauses?ex=15)

Tired to complete some assignment from Coursera. Learned more types of algorithms from algorithmic toolbox. I tried to solve car fueling problem which is given below.

#Python code

 
```python
def compute_min_refills(distance, tank, stops):

    numrefill, currentrefill= 0,0
    stops = [0] + stops + [distance] #include the start and end points in the stops list   
    if distance <= tank:
        return 0
    else:
        while currentrefill < len(stops)-1:
            lastrefill = currentrefill
            #print(currentrefill, lastrefill, len(stops))
            while currentrefill < len(stops)-1 and stops[currentrefill+1] - stops[lastrefill]<=tank:
           
                currentrefill += 1

            if currentrefill == lastrefill:
                return -1
            if currentrefill < len(stops)-1:
                numrefill +=1

        #print(numrefill)

        return numrefill
if __name__ == '__main__':
    d, m, _, *stops = map(int, sys.stdin.read().split())
    print(compute_min_refills(d, m, stops))
``` 
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Day 58 Of <a href="https://twitter.com/hashtag/100DaysOfCode?src=hash&amp;ref_src=twsrc%5Etfw">#100DaysOfCode</a> and <a href="https://twitter.com/hashtag/Python?src=hash&amp;ref_src=twsrc%5Etfw">#Python</a> <br>* SQL (CROSS JOIN, UNION, UNION ALL, INTERSECT, EXCEPT) From Datacamp<br>* More about Algorithm <br>* Car Fueling <a href="https://twitter.com/hashtag/womenintech?src=hash&amp;ref_src=twsrc%5Etfw">#womenintech</a> <a href="https://twitter.com/hashtag/CodeNewbie?src=hash&amp;ref_src=twsrc%5Etfw">#CodeNewbie</a> <a href="https://twitter.com/hashtag/DEVCommunity?src=hash&amp;ref_src=twsrc%5Etfw">#DEVCommunity</a> <a href="https://t.co/m6S9iYETX1">pic.twitter.com/m6S9iYETX1</a></p>&mdash; Durga Pokharel (@mathdurga) <a href="https://twitter.com/mathdurga/status/1364580892354568194?ref_src=twsrc%5Etfw">February 24, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>