teleren/devto huggingface dataset:
JWT Authentication with Apollo
Tags: dohackathon, nextjs, graphql, javascript
Published: 2020-12-22 15:23:51

One of the features for this app is to have an authentication system without using OAuth. This implementation would be slightly new to me as I've never used GraphQL API.

The authentication flow is the same as how one would use in a REST API. 
1. Server (backend) will create the routes or mutations as they call it in GraphQL to perform authentication logic.
2. The client will call the mutations, passing the necessary parameters such as username and password to the server.
3. The server would handle the logic via jsonwebtoken to sign or verify the user and of course encrypt the password to store in the database.
4. After a successful signature, server will return a valid token and client will store it.

I have a few routes that I want to protect and they must be logged in as the app's user to be able to make those requests. This is how I made it work.

```javascript
// pages/api/graphql/index.js
import { ApolloServer } from 'apollo-server-micro';
import { makeExecutableSchema } from 'graphql-tools';
import resolvers from './resolvers';
import typeDefs from './TypeDef';
import jwt from 'jsonwebtoken';

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

let db;

const apolloServer = new ApolloServer({
  schema,
  context: async ({ req, res }) => {
    // AUTHORIZATION
    let loggedUser;

    const token = req.headers.cookie ? req.headers.cookie.split('token=')[1] : '';

    if (token) {
      const user = jwt.verify(token, process.env.JWT_SECRET_KEY);

      if (!user) throw new AuthenticationError('You must be logged in');

      loggedUser = user;
    }

    // DATABASE
    if (!db) {
      // connect to db
    }

    return { db, loggedUser };
  },
});

export const config = {
  api: {
    bodyParser: false,
  },
};

export default apolloServer.createHandler({ path: '/api/graphql' });

```

In the apollo server entry point, I'm making use of the context object to achieve this. There I'm verifying the token via `jsonwebtoken`. If there is a user signed with that token, I'm setting the `loggedUser` as the user that's verified and returning it in the context object. Now I have access to `loggedUser` in the resolvers as well.

```javascript
// pages/api/graphql/resolvers.js

const resolvers = {
Query: {
    posts: async (_parent, _args, { db, loggedUser }, _info) => {
      if (!loggedUser) throw new AuthenticationError('you must be logged in');

      return await db
        .collection('posts')
        .find()
        .toArray();
    },
  }
}
```
I want to protect this `posts` query from not-logged-users so I'm simply putting a check before returning desired response. The client can now handle it however they want with that error :)

So far, this is working rather nicely 😂. I'll continue posting on the development process in the next posts. Happy hacking!
SuperMan Animation With Voice Command
Tags: html, css, javascript, beginners
Published: 2020-12-22 15:27:02

Hello guys today we will learn how to make a SuperMan Voice Command Animation using html css and javaScript, So let’s get started.
First we need to create three files index.html, Style.css and a file for JavaScript code **(Custom.js)** then we need to do code for SuperMan —>

###Step:1###
**Add below code inside index.html**
```html
<!DOCTYPE html>
<html>
<head>
    <title>SuperMan Animation With Voice Command</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
     <link rel="stylesheet" type="text/css" href="superman-scroll.css">
    <link href="https://fonts.googleapis.com/css2?family=Bree+Serif&display=swap" rel="stylesheet">

</head>
<body>
  <h4 style="color: #fff;" id="result"></h4>
<section id="hero-man-section">
  <h1 class="superman-text">Superman</h1>
</section>

<div class='wrapper'>
  <div class='super-man-wrapper'>
    <div class='superman'>
      <img src='images/superman.png'>
      <div class="flame-leg">
      </div>
    </div>
  </div>
  <div class='shadow'></div>
</div>

</body>
</html>
```
###Step:2###
Then we need to add code for **style.css** which code i provide in below text.
<a href="https://blog.stackfindover.com/superman-with-voice-command/" rel="dofollow">Visit for Css!</a>

###Step:3###
Then we need to add code for our JavaScript file **(custom.js)** which code i provide in below screen.
```js
 var result = document.getElementById('result'); 
function startConverting () {
if('webkitSpeechRecognition' in window) {
var speechRecognizer = new webkitSpeechRecognition();
speechRecognizer.continuous = true;
speechRecognizer.interimResults = true;
speechRecognizer.lang = 'en-US';
speechRecognizer.start();
var finalTranscripts = '';
speechRecognizer.onresult = function(event) {
var interimTranscripts = '';
for(var i = event.resultIndex; i < event.results.length; i++){
var transcript = event.results[i][0].transcript;
transcript.replace("\n", "<br>");
if(event.results[i].isFinal) {
finalTranscripts += transcript;
}else{
interimTranscripts += transcript;
}
}
result.innerHTML = finalTranscripts + '<span style="color: #999">' + interimTranscripts + '</span>';
var getresult = jQuery(result).text();
jQuery("#result:contains('clear')").text('');;
if (getresult == "help Superman") {
$(".super-man-wrapper").addClass("active");
$(".flame-leg").addClass("active");
}else {
$(".super-man-wrapper").removeClass("active");
$(".flame-leg").removeClass("active");
}             
}; 
speechRecognizer.onerror = function (event) {
};
}else {
result.innerHTML = 'Your browser is not supported. Please download Google chrome or Update your Google chrome!!';
}   
}
$(window).on('load', function(){ 
startConverting();
});
```
###SuperMan Animation With Voice Command:###
{% youtube eIAEvsc-kKM %}

> For more interesting content

<a href="http://blog.stackfindover.com/" rel="dofollow">Visit for more!</a>
WASM in Create-React-App 4 in 5mn (without ejecting)
Tags: craco, cra4, webassembly, rust
Published: 2020-12-22 15:24:37

---
title: WASM in Create-React-App 4 in 5mn (without ejecting)
published: true
description: Run WASM code in your create-react-app without pain (and without ejecting).
tags: craco, cra4, wasm, rust
---
### First word
In this post, we will write some rust code, compile it to WASM and run it from a CRA4 application without ejecting.

### Rust to WASM FTW
Why Rust? It's cool. There is a lot of hype around it so I decided to give it a go. The [rust book](https://doc.rust-lang.org/book/) and [rust by examples](https://doc.rust-lang.org/stable/rust-by-example/) were pretty useful to get an understanding of the basics.

Once I got my head around the basic concepts, time to look into the conversion to WASM. There is a [lot of nice documentation](https://rustwasm.github.io/docs/book/introduction.html) out there (from the Rust official documentation of course ;)).

The recommendation is to use [wasm-pack](https://rustwasm.github.io/docs/wasm-pack/quickstart.html). That allows you to build and ship an importable WASM module in less than 2mn.

#### Create the project

```
$> wasm-pack new my-wasm-project
$> cd my-wasm-project
```

#### Package and public ([details](https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/packaging-and-publishing.html))
```
$> wasm-pack build --scope nicolasrannou
$> cd pkg
/*make sure the package.json includes the right files. At the time I write this post some .js and .wasm files were missing.*/
$> npm publish --access=public
```

### CRACO
To load the exported module I chose [CRACO](https://github.com/gsoft-inc/craco) because it appears Create-react-app-rewired is not really maintained anymore and doesn't work well with CRA4.

#### Adding dependencies in your CRA4 project
```
$> cd my-cra4-project
$> yarn add @nicolasrannou/my-wasm-project
$> yarn add @craco/craco
$> yarn add wasm-loader
```

Do not forget to update `package.json` by replacing `react-scripts` by `craco`.

#### Setup the config file
```
$> cat craco.config.js

const { addBeforeLoader, loaderByName } = require('@craco/craco');

module.exports = {
  webpack: {
    configure: (webpackConfig) => {
      const wasmExtensionRegExp = /\.wasm$/;
      webpackConfig.resolve.extensions.push('.wasm');

      webpackConfig.module.rules.forEach((rule) => {
        (rule.oneOf || []).forEach((oneOf) => {
          if (oneOf.loader && oneOf.loader.indexOf('file-loader') >= 0) {
            oneOf.exclude.push(wasmExtensionRegExp);
          }
        });
      });

      const wasmLoader = {
        test: /\.wasm$/,
        exclude: /node_modules/,
        loaders: ['wasm-loader'],
      };

      addBeforeLoader(webpackConfig, loaderByName('file-loader'), wasmLoader);

      return webpackConfig;
    },
  },
};
```

#### Import the WASM code
```
$> cat App.tsx
...
  useEffect(async () => {
    const promise = await import("@nicolasrannou/my-wasm-project");

    promise.greet();
  }, []);
...
```

👋 Until next time!
Merry Christmas
Tags: merrychristmas
Published: 2020-12-22 15:16:04

[★˛˚˛*˛°.˛*.˛°˛.*★˚˛*˛°.˛*.˛°˛.*★Merry*★* 。*˛.
˛°_██_*.。*./ ♥ \ .˛* .˛。.˛.*.★* Christmas*★ 。*
˛. (´• ̮•)*.。*/♫.♫\*˛.* ˛_Π_____.♥Everyone ♥ ˛* ˛*
.°( . • . ) ˛°./• ‘♫ ‘ •\.˛*./______/~＼*. ˛*.。˛* ˛.*。
*(…’•’.. ) *˛╬╬╬╬╬˛°.｜田田 ｜門｜╬╬╬╬╬*˚ .˛ …](https://www.truongbui.com/2020/12/merry-christmas.html)
Talking Chess: Adding Offline, Cross-Platform Voice Controls to Chess in .NET Core
Tags: dotnet, csharp, ai, speechrecognition
Published: 2020-12-22 15:10:48

{% youtube bdaowr0j0fU %}
{% medium https://medium.com/picovoice/talking-chess-adding-offline-cross-platform-voice-controls-to-chess-in-net-core-f74712b379c3 %}
Advent of Code 2020 Solution Megathread - Day 22: Crab Combat
Tags: adventofcode, challenge
Published: 2020-12-22 15:10:39

---
title: Advent of Code 2020 Solution Megathread - Day 22: Crab Combat
published: true
description: We're teaching crustaceans to play Combat (a.k.a. War) and simulating the whole thing.
tags: adventofcode, challenge
series: Advent of Code 2020
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/p8sf26wttt33kp2y50gi.png
---

We're getting close.  I can comfortably say that it's Christmas Eve Eve Eve.  Three Eves.  We Three Eves.  Actually, not a bad band name.  Sort of a holiday-themed Destiny's Child vibe.  Anyways, on to the puzzle.

## The Puzzle

In [today’s puzzle](https://adventofcode.com/2020/day/22), we have gotten so bored on our journey that we've inexplicably taught a crab how to play cards.  We're playing Combat (which I've played as War).  Whoever has the highest card each round takes both cards into the bottom of their deck and play proceeds until someone has all the cards.  Good luck!

## The Leaderboards

As always, this is the spot where I’ll plug any leaderboard codes shared from the community.

```
Ryan's Leaderboard: 224198-25048a19
```

If you want to generate your own leaderboard and signal boost it a little bit, send it to me either in a DEV message or in a comment on one of these posts and I'll add it to the list above.

## Yesterday’s Languages

Updated 07:10AM 12/22/2020 PST.

| Language   | Count |
|------------|-------|
| JavaScript |     2 |
| Rust       |     1 |
| Python     |     1 |
| Haskell    |     1 |

Merry Coding!
What is AJAX ?
Tags: beginners
Published: 2020-12-22 14:58:19


Imagine scrolling down on twitter when suddenly the whole page refreshes on you! Imagine this happening every ten seconds just so twitter can show you new tweets. You were probably reading comments or a post that you were very interested in, but now lost your spot because the whole page just refreshed on you. If this happened, you will probably think the website is broken and never want to use it again. To prevent this bad experience, Twitter and Instagram use AJAX. AJAX stands for Asynchronous Javascript and XML. It uses an asynchronous processing model to render dynamic components of a page without having to refresh the entire page. The features that update itself without having to refresh the browser like amount of followers, new tweets, and new post are all results of using AJAX. 


#Working AJAX 
Since you don’t have to load the whole page the data will load faster! This improves the users experience and also allows users to do other things on the page until that section of the page comes back with new data. AJAX gets the browser to request data from the server. Then the server sends back data that is in  HTML , XML or JSON format. You can read more about [AJAX response data formats](https://www.quirksmode.org/blog/archives/2005/12/the_ajax_respon.html) here . Once the browser has successfully received the data it needs, it will fire an event that renders the new data to the page.

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

This AJAX call is enclosed in a jQuery on click event.
There are some settings you must set before making the AJAX call. The first to take a look at is the **url** property. You must have the correct endpoint to get back data from your server. In this, i'm using a joke api to render random jokes to my plain Jane page. The **type** property will take a HTTP verb GET or POST to retrieve data depending on what you need back. GET will retrieve data already saved to the database and POST will update the database with new information retrieved. **Timeout** will do what it says, timeout after five seconds if the server doesn't respond. **BeforeSend** method will display loading if it takes a while to load or an error occurs. Finally if the request come back correctly the **success** function will run which appends my jokes to the web page. If there is a problem with the request, the **error** function will fire off!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/do51v7cqcdrfx0vmqtla.png)
Now when you click the joke button it will request new jokes from the server. 
#Conclusion 
My example was plain but I wanted to show at the simplest level how AJAX is used. This can be a powerful technique due to its asynchronous processing model. You can improve the users experience by having components on the page render without refreshing the page entirely. It also makes your data load faster. Also, using Ajax with Jquery can also make things easier when requesting and appending data back onto the page. Thank you for reading ! Happy coding!
AngularJS to Angular
Tags: angular, typescript, webpack, webdev
Published: 2020-12-22 14:53:38

### Introduction

Recently I tried to upgrade AngularJS application to Angular (v11.0.5). In this post I will describe important steps how AngularJS can be upgraded to Angular.

### Convert `.js` files to `.ts`

If you are using AngularJS with JavaScript, first you need to convert all the files to Typescript by changing the extension to `.ts`. Since TypeScript is just an extension of JavaScript, conversion should be done without any issues.

### Add TypeScript
- Install TypeScript by running `npm i typescript`.
- Create `tsconfig.json` file with following [content](https://raw.githubusercontent.com/slaven3kopic/angularjs2angular/main/tsconfig.json).

### Add Webpack and Webpack Dev Server
- Install Webpack by running `npm i webpack webpack-dev-server -d`.
- Create `webpack.config.js` file with following [content](https://raw.githubusercontent.com/slaven3kopic/angularjs2angular/main/webpack.config.js).
- Webpack plugins used in `webpack.config.js` also need to be installed.

### Load TypeScript
- create `main.ts` with following [content](https://raw.githubusercontent.com/slaven3kopic/angularjs2angular/main/app/main.ts).
- `main.ts` is used as entry file for Webpack.

### Add scripts
- Add scripts to run and build the app in the `package.json` file.
- Scripts can be found in the [package.json](https://raw.githubusercontent.com/slaven3kopic/angularjs2angular/main/package.json).

### Add Angular dependencies
- Install Angular dependencies by running `npm i @angular/animations @angular/common @angular/compiler @angular/compiler-cli @angular/core @angular/forms @angular/platform-browser @angular/platform-browser-dynamic @angular/router @angular/upgrade zone.js rxjs`.

### Bootstrap hybrid app
- Use [UpgradeModule](https://angular.io/api/upgrade/static/UpgradeModule) to bootstrap hybrid app.
- Example of how to bootstrap hybrid app can be found [here](https://github.com/slaven3kopic/angularjs2angular/blob/main/app/main.ts).

### Migrate services
- Migrate services one by one to Angular.
- In transition period use `downgradeInjectable()` to run Angular services inside AngularJS.
- Example of how to migrate a service and use it in AngularJS can be found [here](https://raw.githubusercontent.com/slaven3kopic/angularjs2angular/main/app/core/phone/phone.service.ts).

### Migrate components and modules
- Migrate all components and modules to Angular.
- In transition period use `downgradeComponent()` and `downgradeModule()` to run Angular components and modules in AngularJS.

### Remove AngularJS
- Remove downgrades (`downgradeInjectable()`, `downgradeComponent()`, `downgradeModule()`)
- Remove all AngularJS dependencies.

### Running
- Run app by executing the following command `npm start`.

### Example project
- Example project can be found [here](https://github.com/slaven3kopic/angularjs2angular).

### Disclaimer

Only the steps I personally found important to emphasize are written. Example project is not fully complete.
How To Earn Money As A Student Through Coding / Programming
Tags: computerscience, coding, earn, student
Published: 2020-12-22 14:51:27

####Having the knowledge of coding or programming is a very valuable skill with the help of this we can earn a lot of money. There are tons of ways when it comes to making money with code/program.

<hr>
#### Here I am going to mention few topics from which we can earn money as a programmer. 
<hr>

1) Blogging
2) Content Writers At `GeeksForGeeks` Or Other Sites
3) Game Developer
4) Create Programming Problems For `Hackerearth.com` As Well As for `CodeChef`
5) Instagram Page
6) Freelancing
7) And many more 

<hr>
#####Detailed information about each point is described in the link below.

Visit [cscode.tech](https://cscode.tech/how-to-earn-money-as-a-student-through-coding-programming/).

###For more programming related stuff 
Visit our [Instagram Page](https://instagram.com/computer_science_engineering_)
The how, why, and when of a tech blog
Tags: nextjs, discuss
Published: 2020-12-22 14:37:00

This post was originally made on - [My Tech Blog](https://tech.riju.co/posts/how-when-why)
Most developers handle a wide variety of challenging tasks on a day to day basis, and that includes the meticulous art of being able to _google_ our bugs and find relevant solutions. 
And you have to admit, you have copy-pasted code from a technical blog at some point in time. After all, we do stand on the shoulders of giants.
>TODO - Insert flat earth turtle picture

## Why _another_ tech blog
To put it simply, nothing demonstrates your skill better than being able to impart that skill onto others. As a developer, its an easy way to showcase your abilities on a range of topics to any potential employer. This is especially beneficial because a blog can portray your thinking process and problem-solving abilities in broader ways than a white board interview can for such _untangible_ skills. 
## How to make a distinct tech blog
- **Identify and cater to your audience**
Your audience **isn't** going to be your average leisure reading crowd. It probably is a developer on their second cup of coffee desperately trying to fix something with at least 30 other tabs open simultaneously. 
- **Make an impression**
Clean UI, readable text, lack of _snazzy_ animations. To the point information. All of it matters. You should put in the time and effort to save someone else the same time and effort. 
This matters even more when an employer goes through your blog, and a well designed and maintained one can make your resume shine!
- **Try not to use WordPress**
You probably can, and it's easier, but as a showcase of your technical skills, you can do better. Take this blog, for example, I learned **Next.js** (detailed post coming _soon_ 😉), followed a tutorial and now I can use this blog on my portfolio as well. 
- **Don't repeat yourself (or others)**
There are _plenty_ of technical blogs and stack overflow posts out there. Not everything is worth repeating. Only repeat something already out there if :
	1. A given resource was _hard_ to find. 
	2. It needs updating.
	3. Alternative approaches to established practices. 
## When to blog
Honestly, whenever you want to, or have the time to. It might be a god tip to create a blog post whenever you solve a tricky problem or a persistent headache is resolved. For me, that happens at least once a week, so my goal is to do that as my New Year's resolution (fingers crossed 🤞).

Stay tuned for further updates, and I'll see you in 2021!
Let's try C++20 | using enum
Tags: cpp, programming, todayilearned
Published: 2020-12-22 14:47:37

Proposal [P1099R5](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1099r5.html) by Gašper Ažman and Jonathan Müller adds the possibility to write `using enum my_enum;` so that the names inside the enumeration `my_enum` can be used directly, with being preceded by `my_enum::`.

Let's consider an enumeration like this:

```cpp
enum class EnumWithALongName {
    FirstValue,
    SecondValue,
    YetAnotherValue
};
```

Until C++17, you had to write their fully qualified names to use the enumerators. Sometimes, it would make code quite verbose:

```cpp
void process(EnumWithALongName value) {
    switch(value) {
        case EnumWithALongName:::FirstValue:
            // stuff
        case EnumWithALongName::SecondValue:
            // more stuff
        case EnumWithALongName::YetAnotherValue:
            // OK, I got it, we are dealing with EnumWithALongName...
    }
}
```

Thanks to C++20, we can now write:

```cpp
void process(EnumWithALongName value) {
    switch(value) {
        using enum EnumWithALongName; // this is new \o/
            
        case FirstValue:
            // stuff
        case SecondValue:
            // more stuff
        case YetAnotherValue:
            // code is more readable like this
    }
}
```

It is also possible to bring up only some particular enumerators from an enumeration:

```cpp
int main() {
    using EnumWithALongName::FirstValue, EnumWithALongName::SecondValue;
    auto value = FirstValue;
    return value != SecondValue;
}
```

In my opinion, the last reason to use unscoped enums was the possibility to use them without being preceded by the name of the enumeration. [This reason has now disappeared](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1099r5.html#strong-enums-global-ids) 😀