teleren/devto huggingface dataset:
Fetch API in JavaScript
Tags: api, javascript, programming, beginners
Published: 2022-09-25 10:41:08

Basic Fetch request
```js
fetch(url)
.then(response=> response.json())
.then(data => console.log(data));
```
This is how to fetch in javascript. Very simple!

Wait not done yet.

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. Before fetch(), we used XHR (XMLHttpRequest). Using Fetch is very easy. Fetch() starts the process of fetching a resource from a server and returns Promise that resolves to a Response object.
So we dont need XMLHttpRequest anymore. But yeah, we need xhr for ajax.

But how XMLHttpRequest is look like? how to write ? 
Lets see:

```js
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();

// Define a callback function
xhttp.onload = function() {
  // Here you can use the Data
}

// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
```

### fetch()
```js
fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));
```
Here we are fetching a JSON file from our desire server and printing it to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and does not directly return the JSON response body but instead returns a promise that resolves with a Response object.

The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.

### Real Example:
Fetch url: https://my-json-server.typicode.com/typicode/demo/posts
```js
fetch('https://my-json-server.typicode.com/typicode/demo/posts')
  .then((response) => response.json())
  .then((data) => console.log(data[0].id));
// output: 1
```
Go to the link. We are fetching json from this url.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dlplc3gmn6awroz09hrk.png)

for more example, check my codepen code [FETCH "BRAKING BAD" CHARACTER](https://codepen.io/devvsakib/pen/JjJqQoR)
Creating a subscriber in medusa
Tags: javascript, webdev, beginners
Published: 2022-09-25 10:14:59

Another cool feature in medusa is that we can create custom subscribers. Subscribers are actions that are triggered by certain events.

Check out [this list with all events available](https://docs.medusajs.com/advanced/backend/subscribers/events-list/).

In our case, we want to subscribe to the `product.created` event so we can eventually request external information for each product created.

## Installing Redis

The subscriber fires based on Redis, so to make this work, you'll have to set up Redis for medusa.

First, install Redis on your machine. You can follow the documentation on [the Redis website](https://redis.io/docs/getting-started/).

Once installed, open up your medusa server project and find the `medusa-config.js` file.

You will see the following line, which defines the Redis URL. You can set it to another value via the `.env` file. (However, in most cases, this default will work).

```js
const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379';
```

Then a bit lower, you need to enable Redis in the config.

```js
module.exports = {
  projectConfig: {
    // Turn the line below on
    redis_url: REDIS_URL,
    database_database: './medusa-db.sql',
    database_type: 'sqlite',
    store_cors: STORE_CORS,
    admin_cors: ADMIN_CORS,
  },
  plugins,
};
```

And that's it. You now have Redis enabled.

## Creating a custom subscriber in medusa

Now that we have Redis installed let's create our custom subscribers.

In your medusa server project, find the `src/subscribers` folder and, in there, create a new file called: `productNotifier.js`.
I'm using this naming as I want to be a notifier for new products.

The setup for each subscriber looks like this.

```js
class ProductNotifierSubscriber {
  constructor({ eventBusService }) {
    eventBusService.subscribe('product.created', this.handleProduct);
  }

  handleProduct = async (data) => {
    console.log('New product: ' + data.id);
  };
}

export default ProductNotifierSubscriber;
```

In the example above, we subscribe to the `product.created` event, which is triggered each time a product is created.
We can tell medusa to execute our own `handleProduct` function.

Inside this function, we log the product for now.

Go ahead and spool up your server. Now visit the admin portal and add a new product.
You should see the server log showing this log now.

![medusa custom subscriber](https://cdn.hashnode.com/res/hashnode/image/upload/v1663224368007/kJ9oP7lYA.png)

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
What is a regex for a email?
Published: 2022-09-25 10:14:55

My email can also contain special characters including @,&,-,_,:,(),|
I have wrote 
```\w+([\.-:|()&_]?\w+)*@\w+([\.-:|()&_]?\w+)*(\.\w{2,3})+$```
But it doesn't seem efficient. Any suggestions?
Day 5-6: Who downloads my unfinished npm package?!
Tags: 100daysofcode, devjournal
Published: 2022-09-25 10:14:44

So, last Friday, I [published](https://dev.to/dagnelies/day-3-4-published-first-npm-package-551d) my first [npm package](https://www.npmjs.com/package/@passwordless-id/webauthn). Honestly, it was kind of unfinished ...heck, I didn't even try to see if it works properly!

But it does not matter, right? After all, nobody knows about this package. At least, nobody should know about it. I expected a 0 download rate for some time.
 
However, after some weekend time to spend some together with my family and have a break, I looked at this package again. Because of this 100DaysOfCode challenge, I thought "let's do a little bit today anyway", and what I saw surprised me greatly!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t58kl0pdgutrrloptggq.png)

Who the heck is downloading my module?! I did not advertise it anywhere. Not a word, except my post two days ago that was seen by "< 25" people as they put it, probably a gentle way to describe it to not depress the writers when the view count is a single digit on the lower end.

So almost nobody should be aware of it. Even the docs are lacking, a starter example is missing ...I don't even know if it works as intended since this whole npm publishing is a little new to me. I just know for example that the minimized browser link was not available, and after trying it to fix today, noticed that the minimized removed too much stuff. ...but the mystery of who downloaded it and how they arrived there remains.

At least, now I know I should hurry up in the next days to make it functional. ;P


Edit:

26.09 weekly downloads: 134
VirtualBox/VMware Alternatives for Linux
Tags: linux, tutorial, virtualbox, vmm
Published: 2022-09-25 09:46:37

Virtualbox always create issues in linux distribution like NS_ERROR_FAILURE (0x80004005) or gnu c compiler was not found etc, I don't know why and on the other hand VMware not free at all. So that I think QEMU/virtual machine manager is best alternative.

So we can install this by 2 simple command 
```bash 
$ sudo apt install qemu
$ sudo apt install virt-manager
```

And now open virtual machine manager via terminal 
```bash 
sudo virt-manager
```

![virtual machine manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iihscoentajwze866ycn.png)


![virtual machine manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vjodlrxmocgh6fgkjgwj.gif)


![virtual machine manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/720dulzpwr7kq0y2myob.gif)
Evaluating response times in a Support ticket
Published: 2022-09-26 12:43:50

---
title: Evaluating response times in a Support ticket
published: true
date: 2022-09-25 09:44:02 UTC
tags: 
canonical_url: https://write.as/kelvintaywl/evaluating-response-times-in-a-support-ticket?pk_campaign=rss-feed
---

I have [built a quick tool (in Python)](https://github.com/kelvintaywl/zendesk-response-times) that calculates the time taken for agents to follow up on a customer ticket on Zendesk.

If this is also useful for your support team, feel free to [copy from the source code here](https://github.com/kelvintaywl/zendesk-response-times/generate).

## Background

As a senior support engineer, I follow up with customers who left a negative review on their support experience.

We noted that some dissatisfied customers felt that they waited too long for a response. However, this is usually due to genuine misunderstandings and expectations around the response time SLAs for their support plan.

## Motivation

To make it easy for customers and ourselves to confirm our response times within a ticket, I built this tool that:

- calculates the time taken for the first agent response to each comment from the customer
- provides the arithmetic for proof
- includes information of when weekends were involved

In this tool, I elected to keep the calculation of response times agnostic to the specific plan of the customer; It merely calculates the time taken between a customer comment and an agent's response.

I find this useful, since Support plans (and their promised SLAs) may change overtime. Keeping the tool really simple allows anyone to build on top of the output (CSV file), for flexibility.

Please feel free to copy as needed. 🍺

[buy Kelvin a cup of coffee](https://www.buymeacoffee.com/kelvintaywl) ☕
Job resource Point
Tags: jobs, jobsinbankura, bankurajobs
Published: 2022-09-25 09:34:40

They are looking and searching for [Jobs in Bankura](https://www.jobresourcepoint.com/jobs-in-bankura/). through the Job Resource, Point Website gives job seekers extra advantage to apply right jobs to the right candidates If candidates in Bankura locking for jobs they can apply for jobs through the website.
Hoisting in javascript. Magic of declare order
Tags: javascript, beginners
Published: 2022-09-25 09:20:53

# What is hoisting ??
> a variable can be used before it has been declared because it stores in memory

for example

### 💎 function
```javascript
b();

function b(){
  console.log('foo');
}

// "foo" 
// ✅ thanks to hoisting, function has stored in memory before declaring
```

▼ But arrow function isn't like that

```javascript
arrFn();

const arrFn = () => {
  console.log('arrow!!');
}

// 🔥 Uncaught ReferenceError: Cannot access 'arrFn' before initialization
```

### 💎 variable

```javascript
console.log(b)
var b  = 10;

// "undefined"
// ✅ default initialization of the var is undefined.
// ❗ initial value = undefined
```

the case of const and let

```javascript
console.log(NAME) // 🔥 Throws ReferenceError exception as the variable value is uninitialized
const NAME = 'kaziu'
```

```javascript
console.log(count) // 🔥 Throws ReferenceError exception as the variable value is uninitialized
let count = 2
```
Hello Fam ️
Published: 2022-09-25 08:30:25

Hey guys 👋.
I’m curious ‘what’s your biggest problems are’ as a Frontend Developer. 
Also, you can fill out my survey below and I’ll be happy to solve the result and let’s brainstorm some solutions to them. 

https://forms.gle/fwHFt8VB5PYV2gp87
What is an XSS Filter?
Tags: spring, java, springboot, webdev
Published: 2022-09-25 08:28:20

I have a requirement to make an email field supporting all special characters. But while I am giving tes(t)@test.com in email, I am getting "XSSFilter error found" and when I skip the XSS filter for this particular URL it works fine. But what actually XSS filter do?
Lists operations from right to left. Was this really needed?
Tags: elixir, beginners, programming
Published: 2022-09-25 08:18:26

Today my little brain got one of the concepts that I wasn't quite getting. 

What is this thing about Elixir evaluating operations from right to left when it comes to lists? I can hear José Valim giggle: "this is going to break a few brains, mwahahahahaha".

Ok, José, close call, but I got this one. Gimme something trickier.

I was initially confused by this:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8et647hf2g6y4lxr1u2.png)

WHAAAAAAAAAAAT thaaa 

2?

But, but, one minus one is zero and two minus two is zero, so one and two minus one and minus two...


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uwijr3wcqznkssahna3o.gif)



So I went back to Apples And Oranges. Sesame-Street my life.

Here is my genius achievement of the day. One more step to Elixir Everest.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v67z6hihprf8q662aue0.png)

Here is looking at you, José


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/umr4t940eoctblh3u26o.gif)



git add . 
git commit -m "I am sure there is a reason for this madness"

BigSpaces
Interest Calculator In C++
Tags: cpp
Published: 2022-09-25 08:13:03

## Interest calculator System in C++
```cpp
#include<iostream>
#include<cmath>
#include<string>

using namespace std;

float simple_interest(float a, float b, int c){
	float si = (a*b*c)/100;
	return si;
}

float compound_interest(float x, float y, int z){
	float ci = x*pow((1+y/100),z)-x;
	return ci;
}

int main(){
	float p, r;
	int t;
	string m;
	cout<<"Enter your Principal Amount: ";
	cin>>p;
	cout<<"Enter your Rate of Interest: ";
	cin>>r;
	cout<<"Enter your Time: ";
	cin>>t;
	cout<<"****************"<<endl;
	cout<<"Type of Interest(s for SI and c for CI): ";
	cin>>m;
	if(m=="c"){
		cout<<"Compound Interest is: "<<compound_interest(p,r,t);
	}
	else if(m=="s"){
		cout<<"Simple Interest is: "<<simple_interest(p,r,t);
	}
	else{
		cout<<"Please select between SI & CI";
	};

	return 0;
}
```
Card with an image and rounded borders
Tags: css
Published: 2022-09-25 08:09:19

If you have a card with an image at the top and text at the bottom, and it has a border with rounded corners, the image's corners don't also round. I found various ways round fixing this, but then it turned out the answer was obvious.

## Card setup
Here's the basic set up for the card:
```html
<div class="card one">
  <img src="https://placekitten.com/200/200" alt="Kitten">
  <p>Some card text here</p>  
</div>
```
It comes with a cute kitten photo...

```css
.card {
  border: 3px solid red;
  border-radius: 0.5em;
}
```
I made the border big and red so it's obvious. You can see the the corners of the image are over the border:
![Image over border](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c88zvd7m5ymjwyk80tpw.png)

## The solution
```css
.card {
  overflow: hidden;
}
```

![Image with rounded edges](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1oxyccuzlg097x5zy3l0.png)

One line is all that's needed. It's obvious, in retrospect. `overflow: hidden` means that anything outside the edge of the card should be hidden. The edge of the card starts on the inside of the border. So it therefore cuts off the corners of the image to fit the border.
Today's Daily Humor For Devs - Daily Developer Jokes
Tags: jokes, dailydeveloperjokes
Published: 2022-09-25 08:00:26

---
title: "Today's Daily Humor For Devs - Daily Developer Jokes"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258ef9deee.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ What did the proud React component say to its child?

___A:___ I've got to give you props
 -->
Git Basics
Tags: github, git
Published: 2022-09-25 07:55:29

Git is an version controller tool developed by legend Linus Torvalds, which helps Developer tracking changes in any set of files, sometimes its a life saver, believe me 


Learn Git fundamentals in this short blog OR use it as a
cheatsheet for future references.

### First initialize the present local directory

```
git init
```
Write some code
### Stage the code to commit

- Stage all files

```
git add .
```
- Stage a specfic file
```
git add file.html
```
- Unstage a file

```
$ git restore — staged name.txt
```

### Now commit the staged code 

with a commit message for future references

```
git commit -m "First Git commit"
```

We can check commited code status by 
    ```
    git status
    ```

Check history of your commits
    ```
    git log
    ```

### Upload files to your Github Account
Now connect your Github Account and upload your files.

- First, we need to create a Github repository
    
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/npep3sj9f0a7ltvgoaxe.png)

- Copy the HTTPS link of your repository
    
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lv7nlrsvt8ckhzo9w1c4.png)

- Now add remote access to your GitHub repository
``` 
git remote add origin https://github.com/sheoranharis/sheoranharis.git
```
    **origin** is name of the link to your repo

- Create a branch by which you will push your code to the repo
```
git checkout -b mybranch
```

- We need remote access to our Github Account
    
    First, generate a SSH Key - 
    [Github Docs](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent) 
    
    then add this SSH key to your Github account - 
    [Github Docs](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent)
   
### OR
If you are using VS code, just login into VScode by your Github account
and you are good to go.

### Push your code to Github using Git
``` 
git push origin mybranch
```

We are pushing our code by **mybranch** to **origin** 

Check your Github account to see changes

*See you in next blog.....[Lets Connect](https://harish.pages.dev/)*
Productivity Boost with Cmd+. / Ctrl+.
Tags: productivity, vscode, typescript, webdev
Published: 2022-09-25 07:23:24

The light bulb icon 💡 means that VS Code found a possibility to refactor the code. It can be accessed by pressing <kbd>⌘ Cmd</kbd>+<kbd>.</kbd> / <kbd>⌃ Ctrl</kbd>+<kbd>.</kbd>

There are many more little quick fixes, but here are some I frequently use:

## Remove braces

![Remove braces](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lclfmgo6pwgboaokdzuo.gif)

---

## Add braces

![Add braces](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ge22zuzmf84q5cjyhxb.gif)

---

## Extract to a constant/function

![Extract to a constant](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fkyn49jwk83i4bc4cnxa.gif)

---

## Extract Type/Interface


![Extract Type/Interface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lqmrun2gf97i9siqews.gif)

---

## Remove unused imports

![There are many more little quick fixes options.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0v8uom3gfzoxk1emo8hd.gif)

---

## Add a missing import

![Add a missing import](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cfnn7swcd41ih533parv.gif)

---

## Add all missing imports

![Add all missing imports](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pps5kjpelhxtssx2cuf2.gif)

---

## Convert then to async await

![Convert then to async await](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0d1f70qpr7sca334xeo5.gif)

---

### Bonus Productivity Tip ⚡️
By pressing <kbd>F2</kbd>, the variable's name will be changed everywhere it is referenced.



![Renaming](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/skwikbbx1xav0ec5gy2d.gif)
Migrate to New Google Identity Service (with React & NodeJS)
Published: 2022-09-25 07:19:52

Here is the code sample of signing up users with the new Google Identity Service (GSI) using React & NodeJS. 

Official Migration Guide: [Link](https://developers.google.com/identity/gsi/web/guides/migration)

## 1. Packages used
[@react-oauth/google](https://www.npmjs.com/package/@react-oauth/google)
[google-auth-library](https://www.npmjs.com/package/google-auth-library)

## 2. Client side code

Wrap your top component with the Provider and give your Google Client ID to it.
```javascript
import { GoogleOAuthProvider } from "@react-oauth/google";

export const TopComponent = () => {
  return (
    <GoogleOAuthProvider clientId={GAPI_CLIENT_ID}>
      <YourApp />
    </GoogleOAuthProvider>
  )
}
    
```

Make a login function to retrieve the "code". 
```javascript
import { useGoogleLogin } from "@react-oauth/google";

// make a login function
const loginWitnGoogle = useGoogleLogin({
    onSuccess: (codeResponse) => {
      functionToSendToServer(codeResponse.code);
    },
    flow: "auth-code",
    ux_mode: "popup",
});

// attach the login function to the button
export const LoginPage = () => {
  return (
    <LoginButton onClick={loginWithGoogle}>Login with Google</LoginButton>
  )
}
```

## 3. Backend code

Use the client generated "code" to retrieve id_token. Then use id_token to get the user profile data (email, picture, etc). 

```javascript
import { OAuth2Client } from "google-auth-library";

const oAuth2Client = new OAuth2Client(
  process.env.GAPI_CLIENT_ID,
  process.env.GAPI_CLIENT_SECRET,
  "postmessage"
);

// use the "code" to get user info from Google
async function getUserInfo(code) {
  const { tokens } = await oAuth2Client.getToken(code);

  const ticket = await oAuth2Client.verifyIdToken({
      idToken: tokens.id_token,
      audience: process.env.GAPI_CLIENT_ID
  });
  
  const payload = ticket.getPayload();

  return {
      email: payload.email,
      googleId: payload.sub,
      picture: payload.picture,
      name: payload.name,
  };
}

```