teleren/devto huggingface dataset:
Make a TIC-TAC-TOE by using NextJs, React and Redux with Typescript
Tags: nextjs, react, redux
Published: 2022-04-09 06:38:33

---
title: Make a TIC-TAC-TOE by using NextJs, React and Redux with Typescript
published: true
description: Simple tic-tac-toe game build on top of nextjs
tags: nextjs, react, redux

---
![Tic Tac Toe](https://github.com/phonist/tictactoe/blob/main/public/assets/gameboard.png?raw=true)
Demo link: https://tictactoe-hu2mk80qr-phonist.vercel.app/
GitHub repo: https://github.com/phonist/tictactoe

<!-- ABOUT THE PROJECT -->
## About The Project

This is a straightforward Tic Tac Toe game.
The game is build using NextJs on top of React with Typescript.
Then there's redux, redux-thunk, and material-UI.

### Build With
* [React](https://reactjs.org/)
* [NextJs](https://nextjs.org/docs/basic-features/typescript)
* [Typescript](https://www.typescriptlang.org/)
* [Redux](https://redux.js.org/)
* [Redux-thunk](https://github.com/reduxjs/redux-thunk)
* [Material-UI](https://mui.com/)


<!-- GETTING STARTED -->
## Getting Started
The project are mainly categorize into three parts (UI, redux logic and typescript interface):
```
pages
|-- index.tsx
|-- _app.tsx
|-- Board.tsx
|-- Game.tsx
|-- Square.tsx
redux
|-- reducers
|-- actions
|-- thunks
|-- types
      |-- interfaces
|-- reducers.ts
|-- store.ts
```
* All UI components are kept in the `pages` folder..
* All redux logic are kept inside `redux` folder.
* All typescript interfaces are kept inside `types` and `types/interfaces` folder.


### Prerequisites
* Node - 16.2.0
* Yarn - 1.22.17


### Installation
1. git clone https://github.com/phonist/tictactoe.git
2. cd tictactoe
3. yarn dev
4. navigate to localhost:3000 and start your development
DTDL Parser extensions
Tags: azure, iot
Published: 2022-04-09 06:37:58

---
title: DTDL Parser extensions
published: true
description:
canonical_url: https://blog.rido.dev/tools/2022/03/31/dtdl-parser-extensions/
tags: #azure #iot #mqtt
---


The DTDL dotnet parser provides and object model to inspect DTDL elements: Telemetry, Properties, Commands, Components and Relationships.

All of these are represented as `DTEntityInfo` elements that must be used with the appropriate `DT*` types using casting.

To make it easier the navigation through those types, and by using some C# goodness, I've created this DTDL parser C# extensions:

{% embed https://gist.github.com/rido-min/3364aa967ffc66ec503511bc6f01dcfd %}

That can be used as

```cs
var model = await new ModelParser().ParseAsync(ReadFile("dtmi/samples/aninterface-1.json"));

Console.WriteLine(model.Id);

foreach (var t in model.Telemetries)
{
    Console.WriteLine($" [T] {t.Name} {t.Schema.Id}");
}

foreach (var p in model.Properties)
{
    Console.WriteLine($" [P] {p.Name} {p.Schema.Id}");
}

foreach (var c in model.Commands)
{
    Console.WriteLine($" [C] {c.Name} {c.Request.Id} {c.Response.Id}");
}
```
Jest partial snapshot matching
Tags: testing
Published: 2022-04-09 04:46:55

Now that we first looked at [snapshot testing](https://daily-dev-tips.com/posts/react-snapshot-testing-with-jest/), you might already have come across some weird use-cases.

For instance, what if your data returns a date object?
Or are your IDs dynamic and ever-changing?

This means only a part of our snapshot should match.

## Jest partial snapshot matching

Let's take the following test, for instance.

```js
test('snapshot testing', async () => {
  const randomFact = {
    id: Math.random().toString(36).slice(2),
    fact: 'Chris is writing about Jest',
    createdAt: new Date(),
  };

  expect(randomFact).toMatchSnapshot();
});
```

If we run this code, our snapshot will be generated nicely, and the test will succeed.

```js
exports[`snapshot testing 1`] = `
Object {
  "createdAt": 2022-03-30T04:36:39.987Z,
  "fact": "Chris is writing about Jest",
  "id": "eq8b6a67yjb",
}
`;
```

However, what do you think will happen on the next run?
Correct, it will fail on both the `createdAt` and the `id` since those will be different.

![Failing snapshot](https://cdn.hashnode.com/res/hashnode/image/upload/v1648615075808/KTo7vlfMZ.png)

To fix this, we have to make sure Jest knows that the `createdAt` can be any date, and the ID can be any string type.

Luckily for us, it comes with this function, inside the `toMatchSnapshot` function you can define what objects should be made of like this:

```js
test('snapshot testing', async () => {
  const randomFact = {
    id: Math.random().toString(36).slice(2),
    fact: 'Chris is writing about Jest',
    createdAt: new Date(),
  };

  expect(randomFact).toMatchSnapshot({
    id: expect.any(String),
    createdAt: expect.any(Date),
  });
});
```

Note how we didn't add the `fact`. This means this will still check uniquely for each snapshot.

Now make sure to run your next test while passing the update flag.

```bash
npm run test -u
```

And after the update, your snapshot should look like this:

```js
exports[`snapshot testing 1`] = `
Object {
  "createdAt": Any<Date>,
  "fact": "Chris is writing about Jest",
  "id": Any<String>,
}
`;
```

Perfect!
We now have a unique date check on the `createdAt` field and a string check for the `id`.

### 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)
Stop Raising ValidationError on create() on Serializers
Tags: django, python, validation
Published: 2022-04-09 06:00:02

When working with Django and also learning it, I've used to read but also write similar code.

```python
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["username", "password", "email"]

    def create(self, validated_data):
        username = validated_data.get("username")

        if username:
            try:
                User.objects.get(username=username)
                raise ValidationError({"user": "This user already exists."})
            except ObjectDoesNotExist:
                pass
        return User.objects.create(**validated_data)
```

What is actually wrong with the code? 
Well, we are raising ValidationError on the `create()` method instead of doing the work of data validation in the `validate()` or the `validate_field()` methods. 🥶

### What are the implications?🤔

First of all, we are violating DRF rules and writing bad code. The fact that there is literally a function we can surcharge to make this task and it's not used is a pretty bad pattern. 

And secondly, performance issues. The validation of the data comes actually before the creation, updating, and deletion of data. 
Writing data validation on the `validate()` or the `validate_field()` methods can make CRUD methods much faster.🚀


*Article posted using [bloggu.io](https://bloggu.io). Try it for free.*
Developers Suggest !!
Tags: beginners, webdev, programming, discuss
Published: 2022-04-09 05:44:52

I am a Mechanical Engineering graduate who have been working in the same field for the past 3 years. I was not self satisfied with mechanical field job. So I thought of changing my career to developing field which I have got passion and interest to work in. Please suggest me that whether my decision is good or not, and also will I get job in web developing field if I seek skills in developing field without a CS degree or relevant experience !!??
Use Github Copilot Labs to transalte code in other languages
Tags: github, computerscience, vscode, githubcopilot
Published: 2022-04-09 05:06:27

![Copilot Labs](https://github.gallerycdn.vsassets.io/extensions/github/copilot-labs/0.0.103/1649094244328/Microsoft.VisualStudio.Services.Icons.Default)


# Code Translations in [`VSCode`](https://vscode.dev)

    What is Code Translations?
    Making a environment where solutions matter's and not just the language.


### How [`GitHub Copilot Labs`](https://next.github.com/projects/copilot-labs/) helps you to translate your code to other languages?
<!-- how github helps with copilot labs -->
>Github Copilot Labs is a platform that helps you to translate your code to other languages, start with installing the extension and then you can start translating your code.

# Start with installing the [`Copilot Labs`](https://marketplace.visualstudio.com/items?itemName=GitHub.copilot-labs)
    


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

    1. Install the extension
    2. Go to your folder and open the file you want to translate, and then click on the extension icon.

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

    3. Here you will find two buttons Explain and Translate, you can use them to explain your code and translate it to other languages.
    4. Click on Explain to minimize it.
    5. Click on Translate to start translating your code.


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

    6. Highlight the code you want to translate and click on the ASK COPILOT.

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

# Yeap, it works🤯!

Share the translation with your friends and colleagues.
<!-- add my social media profiles -->

Connect with me on:
### Twitter: [`@Abhayprajapati_`](https://twitter.com/Abhayprajapati_)
### Github: [`@theAbhayprajapati`](https://github.com/theabhayprajapati)

## Check out API that I have builded.
###[`Open Source Apple Store API`](oas.vercel.app)
Windows para desenvolvimento
Published: 2022-04-09 05:06:07

O Windows não é o meu ambiente preferido para desenvolvimento, mas em alguns casos é necessário utilizar o Windows, então resolvi criar um script para me auxiliar na criação deste ambiente.

## Chocolatey
Uma das coisas que mais me incomoda na utilização do Windows é a instalação de programas, um gerenciador de pacotes é muito interessante para remediar esse problema, o Chocolatey é o escolhido por ser o mais flexível e completo.
Executar o comando a seguir em um terminal administrador para instalar:

```bash
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
```

O passo a passo para a instalação está disponível em:
- https://chocolatey.org/install#individual

## gsudo
No Linux existe o sudo, uma aplicação que eleva os direitos para execução de um comando específico, o gsudo acrescenta essa funcionalidade ao Windows, permitindo executar comandos isoladamente com permissão de administrador, isso é importante para o Chocolatey, que necessita de elevação de direitos para instalar a maioria dos programas.
Em um terminal administrador, executar:

```bash
choco install gsudo -y
```
Agora basta adicionar o comando `sudo` antes de qualquer comando no terminal para elevar o comando seguinte.

## PowerShell
Existem alguns emuladores de terminal alternativos para Windows, mas o terminal padrão permite algumas customizações que julgo adequadas para meu uso. É importante manter o PowerShell atualizado para ter os últimos recursos das ferramentas.
```bash
sudo choco install powershell-core -y
```

## Windows terminal
O windows terminal é um utilitário emulador de terminal que centraliza diferentes terminais instalados e permite algumas configurações de estilização de forma centralizada.
```bash
sudo choco install microsoft-windows-terminal -y
```

## Oh-My-Posh
No Linux eu costumo utilizar o Zsh com o Oh-My-Zsh, e o Powershell tem um paralelo que permite algumas personalizações do terminal parecida com disponível para Zsh.

```bash
sudo choco install oh-my-posh -y
```

Acessar a pasta de temas, um dos disponíveis é o ys:

```bash
cd ~\AppData\Local\Programs\oh-my-posh\themes\

oh-my-posh --init --shell pwsh --config ys.omp.json | Invoke-Expression
```

Editar o arquivo $PROFILE e adicionar o inicializador do oh-my-posh:

```bash
oh-my-posh --init --shell pwsh --config ~\AppData\Local\Programs\oh-my-posh\themes\ys.omp.json | Invoke-Expression
```

## Docker-cli
O Docker será importante para gerar ambiente para desenvolvimento.
```bash
sudo choco install docker-cli -y
```

## VS Code
Para desenvolver é necessário ter uma IDE ou um editor de texto, porque não um editor de texto que se mete a ser IDE.
```bash
sudo choco install vscode -y
```

## Git
```bash
sudo choco install git -y
```
Fitting goals into a job, not in it
Published: 2022-04-09 05:01:07


> *Programming into a language, not in it.*
> 

I came across this concept in Code Complete 2 and it resonates deeply with me. A language is just a mean towards a goal (e.g. communication). Regardless it is a human language to connect human, or programming language to instruct computers. Without knowing what the end purpose is, we can hardly assign any meaning to the process. 

In the meantime, same as any other tools in life, it comes with constraints and limitations. If we simply programming “in” the language, we are guaranteed to be bound by the limitations of the language and stuck at the implementation details. In order not to lose sight, we should always stay close to the problem we’re aiming to solve. After all, if the problem isn’t worth solving, why are we bother spending time on it at all. 

The same idea applies to job as well. Lots of jobs are filled with mundane tasks and not designed for intellectual growth. When I first enter the workplace, I have no idea about what a job is. I told myself that as long as I am willing to grow, the rest will follow. However, that is simply not true. Later I realized that I set the expectation too high on a job. There might be some job full of excitement and challenges, but that’s not for ordinary people. Dream job, if there is any, doesn’t come easy.

If we can’t control what we are asked to do in a job, what else can we do? Complaining about the system is broken? Fuck no, this is the least useful thing to do in life. Finding another job? It still feels like gambling though. Until recently, inspired by above quote, another option pops into my mind. It is simply taking a step back and thinking *very* hard about our goals first, then fitting the goal into the job. They don’t need to align perfectly, in fact, most of time they don’t. But the priority is clear. I got to admit that this is easy to say than done due to all the ambiguities to deal with when setting goals, but it’s a necessary step to redefine what a job actually means in our life.
Git Worktree
Tags: git, webdev, programming, beginners
Published: 2022-04-09 04:41:55

I am not sure why I had no idea about this gem. I have been using Git for almost 10 year and discovered this just few days back and from that time it has become an essential part of my workflow.

**Scenario**: Deep down working on a feature branch for an app, suddenly a big issue was found in production for which you have to find a solution and deploy hotfix

Here was my workflow:
### Workflow 1

- Commit all my work in my feature branch, even when I know it's not even half done and obviously will not compile.
- Checkout master -> create hotfix branch --> make changes and deploy
- Checkout my feature branch, undo last commit, and start working again.

### Workflow 2

- Stash changes to feature branch. Most of the time I will forget to stash untracked files, so stash again with a message "this also needs to be unstashed-- "
- Checkout master -> create hotfix branch --> make changes and deploy
- Checkout feature branch, pop up last stash and second last stash, continue working

The problem with above workflow was, if I move to work on something else, and come back after considerable time, I will not remember where I left, and god forbid If I have more stash changes and my stash message are not even understandable by me after a week.

## How Git Worktree helped me out.

Now whenever I have to work on a feature, I add a new worktree. In case I have to go and work in another branch, I just change worktree folder and start working on that branch. I don't have to commit half or not working code or have to stash them (with appropriate message) anymore. I can just switch folder and start working in a new branch.

### How to add a worktree

 > git worktree add -b "feature/your-branch-name" <path>

Full list of commands for worktree

```txt
git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]] [-b <new-branch>] <path> [<commit-ish>]
git worktree list [-v | --porcelain]
git worktree lock [--reason <string>] <worktree>
git worktree move <worktree> <new-path>
git worktree prune [-n] [-v] [--expire <expire>]
git worktree remove [-f] <worktree>
git worktree repair [<path>…​]
git worktree unlock <worktree>
```
[Read more here](https://git-scm.com/docs/git-worktree)
Let me know how you use worktree.

Thanks
Kumar Nitesh
5 Best Tools for Software Developers
Tags: javascript, programming, webdev, productivity
Published: 2022-04-09 04:30:10

Software developers are tasked with solving a lot of big problems. Whether it is finding the best solution to the problem in question or deciding which technologies they'll use to realize their product, there's no shortage of obstacles that stand between them and success. That's why we've put together this list of 10 tools that every developer should be using in order to make these tasks easier for themselves so that they can focus on what's important - building great products.


## [CodePen](https://codepen.io/)

CodePen is a cloud-based website that allows users to post code and run it in real time through their browsers. It also has tutorials, snippets, and syntax highlighting for different languages. The CodePen community can give feedback on what the code does or how it should work.

## [Polypad](https://polypad.io/)

Polypad is a scriptable textpad that makes transforming and generating text easy. It's also cross-platform and uses javascript for writing scripts.

## [GitHub](https://github.com/)

GitHub is a web-based hosting service for version control, which means it stores different versions of the same file. It offers unlimited public and private repositories and provides tools for managing projects with easy to use interface. It also has a built-in wiki and in-line commenting.

## [Slack](https://slack.com/)

Slack is a team communication app that has come out with many new features and updates. The newest update to the app has enabled users to share files with teammates, including PDFs and other types of documents. Another handy feature is the ability to set reminders for when you need to follow up on emails. Users can also create polls in chat rooms that allow everyone to vote. These features are just the tip of the iceberg when it comes to what Slack offers for teams.


## [Visual Studio Code](https://code.visualstudio.com/)

Visual Studio Code is a free editor for coding. It is a lightweight and fast code editor that can be used with many different programming languages. Unlike other code editors, Visual Studio Code has a clean interface with no toolbars or symbols around the document area. This enables coders to see more of their work at once and makes it easier to find features quicker.


I hope you enjoyed this article and plan to write more in the near future!
How to create Style with typed safe in React JS
Tags: javascript, react, css, typescript
Published: 2022-04-09 04:19:47

That ways very simple using 'CSSProperties'

```
import { CSSProperties } from "react";
```

create style

```
const BannerStyle : CSSProperties = {
        background: `url(/img/product/shop-bg.jpg)`,
        backgroundRepeat:'no-repeat',
        backgroundPosition:'center center',
        backgroundSize:'cover',
        position:'relative'
    }
```
and then use style into html tag

```
<div style={BannerStyle}>
</div>
```
A TTY Can Save Your Bacon
Tags: linux
Published: 2022-04-09 04:05:56

---
canonical_url: https://waylonwalker.com/til/linux-tty/
published: true
tags:
- linux
- linux
- linux
title: A TTY Can Save Your Bacon
---

I recently was unable to boot into my home Linux Desktop, it got stuck at diskcheck `fsck`.  I found that I was able to get in to a tty through a hotkey.

<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Did a sudo apt update &amp;&amp; upgrade last night, power got tripped off couldnt reboot, had to reinstall my display manager from a tty.</p>&mdash; Waylon Walker 🐍 (@_WaylonWalker) <a href="https://twitter.com/_WaylonWalker/status/1512281106120384519?ref_src=twsrc%5Etfw">April 8, 2022</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>


## What's a TTY?

There's probably more to it, but to me its a full screen terminal with zero gui, not even your gui fonts.  It does log into your default shell so if you have a comfy command line setup it will be here for you even though it looks much different without fonts and full colorspace.

## Normal setup

Normally you have 6 TTY's running, the first is dedicated to your desktop manager, which is your login screen it might be something like gdm or lightdm.

* ctrl+alt+F1: login screen
* ctrl+alt+F2: Desktop
* ctrl+alt+F3: TTY 3
* ctrl+alt+F4: TTY 4
* ctrl+alt+F5: TTY 5
* ctrl+alt+F6: TTY 6

In my case the desktop manager neverstarted, so ctrl+alt+F1 brought me into a tty.

## What happened??

Well after getting back in and having some time to reflect, I think my Desktop manager was installed or just broken, possibly during a update I ran a few days prior.

I tried a bunch of things like switching to lightdm, and manually running startx.

## Getting back in

The final commands that ended up getting me back in were installing and starting gdm3.

``` bash
sudo apt install gdm3 sudo systemctl start gdm3
```
Day 555 : The Morning
Tags: hiphop, code, coding, lifelongdev
Published: 2022-04-09 03:12:56

_liner notes_:
- Professional : Not a bad day. Basically just worked on some tickets. Also booked my flight to the UK.

- Personal : Don't remember what I did last night. haha Think I'm still getting over my jetlag.

![View from a lake in Two Jack Lake, AB, Canada with a small island with pine trees and mountains in the distance ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o66a89mvkw5awmwq93qy.png)

Didn't feel well after dinner. Think I ate too much. Went to sleep and that's why the blog post went up late. Going to sleep and work on the radio show in the morning.

Have a great night and weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube bv59JrDIeXI %}