teleren/devto huggingface dataset:
Artificial Intelligence Chatbot
Tags: python, ai
Published: 2021-08-29 18:10:32

Yesterday I finished this little side project. The goal was to learn more about AI in python and I always wanted to build some kind of bot, that communicates with me. So I started to do some research on how to handle with all these input data. After a few YouTube videos and a lot of tutorials on the internet, I started coding and ended up with this... 
It still has no name 😂...
Maybe you have some ideas.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/csz7hq4epgh1tyeiu8p0.png)
Analyze slidev example
Published: 2021-08-29 18:02:51

<sub>Photo by <a href="https://unsplash.com/@isaacmsmith">Isaac Smith</a> on <a href="https://unsplash.com/s/photos/analysis">Unsplash</a></sub>

I have tried to create [slidev slides](https://sli.dev/) and i analyzed [this example](https://demo.sli.dev/composable-vue/1) to understand how to use layout.


We can use the follwing layouts:
- layout: cover  First Page
- layout: 'intro'  Speaker Presentation
- layout: center   centered content
- Split 2 columns : <div class="grid grid-cols-2 gap-x-4 mt-4"><div>Content first column</div><div>Content second column</div></div>


Hope this helps !
Get Foods {Day - 16}
Tags: 100daysofcode, beginners, javascript, webdev
Published: 2021-08-29 17:53:18

#100daysofcode { Day - 16 }

Here you can search for the food of your choice and find out the details by clicking on the food. I created it using the themealdb API and currently updating the site.

Live Preview: https://alsiamworld.github.io/get-foods/

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lff0hpexfq4eyhs97hzq.png)
Building API in Rails Series
Tags: ruby, rails, ror, rspec
Published: 2021-08-29 17:43:13

---
title: Building API in Rails Series
published: true
description: This is the series of blogs for building api in Rails
tags: ruby, rails, ror, rspec
cover_image: https://developerblogs.github.io/assets/img/api.jpeg
---

Hi there, welcome to the series of **Building API in Rails**. Let's just start with what this series will cover 

1. Setting up our Ruby on Rails API only application with all necessary gems and stuff.
2. Adding Rspec for the TDD approach.
3. Building a CRUD RESTful APIs
4. Active model serializers
5. Integrating Fast JSON api, JSON API specification
6. Securing our API with JWT
7. Integration SWAGGER for api documentation
8. and many more....

<a href="https://developerblogs.github.io/blogs/rails_api_series/01" target="_blank">**:one: Buidling API in Rails Part 1 :rocket:​** </a>.

<a href="https://developerblogs.github.io/blogs/rails_api_series/02" target="_blank">**:two: Buidling API in Rails Part 2 :gem:** </a>.

<a href="https://developerblogs.github.io/blogs/rails_api_series/03" target="_blank">**:three: Buidling API in Rails Part 3 :rocket:​** </a>.

<a href="https://developerblogs.github.io/blogs/rails_api_series/04" target="_blank">**:four: Buidling API in Rails Part 4 :muscle:​** </a>.

<a href="https://developerblogs.github.io/blogs/rails_api_series/05" target="_blank">**:five: Buidling API in Rails Part 5 :lock:​** </a>.
Media Queries in JS
Tags: react, javascript, webdev
Published: 2021-08-29 17:39:57

In these modern times, your web applications can be viewed in a variety of screen sizes -- from small screen phones to large 4k monitors. Luckily CSS allows us to add certain stylings depending on many variables using media queries. Sometimes using media queries isn't enough to achieve the goal. This is where `matchMedia` could help.

`matchMedia` is a method provided by `window` that can determine whether the given media query matches the current state of the browser.

## `matchMedia`

`matchMedia` accepts a media query as a string and returns a `MediaQueryList` which can be used to check if the current state of the browser matches the given media query.

```javascript
const mediaQueryList = window.matchMedia("only screen and (max-width: 600px)");

if (mediaQueryList.matches) {
  console.log("Matches");
} else {
  console.log("Does not match");
}
```

### Keeping track of changes

We can keep track of these changes by listening for a change event.

```javascript
const callback = (event) => {
  if (event.matches) {
    console.log("Matches");
  } else {
    console.log("Does not match");
  }
}

mediaQueryList.addEventListener("change", callback);
mediaQueryList.removeEventListener("change", callback);
```

If you need to support older browsers, you can use `addListener` and `removeListener` respectively but do remember that those methods are deprecated.

```javascript
mediaQueryList.addListener(callback);
mediaQueryList.removeListener(callback);
```

## `useMediaQuery`

This technology can also be transferred to a reusable React hook. The hook will accept a media query and a callback function for when changes occur.

```javascript
const useMediaQuery = (query, callback) => {
  const [isMatchingQuery, setIsMatchingQuery] = useState(false);

  useEffect(() => {
    const mediaQueryList = window.matchMedia(query);
    const onMediaQueryUpdate = (e) => {
      setIsMatching(e.matches);

      if(callback) {
        callback(e);
      }
    };

    // Set whether the browser initially matches the query
    setIsMatchingQuery(mediaQueryList.matches);

    mediaQueryList.addEventListener("change", onMediaQueryUpdate);
    return () => {
      mediaQueryList.removeEventListener("change", onMediaQueryUpdate);
    }
  }, [query, callback, setIsMatchingQuery]);

  return { isMatchingQuery };
}
```

If you're already using `matchMedia` in your project, how are you using it? If you're using a different framework, how would you incorporate `matchMedia` into that framework?
Installing open-wc on Mac
Published: 2021-08-29 17:26:52

**Introduction**
When installing open-wc on Mac, there are a few software installs that need to be done. The software that we will be installing are NodeJS, yarn, and the open-wc boilerplate.

**Installing NodeJS**
To install NodeJS just click [here](https://nodejs.org/en/). Follow the instructions of the install, and since NodeJS comes with npm we do not have to install it separately. To double-check that both were installed currently you can type in `node -v` and `npm -v` into your terminal.

**Installing Yarn**
First, start by opening your terminal and typing `npm install -g yarn`. If there is a permissions error when you are trying to install yarn then you may need to type sudo npm `install -g yarn` instead.

**Open-wc boilerplate**
To finish out we are going to run a test project of hello-world. So, in your terminal, you are going to navigate to the folder you want to keep the folder in by using cd. For example, if I wanted to use my edtechjoker folder that is in my git folder which is located in my documents folder I would type `cd Documents` and enter it then `cd git` enter, and finally `cd edtechjoker` enter. Once you are in the folder you want you will run this command `npm init @open-wc`. As long as your installs are all working you should be able to scaffold a new project by using your enter key. You will then want to select web component with your return key. After that, you should be able to select all three tooling options of linting, testing, and demoing by using your space bar. Next, you will want to select no for using typescript and then set the name as `hello-world` with no caps or it will throw a fit. Finally, select yes to write the file structure to disk and yes with yarn to finalize the install. If the install was successful you should get a message that says it is set up. 

**Run Project**
Just simply type `cd hello-world` and then `npm run start`.
.map() Polyfill
Tags: javascript, functional
Published: 2021-08-29 17:21:35

## What is a polyfill?

Polyfill is code that implements a feature on web browsers that is expected to be provided by the browser natively but is not available. The developer uses one's logic to implement the solution.

## What is .map()

It is an array function that is used to iterate over an array and create a new array with the results of the calling of the function. This comes in handy when we don't want to implement the for loop from scratch and want to modify all the elements of the array in the same way, hence saving a lot of time as well as some lines of code.

The function is applied in an array and takes in another function as a parameter (known as callback function). In the callback function's parameters __the current element of the array__, __index__ , and __the complete array__ are passed. They same way it happens in the ___.forEach()___ function.

`.map()` is very similar to that of `.forEach()`. But instead of returning the items, `.map()` returns the a new array by modifying the existing elements. (the old array doesn't get changed)

## Writing the Polyfill

We will be iterating over an array of some listed companies in NSE and adding the prefix of "NSE:" before every stock.

```js
var stocks = [
  'COLPAL',
  'ITC',
  'IOC',
  'NHPC',
  'INFY',
]
```

Firstly let's try running the native `.map()`

```js
nseStocks = stocks.map(function (stock) {
  return `NSE: ${stock}`
});

console.log(nseStocks)
// ["NSE: COLPAL", "NSE: ITC", "NSE: IOC", "NSE: NHPC", "NSE: INFY"]
```

So, now let's write the polyfill and add the map function to the prototype of Array.

```js
Array.prototype.myMap = function (callback) {
  var newArray = [];
  for (var i = 0; i < this.length; i++) {
    newArray[i] = callback(this[i], i, this)
  }
  return newArray;
}
```

Now let's try running our polyfill.

```js
nseStocks = stocks.myMap(function (stock) {
  return `NSE: ${stock}`
});

console.log(nseStocks)
// ["NSE: COLPAL", "NSE: ITC", "NSE: IOC", "NSE: NHPC", "NSE: INFY"]
```

## Connect with me

> For more ***awesome*** JS or WebDev related blogs [check out my profile](https://dev.to/swapnadeepmohapatra/)

[LinkedIn](https://www.linkedin.com/in/swapnadeep-mohapatra-11b371159/) [My Portfolio](https://www.swapnadeep.com/) [Twitter](https://www.twitter.com/swapnadeeptukk/) [Instagram](https://www.instagram.com/swapnadeep_mohapatra/)
Introduction
Published: 2021-08-29 16:36:52

Hello everyone! My name is Perry McLaughlin.  I am a senior from Cleveland, Ohio currently studying Human-Centered Design and Development.  I will be graduating in December and am so excited! 

I do not have a ton of programming experience outside of course work here at Penn State. I have been lucky enough to take a fair amount of programming courses while I have been here at Penn State.  I have taken probably 2-3 programming courses a year since I have been here. Outside of these courses, I do not have much experience. This past summer I worked for a mortgage bank located in Cleveland, Ohio.  During my internship there I worked as a business systems analyst.  My job was focused on writing requirements to present to developers and do vendor research on possible products that we could purchase.  I worked very closely with multiple developers but was not doing any of the actual programming. An example of a project that I worked on during my time there was creating an automated email to send out to loan officers when loans that they were working on were getting close to the closing date.  It was a really good project to get my foot in the door and was able to work with the developers to get that automated email created.   

I am really excited to get the semester started and learn many new things through out it.  I wish everyone the best this semester.
Optimizing JavaScript
Published: 2021-08-29 16:29:59

One of my daily code challenges this week was to return the number of occurrences of the max value of an array.  At first I just tried the "brute force" iteration approach with a dictionary to keep track of the count:
```
    const ar = [3,2,1,3] // there are 2 3's so 2 should be my result
    const dict = {}
    for (let i=0; i<ar.length; i++){
        if (dict[ar[i]]){
            dict[ar[i]]++
        } else {
            dict[ar[i]]=1
        }
    }
    // console.log(Object.keys(dict).length)
    return (Object.values(dict).sort()[Object.keys(dict).length-1])
```
... which did work but I always like to shoot for a "one-line" solution.
So, I took my iteration and started thinking through the built in prototype.Array functions in JavaScript.  I decided to use "filter()" because it will return a sub-set of the original array.  Then I can use "length" to get the count of the elements that match the filter.  Seems easy enough:
```
ar.filter(el => el == 3).length // returns 2
```
My "3" comparison value is just psuedocode for now, only because I already know the max value.  Now I have to find the max value so I can make this a dynamic function.  I can use "Math.max()" to determine the max value of the array:
```
Math.max(...ar) // returns 3
// using the spread operator "..." is shorthand for using "apply".  The "apply" method could also be used:
Math.max.apply(null, ar)
```
So now I can just replace my psuedocode value with the function to find the max of the array:
```
ar.filter(el => el == Math.max(...ar)).length // returns 2
```
...which does work but since this is a code challenge, the solution times out and fails the test cases (if you do code challenges, you know what this means).
I examined what was happening and noticed that even if a function is nested within another function - on one line or otherwise - it still is a nested function.  For every element of the ar filter step, it was checking to find the max value of the array.  I'm pretty sure this would be O(n^2).  But if I create a variable (maxVal) and assign the max value (Math.max(...ar)) OUTSIDE of the filter function, then the timeout errors go away and all test cases pass:
```
    const maxVal = Math.max(...ar)
    return (ar.filter(el => el == maxVal).length)
```
So, not exactly a one line solution but much leaner and cleaner than the "brute force" method where I started.  And a valuable lesson, for sure!
Real World Python 🐍: Introduction
Tags: python, beginners
Published: 2021-08-29 16:28:44

## Motivation

There is a gap in the python material available online. While a lot of tutorials are available for absolute beginners, there is a distinct lack of content for those who are looking to take the next step.

Nature abhors a vacuum. So, here I am to fill the void. In this series we will cover all the stuff that goes into making a real world python project.

## Intended Audience

Python beginners who have knowledge of the fundamentals of programming and are looking to start with their first real project. I will assume that the reader already knows topics such as conditional statements, loops, functions etc. My focus will be more on the structure and the "flow" of a project rather than the logic.

## What we will build

A web scraper which grabs quotes from [goodreads.com](https://www.goodreads.com/quotes/437173-talk-is-cheap-show-me-the-code) and stores them locally or to a remote database.

{% github tintindas/quotes-scraper no-readme %}

## Roadmap

These are the planned topics for the series.

1. Environment Setup - pyenv
2. Project Setup
3. Directory Structure

## Some Notes

- This is my way of doing things which is just one way out of many. There are no hard and fast rules. Most of the steps in this series are optional, but highly recommended.
- The series is mostly geared towards Mac/Linux systems. Though it should all work on WSL too.
What did you teach this week?
Tags: teachingthisweek, discuss
Published: 2021-08-29 16:27:45

> The art of teaching is the art of assisting discovery.
– Mark Van Doren

Teaching is perhaps the most noble profession ever! We as Developers, too can participate as teachers in many different ways. Writing blogs, answering on stack exchange or helping a collogue with a tricky concept all count in teaching.


Whatever you have taught this week, however small, counts as a big help!
 So please comment below, your teachings in this week! 
![teacher-school](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cyte0sp7cge3hjmodlrj.gif)
JS Coding Question #4: Remove Duplicates [Common Question]
Tags: challenge, javascript, tutorial, career
Published: 2021-08-29 16:21:06

---
title: JS Coding Question #4: Remove Duplicates [Common Question]
published: true
description: Front end job interview question, Remove Duplicates, Get Unique Characters
tags: challenge, javascript, tutorial, career 
cover_image: https://images.unsplash.com/photo-1617529497471-9218633199c0?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1650&q=80
series: Job Interview Preparation Materials
---

#### Interview Question #4:
Write a function that will remove duplicate in an array❓🤔 You can get a variation of this question as Get unique characters from a list.

> If you need practice, try to solve this on your own. I have included 2 potential solutions below. 

> Note: There are many other potential solutions to this problem.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

Code: https://codepen.io/angelo_jin/pen/PojPRzQ

#### Solution #1: ES6 Set
- uses the elegance of Set just like other programming languages. A value in the Set may only occur once; it is unique in the Set's collection.
```js 
function removeDuplicates(array) {
  return [...new Set(array)]
}
```

#### Solution #2: Object
- below will use a js plain object to store key value pairs. Value can be other values as well, i chose to increment it so we may use it for other purpose like get the total count for a characters, etc.
```js
function removeDuplicates(array) {
  const map = {}

  for (const char of array) {
    if (map[char]) {
      map[char]++
    } else {
       map[char] = 1
    }
  }

  return Object.keys(map)
}
```

Happy coding and good luck if you are interviewing!

If you want to support me - [Buy Me A Coffee](https://www.buymeacoffee.com/letscode77)

In case you like a video instead of bunch of code 👍😊
{% youtube nrNTiIRY9MU %}
The Difference Between Arrays and Objects(simplest explaination).
Tags: javascript, webdev
Published: 2021-08-29 16:04:45

In JavaScript, *arrays* use numbered indexes.  

In JavaScript, *objects* use named indexes.

**Arrays** are a special kind of **objects**, with numbered indexes.

When to Use **Arrays**. When to use **Objects**.
1. JavaScript does not support associative arrays.
2. You should use objects when you want the element names to be strings (text).
3. You should use arrays when you want the element names to be numbers.
2021 week 34, JS array & Base64 encoding. Plus Malaysian national anthem.
Tags: javascript, array, base64
Published: 2021-08-29 15:52:48

It's the time of the year in Malaysia where the national flag can be seen everywhere, so I included a tiny history piece as the third item. The first two items are both JavaScript - one on array and another on Base64, the latter seems like it can become a whole article of its own but I kept it short.

- **JavaScript - array**: `[...x]` will result in an array if `x` is iterable. `Array.from(potatoes, (potato) => potato)` will also result in an array if `potatoes` is iterable, but `potatoes` can also be an array-like object, e.g. `{0: small, length: 1}`, that allows us to create a transformed array out of an array-like object, e.g. `const dinner = Array.from(potatoes, (potato) => cook(potato))`.

- **JavaScript - Base64**: while `btoa()` and `atob()` can be used in a browser environment to convert between binary data and Base64 encoded string, they have recently made their way to Node.js as well but use them wisely because character encoding can be tricky and Base64 encoding can easily increase the data size by a third.

- **History - Malaysia**: the founding father - Tunku Abdul Rahman was part of the panel of judges that contributed to the Malaysian national anthem. *"We're not going to War. We don't need this. We need a love song."*, and surely enough, now the national anthem has its root in the melody of a love song.

This is my 7th weekly post since July 2021, thank you for reading and do let me know if you have any feedback by leaving a comment.

### Related Links

- MDN on Array.from(): [developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
- MDN on btoa(): [developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa)
- Goodreads - Dialog: Thoughts on Tunku’s Timeless Thinking: [goodreads.com/book/show/58679923-dialog](https://www.goodreads.com/book/show/58679923-dialog)
Installing open-wc on MacOS
Published: 2021-08-29 15:47:11

Installing open-wc first requires the installation of some additional tools and dependencies. In this post, I will cover Node.js/NPM, yarn, and the open-wc boilerplate.

**Node.js**
Download the latest LTS Build of Node.js [here](https://nodejs.org/en/). Once the download is completed, the installer will have you go through a series of steps to complete agreements and enable necessary permissions. For now, stick with all of the default settings. NPM should also be installed with Node. To confirm that they were both installed, you can do `node -v` and `npm -v` in the terminal to check the version numbers.

**yarn**
Open your terminal to begin installing yarn. You can use the recently installed NPM to instal yarn with `npm install --global yarn`. If you encounter a permissions error, you may not have administrative permissions with your current user. If this is the case, use `sudo npm install --global yarn`.

Go to [https://yarnpkg.com/](https://yarnpkg.com/) for more information about yarn. 

**open-wc boilerplate**
Let's create a test project called `hello-world` to ensure everything is setup as expected. First, in your terminal, navigate to the folder where you want your project to be. Next, run the following command: `npm init @open-wc`. If your installations were successful, you should be given an option to *Scaffold a new project*. Use your return key to select this option. Next, use return to select *Web Component* and space bar to select all three tooling options: *Linting, Testing, and Demoing*. Select *No* for Typescript and set the name for you component as `hello-world` in all lowercase. Then, select *Yes* for writing this file structure to the disk and *Yes, with yarn* to complete the installation of all necessary dependencies. If everything was setup correctly, you should see the *You're all set up now!* message. To run it, do `cd hello-world` and `npm run start`.
`soim`: Social image generator CLI
Tags: showdev, writing, npm
Published: 2021-08-29 15:45:43

In my [last post on Social Image generation](https://dev.to/siddharthshyniben/introducing-the-social-image-generator-bbp), I talked about how I built a site which can be used to automate social image generation. Well, I just built a CLI for it! Introducing `soim`.

{% github SiddharthShyniben/soim %}

It's a small CLI tool to generate social images. Just run `soim --text Something --caption something ...` and get an image!

It uses puppeteer under the hood to generate images. I'll write a post on it someday.

Hope you like it!