teleren/devto huggingface dataset:
Managing HighScore with Unity's PlayerPrefs
Tags: gamedev
Published: 2020-10-03 14:50:13

In the last couple of days, I added a way to save the high-score in my game using Unity's PlayerPrefs API.

Also, I improved the end screen of the game.

{% youtube WdwEIHLidoI %}

## PlayerPrefs Usage

Using the [PlayerPrefs API](https://docs.unity3d.com/ScriptReference/PlayerPrefs.html) is very simple. Here's my high-score saving logic looks like:

```cs
private bool SaveHighScore(int newScore)
{
    int highScore = PlayerPrefs.GetInt("HighScore", 0);
    bool gotNewHighScore = newScore > highScore;

    if (gotNewHighScore)
    {
        PlayerPrefs.SetInt("HighScore", newScore);
        PlayerPrefs.Save();
    }

    return gotNewHighScore;
}
```
Crispy Forms In Django.
Tags: django, python, codenewbie
Published: 2020-10-03 14:49:16

Crispy forms provide a very neat way of using Bootstrap within our Django templates. For the purpose of this article, we are going to be using bootstrap 4.

The first step is to install crispy form:

```python
pip install django-crispy-forms
```

Next, go to the settings.py and under installed app, add `crispy_forms`

Then at the bottom of the settings.py, add 

```python
CRISPY_TEMPLATE_PACK = 'bootstrap4'

```
Lastly, in order to use it, we simplyload the crispy form tag at the top of our template,

```python
{% load crispy_forms_tags %}
```

and wherever you intend to render your form tag, you use the crispy tag as a template tag using the pipe character '|'

```HTML
{{form | crispy }}
```
SpinnerDialog
Tags: hacktoberfest, android, kotlin, release
Published: 2020-10-03 14:44:05

https://github.com/hamzaahmedkhan/SpinnerDialog

My library Spinner Dialog release v1.2.3 is rolled out.
Please check it out. If you think there is a room for improvement. Do create Feature/Bug request or you can even generate PRs for Milestone v1.3.0

Happy coding!!!
#hacktoberfest #pullrequest #android #opensource #library
Tic tac toe game with vanilla js
Tags: html, javascript, css
Published: 2020-10-03 14:23:33

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9iy4pznenleoe497p6v9.jpg)
Ok, i'll share how to make simple tic tac toe game with vanilla js.

###How its work?
- If player = **x** then player change to **o**
- If clicked time more than equal 9 blocks disabled

###Lets Do it!
**index.html**
```html
<!DOCTYPE html>
<html>
<head>
  <title>Example</title>
</head>
<body>


  <style type="text/css" media="all">
    td {
      width: 100px;
      height: 100px;
      background: black;
      color: white;
      line-height: 100px;
      text-align: center;
      font-size: 3rem;
    }
  </style>
  <button type="submit">Reset</button>
  <table border="0">
    <tr>
      <td id="1"></td>
      <td id="2"></td>
      <td id="3"></td>
    </tr>
    <tr>
      <td id="4"></td>
      <td id="5"></td>
      <td id="6"></td>
    </tr>
    <tr>
      <td id="7"></td>
      <td id="8"></td>
      <td id="9"></td>
    </tr>
  </table>
  <script>

    const blocks = document.querySelector("table");
    const reset = document.querySelector("button");
    
    let selected = [];
    let player = '';


    blocks.addEventListener('click', (e)=> {
      if (selected.length <= 8) {
        let id = e.target.id;
        player == 'O'?output(id, 'X'): output(id, 'O');
        selected.push(id);
      }
    });
    
    reset.addEventListener('click',()=>{
      selected.forEach(x => output(x,''));
      selected = [];
    })

    function output(id, val) {
      player = val;
      document.getElementById(id).innerHTML = val;
    }
  </script>
</body>
</html>
```
WebHook or Reverse API
Tags: python, beginners
Published: 2020-10-03 12:03:43

I do some Development work as a freelancer to keep updated myself with new kinds of work apart from being a Support Engineer.

I came up with work where I was to write a code where data is to be exposed as a JSON. I thought its easy work can be done quickly. But there was a tweak on the work. The code was to send as JSON to **Webhook** not exposed as an API. First time I came up with the word Webhook. I checked for an hour with my teacher GOOGLE. I really liked the concept of Webhook which I like to share with all of you.

WebHook or also said Reverse API is a concept where data in any format is sent to the other application POST method URL. Normally in API, we keep checking with the server for any new data in the API. But in Webhook, the server when to find any changes in data is sent to the client application.

This prevents a lot of traffic onto the server, as the client doesn't have to make requests every time to check for updated data. But API has its own use. 

Now let's understand it through code perspective.
First, let me make a Post Method in FLask Server that accepts a JSON file. This method will accept the code. So this will be webhook URL(http://localhost/webhook)

```python
@app.route("/webhook",methods=['POST'])
def respond():
    print(request.json)
    return Response(status=200)
```
The server end will now send the data to this URL when it's triggered using some condition. When the triggered condition is met the data will be sent to the URL. 

```python

# WebURL which will accept this Json file
webhook_url = "http://localhost/webhook"

# DB connection
cnxn = db_conn()

# SQL Query. Place your own query
df = pd.read_sql_query('''select * from sample''',cnxn)

# Convert sql result in json format
json_response = df.to_json(orient='records')
print(json)

# Send data to URL
while True:
if triggered: #Any condition as per your design logic
    reponse = requests.post(
    webhook_url,data=json.dumps(json_response),
    headers = {'Content-Type': 'application/json'}
)

# Raise Error if data send not successfull 200 code for successfull
if reponse.status_code != 200:
    print(reponse.status_code)
    raise ValueError("Error")
```
This Youtube link explains more about WebHook which is used in Github. Do watch this.

{% youtube YMBzb_RBDAA %}
Javascript 1o1 - Arrow Functions
Tags: javascript1o1, javascript
Published: 2020-10-03 14:17:22

Arrow functions are a cleaner way of writing functions in Javascript.
There are some differences between normal javaScript functions and arrow functions.

### this 

`this` keyword in arrow functions refers to the scope where it is defined
For example:

```js
const hello = () => console.log(this);
hello();
```
Output:
![arrow-function-output-1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1601472366188/xYrb1WD4p.png)
here this refers to the window object, as it is defined in the `global` scope. 

### Syntax
A typical arrow function syntax looks like this
```js
identifier functionName = (param1, paramN) => { statements; } 
```
A nice example would be
```js
let hello = (name) => { console.log("Hello" + name ) }
```

Although it is the way to write an arrow function. It can be made cleaner and readable. 

Here are some conditions where arrow functions can be made more beautiful.

### Single line Arrow functions

1 .  It does not require parenthesis {}
 
For example, you could write a single arrow function as
```js
let hello = () =>  console.log("Hello" );
```

2 .  It does not require the `return` keyword

For example
```js
let sum = () => a+b;  //returns a+b
```
is equivalent to 
```js
let sum = () => {return a+b;} //returns a+b
```

> If you use parenthesis in a single statement function then you should write the `return` keyword explicitly.

```js
let sum = () => { a+b; }  //returns undefined
```
```js
let sum = () =>  a+b;   //returns a + b
```

### Parameters

1 .  No parameters

 It is mandatory to provide () even in case of no parameters
Example:
```js
let hello= () => console.log("Hello");
```

2 .  Single Parameters
You don't have to write () if there is only a single parameter.
For example
```js
let hello = name => console.log("Hello " + name);
```

This single parameter and statement arrow function looks so beautiful 😍👌

3 .  Multiple Parameters
You have to use () in case if you have more than 1 parameters
For Example
```js
let hello = (name,caste) => console.log(`Hello ${name} ${caste}`);
```

Points to be Noted:
1. `this` inside arrow function refers to the scope where the function is defined

2. Arrow function does not require `{}` if only a single statement.
3. Single statement Arrow function returns its statement if `{ }` is not used. 
4. `return` keyword should be used explicitly for the single statement arrow function to return value if `{ }` is used.
5. Arrow function doesn't require () if only a single parameter.
6. Stay updated with this series  [Javascript 1o1](https://hashnode.com/series/javascript-1o1-ckflxofgw00ugogs19uaueufy) .
Javascript 1o1 - The Script Tag
Tags: javascript1o1, javascript
Published: 2020-10-03 14:12:32

> This article was originally posted on my [hashnode blog](https://binayak.hashnode.dev/the-script-tag)



The  `<script>` tag in the HTML page contains the executable script or the source to the executable script.

We will learn about three attributes in the `<script>` tag with their meaning and execution behavior.


- src 😂
- async
- defer

### Src

```Html
<script src="./script.js"></script>
``` 
The `src` attribute contains the link to the external javascript file. It may be your own written code or maybe any library you want to use. 


### Async
```Html
<script async src="./script.js"></script>
``` 
The presence of `async` attributes tells the browser to execute the code when the page is parsing.
 
For instance, check the example.

`index.html`
```Html
<html>
<head>
	<title>The Script Tag - Javascript 1o1</title>
</head>
<body>

</body>
<script async src="./script.js"></script>
<script>
	console.log("This will be executed first");
</script>
</html>
```

`script.js`

``` Javascript
console.log("This will be executed second")
```

This page will create such output
![output1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1601263601988/CYCjSWESl.png)

Even though the `script.js` is fetched first, it will not start executing. 
The `script.js` will start executing parallelly with the parsing of the fetched HTML.


### Defer
The `defer` attribute shows similar behavior as the `async` attribute. But script tag with `defer` attribute starts executing the script after completion of parsing the page.

`index.html`
```Html
<html>
<head>
	<title>The Script Tag - Javascript 1o1</title>
</head>
<body>

</body>
<script defer src="./script.js"></script>
<script>
	console.log("This will be executed first");
</script>
</html>
```

`script.js`

``` Javascript
console.log("This will be executed second")
```

This page will create such output
![output1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1601263601988/CYCjSWESl.png)


Although `defer` and `async` usage produced similar output. It may produce an error if not used according to its own requirements.

> The external library should never be  used with `defer` attributes as our script may use the API of the external library, it will throw `ReferenceError`


> The `defer` attributes have no effect on inline scripts. and should only be used when the `src` attribute is present.




| Defer  | Async  |   |   |   |
|---|---|---|---|---|
| executes scripts after completion of parsing page |  executes scripts parallel with  parsing page  |   |   |   |
|   |   |   |   |   |

If neither `defer` nor `async` attribute is present. The script will be fetched and executed immediately.
SpookyBot, an open source Discord bot
Tags: hacktoberfest, javascript, opensource, beginners
Published: 2020-10-03 13:35:45

> 🎃 A spooky Discord bot

This project is convenient for people who want to get into open source and contribute to different projects especially during the Hacktoberfest.

*Don't hesitate to ask me for help on my [Discord server](https://discord.gg/nEDcagb), I would help you with great pleasure!*

# What does he do?
For the moment, the bot reacts with emojis according to the words present in the messages.
For example, if you send the following message: "I saw a ghost today", SpookyBot will add the reaction `👻` to the message.

![SpookyBot react to every messages](https://dev-to-uploads.s3.amazonaws.com/i/b49uwv5qqjb7oat62l1b.gif)

### Words list
| Word | Emoji |
| --- | --- |
| ghost | 👻 |
| halloween | 🎃 |
| candy | 🍬 |
| spooky | *a cute custom ghost* |

If you want to add some cute spooky terror on your server, feel free to [invite SpookyBot](https://discord.com/oauth2/authorize?client_id=761568927188123669&scope=bot&permissions=1141124160) on it!

# What can I do?
Almost everything!
Seriously, you can help me translate the robot into different languages or add new words and emojis to the list. Otherwise, you can help me add some cool commands to make the robot more fun to use!

# How to contribute?
Nothing simpler, just follow the contribution guide on the GitHub repository.

{% github start-again/spookyBot%}

*[Original post from my blog](https://lucasalt.fr/blog/spooky-bot-an-open-source-discord-bot/)*
CMS components
Published: 2020-10-03 13:13:46

Most of us have been there, done that. Some might just be starting there. Others might have new ideas on what a CMS these days should be like. With the trend in headless and new available techologies, a lot of stuff is happening.

At the moment I am developing (as a concept for now) a new lean CMS (again), headless. 

Every CMS needs certain functionality. For now I need a decent mediabrowser/upload function. Without wanting to reinvent the wheel, any good existing suggestions?
Hacktoberfest just changed its rules
Tags: hacktoberfest, discuss
Published: 2020-10-03 13:06:23

Dear contributors,
in case you are wondering why your pull-requests show 14 days maturity while the faqs & rules tell you otherwise:

The github repo of hacktoberfest [digitalocean/hacktoberfest](https://github.com/digitalocean/hacktoberfest) gives us more info.

Until (PR-605)[https://github.com/digitalocean/hacktoberfest/pull/605] is approved, many of us might be in teh dark about the rule-change. 
While I do understand that spam is an issue, I personally don't like the fact that rules change during this event. What do you think?
Hash table efficiency example
Tags: csharp, computerscience
Published: 2020-10-03 13:04:12

Hash tables is a data structure that can map keys to values which means that it gives every item in a list has key that is used to extract it later.
Its known that hash tables has better performance than normal list but how its differ? 

I wrote a code to compare the time it gets for a list to extract an item in reletively big data structure as well as in a hash table.

First, we fill the list and the hash table with **5000000** values.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2a9xxwej5jgggya9q7gw.PNG)

Then we pick a reandom value between **4 million** and **5 million** to get the worst case. After that, we calculate the time it takes for the list and the hash table to extract the value. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6nrbgushl6ky2qh4b49a.PNG)


After we execute the code the results are: 

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

As you can see the difference between the time. The hash table in all the tests took **0** ms but the list took between **34** to **42** ms to extract the desired values.

If you want test the code yourself check my [GitHub] (https://github.com/MoeHdaib/HashTime/blob/gh-pages/Code)
Exclude a route from Nest.js AuthGaurd (make any route publicly available)
Published: 2020-10-03 12:40:44

Create a custom class called `AuthGuard` that extends from the `AuthGaurd` class exported by @nestjs/passport. Notice the inclusion of `isPublic` which allows you to add a decorator to routes that you want to be publicly accessible. 

&nbsp;

```ts
// auth.gaurd.ts

import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard as PassportAuthGaurd } from '@nestjs/passport';

@Injectable()
export class AuthGuard extends PassportAuthGaurd('jwt') {
  constructor(private readonly reflector: Reflector) {
    super();
  }

  canActivate(context: ExecutionContext) {
    const isPublic = this.reflector.get<boolean>(
      'isPublic',
      context.getHandler()
    );

    if (isPublic) {
      return true;
    }

    return super.canActivate(context);
  }
}
```

&nbsp;

Use this gaurd as a global gaurd in main.ts or wherever you bootstrap your application. This will lockdown all routes and make them accessible by authenticated users only.

&nbsp;

```ts
// main.ts

const reflector = app.get(Reflector);
app.useGlobalGuards(new AuthGuard(reflector));
```

&nbsp;

Create a decorator called `Public` which will allow you make any route public.

&nbsp;

```ts
// public.decorator.ts

import { SetMetadata } from '@nestjs/common';
export const Public = () => SetMetadata('isPublic', true);
```

&nbsp;

Finally add the `@Public()` decorator to any routes that need to be publicly accessible by unauthenticated users.

&nbsp;

```ts
// auth.controller.ts

@Post('/signup')
@Public()
async signUp(
  @Body(ValidationPipe) signUpDto: SignUpDto
): Promise<{ accessToken: string; user: User }> {
  // code ...
}

@Post('/signin')
@Public()
signIn(
  @Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto
): Promise<{ accessToken: string; user: User }> {
   // code ...
}
```
Four Tips for Writing Better Copy
Tags: writing, webdev
Published: 2020-10-03 12:26:08

# Introduction
Code and copy are very much alike. In the same way that code rarely works first try, text usually has mistakes first time around - I think it's wise to accept that you may have to iterate on it a bit to get it right. Spelling and grammar checkers are a bit like a complier in that they are necessary to flag the equivalent of syntax errors but a human element is necessary to pick up the less obvious errors.

# Motivation
I'm extremely bad at spelling and typing so I'm constantly looking for errors in my own work. Over time, this behavior has leaked, so I'm subconsciously proofreading everything. I find that personal websites, project readmes, and blog posts tend to be particularly full of spelling mistakes, grammar mistakes and sometimes just copy that's hard to understand. I think it's really sad because they're usually really good in other ways, so I wanted to offer some tips that I've found help me.

# Tip 1 - Get a spell checker for your code editor
I write almost everything in my code editor, so I find having a spell checker there makes a big difference to the quality of the text I write. Errors are being flagged as I write, so even if I forget to proofread it properly, or don't have time, at least the spelling mistakes are gone. The best spell checking Visual Studio Code extension I've found is the <a href="https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker">Code Spell Checker from Street Side Software </a> 

# Tip 2 - Run text through a grammar checker
Grammar checkers, at least in the sense of human language grammar, aren't really a thing on the Visual Studio Code extension marketplace and I doubt they are in other extension marketplaces. So, I tend to take longer pieces of text into a word processor for grammar checking. This acts as a second line of automated checking and will tend to remove a slew of smaller errors a human can easily miss.

# Tip 3 - Reread after a few hours or days away
When I have something important, I try to let it sit for a while and reread it, if I've got time. I find that coming back to a piece after you've had a long break can help to pickup slightly sneakier errors that you and the spelling and grammar checkers missed. This should serve to mop up most of the remaining errors.

# Tip 4 - Get somebody else to read it over 
This one is really good to do if it's a longer piece of text for something really important like a portfolio website or project readme, but may not always be worth the fuss if it isn't. Basically, the idea here is that somebody else who has no idea what the text is supposed to say won't skim over errors subconsciously, and may be able to pick up on errors you missed. This tends to be particularly good for finding text that doesn't flow well or doesn't mean what you thought it meant.

I hope you've found this useful. Feel free to comment below with any criticisms or comments. My first attempt at writing this sort of content, so please be forgiving :)
Tributo a Terry Pratchett
Tags: codepen, freecodecamp
Published: 2020-10-03 11:22:17

---
title: Tributo a Terry Pratchett
published: true
tags: Codepen, FreeCodeCamp
---

<p>This project is made to #FreeCodeCamp for make my first responsive Web site, where the idea is make a tribute. In this time I decide to make a tribute to one of my favorites writers: Terry Pratchett. <br>
<br>
Let me know If you want  I translate this webside. My motherlanguage is spanish so I learn in english and write my content on spanish. Thanks for all!

Have a code day! :)
</p>

{% codepen https://codepen.io/leandroygz/pen/VwaomPW %}
WSL vs Linux with a desktop environment
Tags: discuss, wsl, linux, windows
Published: 2020-10-03 12:19:09

What is better, if not don't need some specific softwares (like MS Office or Power BI) that often?

Like, how customizable is Windows' desktop environment? What about Git Bash? (I don't even know yet about zsh on Windows. Also, is PowerShell productive? And how lock-in?)

What about WINE vs real Windows?

Also, what about Chocolatey vs Ubuntu apt in WSL2?

Actually, I am on an old MacBook hardware, but I am trying to avoid macOS like a plaque. (Because of update requirements not as backward-compat and light-on-hardware as Linux.)
Scrollbar-in-web-browser issue on Linux
Tags: linux, help, gnome
Published: 2020-10-03 12:14:18

I am on Ubuntu MATE environment, using a Chromium-based browser (Brave), actually.

Although it frequently occurs, even on [dev.to/new](https://dev.to/new), I cannot seem to reproduce and capture a screenshot for now.

Like this,

![Quora scrollbar](https://dev-to-uploads.s3.amazonaws.com/i/mrd4almyyzmesmqr5pzt.png)
Write API tests for HTTP POST method
Tags: testing, javascript, beginners, tutorial
Published: 2020-10-03 12:04:06

Let's take a look at how to write API tests using JavaScript for HTTP POST methods.

So when working with the POST method, one of the key things to remember is to send the request data along with the request. Let's take a look at an example of creating a new user using the POST method - 

```javascript
it('POST /users', () => {
   // data to send with the request
    const data = {
      email: `test-${Math.floor(Math.random() * 9999)}@mail.ca`,
      name: 'Test name',
      gender: 'Male',
      status: 'Inactive',
    };

    return request
      .post('users') // hitting the POST route
      .set('Authorization', `Bearer ${TOKEN}`) // setting token for authentication
      .send(data)
      .then((res) => {
        // validate the entire response data using Chai assertion
        expect(res.body.data).to.deep.include(data);
      });
  });

```
So the above code will create a new user for us and will give a similar response back - 
```javascript
{
  code: 201,
  meta: null,
  data: {
    id: 1437,
    name: 'Test name',
    email: 'test-6243@mail.ca',
    gender: 'Male',
    status: 'Inactive',
    created_at: '2020-09-27T04:15:02.057+05:30',
    updated_at: '2020-09-27T04:15:02.057+05:30'
  }
}

```
There you go, that's all we need to do to create an API test for HTTP POST method. 🙌

#### Check out this video to see a detailed explanation on how to work with HTTP POST method:

{% youtube CuTLcnSna2E%}

You can also clone the [GitHub repo](https://github.com/automationbro/JavaScript-API-Automation-Tests) to access this code

***

#### To learn more about API testing, check out my free tutorial series here - 
https://www.youtube.com/watch?v=ZSVw3TyZur4&list=PL6AdzyjjD5HDR2kNRU2dA1C8ydXRAaaBV&ab_channel=AutomationBro
***

I hope this post helped you out, let me know in the comments below! 

Happy testing! 😄 

...

Subscribe to my [YouTube](https://www.youtube.com/channel/UCjugV5pnY6WjvTGYm7U1ucg?sub_confirmation=1) channel
Support my work - https://www.buymeacoffee.com/automationbro
Follow [@automationbro](https://twitter.com/automationbro) on Twitter