teleren/devto huggingface dataset:
Upgrade your React game with TypeScript: Interfaces, types and components
Tags: javascript, typescript, react, webdev
Published: 2020-08-07 00:55:06

Now it's time to put some flavor on our app and create a few components for our app. To do so, we need to understand some TypeScript concepts.

## Types
Types are for letting TS know what kind of data for a specific property should expect.
```
interface CandyBar{
  name: string;
  okToSell: boolean;
  inventory: number;
  categories?: string[];
  howManyinTheFreezer: (bars: number)=> number,
}
```
These are just a few examples of the types. By adding the `?` to a type we make it optional. For functions we have to make sure to specify the type for its parameters and for what it will return.

## Interfaces
An interface is what allows us to create the syntax for a class. Interfaces can be extended dynamically, so we can do something like this:
```
interface Dog{
  name: string,
  age: number,
}
interface Breed extends Dog{
  breed: string,
}
interface Dog{
  isFriendly: boolean,
}
```
Here we're extending Dog's interface with Breed and then we're adding types to it.

Ok, got it :pencil:.

There's one extra thing to add before going hard into our first component, though.

## Prop-types

React has a very useful way to check for types too, `prop-types` and if we mix it with TypeScript, we can make sure to check from compiler to runtime. Isn't it great? 

We can take advantage of it by doing the following:
```
npm i --save-dev @types/prop-types prop-types
```
And making sure in our component we add `import PropTypes from 'prop-types';`

## Creating our first component

Ok, now we're good to go. I decided to go slow and start with a component that won't require a lot since we're just starting: a Navbar.

{% gist https://gist.github.com/misselliev/d53b89858fd47e0b52ba3c14d2ee98ee.js %}

When we do stateless components like this, practically the only change our code has is the `Menubar: React.FC` part right at the very beginning. In that part, we're specifying that Menubar's type as a React Functional Component. The rest of the code is the usual HTML with Tailwind classes.

Now, how about something that requires us to use Props? We're doing a Banner component. The prop is going to be an image we're going to give it since we want to be able to change it up easily.

{% gist https://gist.github.com/misselliev/f83231b7bdd51fd2de9e5a0af129ecca.js %}
Now in `React.FC<Props>` we're letting TypeScript now this component will need props, destructuring we're letting it know it specifically needs bannerImg and an altImg prop.

Now all we need to do it's call it in App.tsx, give it the props we defined and we're good to go.

{% gist https://gist.github.com/misselliev/558cb4652fa688f32f690fa7c60dab0f.js %}

I hope you found this helpful, stay safe and please remember to take a break.

Got something to add? Please feel free to [reach out](https://twitter.com/miss_elliev) for any question, comment, meme or dog photos swap.
❤️ Simple PHP Code Parser
Tags: php
Published: 2020-08-07 00:19:19

---
title: ❤️ Simple PHP Code Parser
published: true
description: Simple PHP Code Parser | a simple data structure from your php code
tags: php
cover_image: https://suckup.de/wp-content/uploads/2012/01/Unbenannt-1-544x510.jpg
---

first published here: https://suckup.de/2020/08/simple-php-code-parser/

It based on code from “[JetBrains/phpstorm-stubs](https://github.com/JetBrains/phpstorm-stubs)” but instead of Php-Reflection we now use nikic/PHP-Parser, BetterReflection, phpDocumentor and PHPStan/phpdoc-parser internally. So, you can get even more information about the code. For example, psalm- / phpstan-phpdoc annotations or inheritdoc from methods.

### Install:

```composer require voku/simple-php-code-parser```

### Link:

[voku/Simple-PHP-Code-Parser](https://github.com/voku/Simple-PHP-Code-Parser)

### More:

- there is also a “.phar” version for e.g. phpdoc checks: [voku/Simple-PHP-Code-Parser/releases](https://github.com/voku/Simple-PHP-Code-Parser/releases)
- and an API documentations helper for your README file, based on the simple php code parser: [voku/Php-Readme-Helper](https://github.com/voku/Php-Readme-Helper)

---

Example: get value from define in “\foo\bar” namespace

```php
$code = '
  <?php
  namespace foo\bar;
  define("FOO_BAR", "Lall");
';

$phpCode = PhpCodeParser::getFromString($code);
$phpConstants = $phpCode->getConstants();

$phpConstants['\foo\bar\FOO_BAR']->value; // 'Lall'
```

---

Example: get information about @property phpdoc from a class

```php
$code = '
  <?php
  /** 
   * @property int[] $foo 
   */
  abstract class Foo { }
';

$phpCode = PhpCodeParser::getFromString($code);
$phpClass = $phpCode->getClass('Foo');

$phpClass->properties['foo']->typeFromPhpDoc); // int
```

---

Example: get classes from a string (or from a class-name or from a file or from a directory)

```php
$code = '
<?php
namespace voku\tests;
class SimpleClass {}
$obja = new class() {};
$objb = new class {};
class AnotherClass {}
';

$phpCode = \voku\SimplePhpParser\Parsers\PhpCodeParser::getFromString($code);
$phpClasses = $phpCode->getClasses();

var_dump($phpClasses['voku\tests\SimpleClass']); // "PHPClass"-object
```
Top 5 DEV Comments from the Past Week
Tags: bestofdev
Published: 2020-08-07 00:16:49

---
title: Top 5 DEV Comments from the Past Week
published: true
description: Highlighting some of the best DEV comments from the past week.
tags: bestofdev
cover_image: https://res.cloudinary.com/practicaldev/image/fetch/s--7VrAA2ln--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://thepracticaldev.s3.amazonaws.com/i/qmb5wkoeywj06pd7p8ku.png
---

This is a weekly roundup of awesome DEV comments that you may have missed.  You are welcome and encouraged to boost posts and comments yourself using the **[#bestofdev](/t/bestofdev)** tag.

@rizvanadnan weighed in on a particularly awesome WiFi network name:

{% devcomment 1353a %}

@rabin016 kept it real in this thread about chairs

{% devcomment 137hd %}

@hiboabd found this post on learning React in 10 weeks helpful. Helpful reminders!

{% devcomment 132gj %}

@amaljoy258 is a coffee purist 😄

{% devcomment 132g8 %}

@ashleemboyer is putting their own needs front and center during the hiring process. Very important!

{% devcomment 135ib %}



See you next week for more great comments ✌
Lessons Learned In Building A Small Project
Tags: php, webdev, codenewbie
Published: 2020-08-07 00:10:58

So I realized that I didn't grasp a lot concepts when learning PHP and programming in general and part of that was not learning to build some projects and little apps that help you grab the basics. I just run towards a big project or something. It took a failed interview for me to realize that I had to go back to the drawing board, a lot of things I figured I needed to learn how to do right. One of them is also blogging, hence I'm writing this article.

I started out by just going through the basics again and this time with PHP where I decided to build a simple calculator after following an exercise and no, I did not do a code along. When using tutorials to learn, it's important that you try to do what you have learnt without the assistance of the instructor and repeat out loud to your self the reason why each piece of code exists. You must be able to explain your code to yourself first before you able to explain it to someone else. 

In this particular pet project, I built a simple calculator in PHP to understand how to use Object Oriented Programming and not just have it as a concept in my head. So even in my sleep, I think I can code it all over again, at least redid the whole thing twice. Initially, I never knew you could write a piece of code to auto load your classes and that was one key thing I learnt today. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3gqop3338ynq2pa82dgv.JPG)

Also understanding the difference between the object properties and the parameters __construct function was quite important as one can tend to confuse both, especially when they have the same naming.

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

All in, it was a good day for me. Dropped a tweet as well on what I achieved for today using the #100DaysOfCode on [Twitter](https://twitter.com/Dante_Frank). It helps to keep you committed. 
{% twitter 1291512522290454529 %}

Hope you enjoyed this article and if it's worth your time and you can check out my code and leave a feedback. Thank you.
{% github DanteFrank/Calculator-OPPP %}
DAY 008 - We Got a New Domain
Tags: css, womenintech, 100daysofcode, webdev
Published: 2020-08-06 23:54:07

Oi gente, tudo bem?

Então hoje é meu oitavo dia do desafio e eu não fiz muitas alterações visuais no meu site.
Eu adicionei mais um ícone e um link ao html, que era justamente o link daqui do dev.to.
E o resto do tempo eu tirei basicamente para estudar CSS, fiz algumas anotações e pretendo começar as "grandes" mudanças no no estilo do site amanhã.
Hoje o dia está bem "normal" comparado com os outros e é bom eu ter isso em mente também. 
Nem só de dias bons e ruins vão consistir o desafio para mim, mas de dias ok também.

Fora isso, lembra que ontem eu falei que já tinha conseguido um novo domínio para o meu site? Então, eu não tentei colocar ontem logo de cara porque eu acreditava que se as pessoas me procurassem pelo endereço antigo do site elas acabariam não me encontrando. Como eu estou participando de alguns processos seletivos  e neles contém meu site ( *sim, nos dias anteriores eu já entrei em processos e já havia alterado meu currículo e posto meu site* ), fiquei realmente preocupada com isso. Ainda assim, hoje eu resolvi tentar alterar o meu domínio, porque eu nunca havia mexido com isso. 
Para a minha feliz surpresa, foi bem fácil, deu um pequeno bug no github, mas nada que me tomou muito tempo para concertar.
Mas e aí? Dá pra achar meu site pelo link antigo? Dá sim! A única coisa que acontece é que a página demora um pouco mais a carregar, mas ela já encaminha para o endereço certo, então não corro o risco de ser "perdida" no meio desses processos seletivos.

Eu pretendo **futuramente** explicar melhor a criação de uma página no github pages e como alterar o domínio, mas como por hora eu só estou estudando, vou deixar isso um pouco mais para frente.

Sei que hoje não foi exatamente empolgante e não trouxe nenhuma mudança drástica, mas fico feliz por estarem acompanhando comigo.

Muito obrigada mesmo, até amanhã! **<3**
Is it good practice to validate on schema mongoose?
Tags: backend
Published: 2020-08-06 23:35:41

---
title: Is it good practice to validate on schema mongoose?
published: true
description: 
tags: backend
//cover_image: https://direct_url_to_image.jpg
---

Hello guys, I'm still new on backend development. I would like to ask what is the good practice for validating data. Should I put the validation on schema or use the validation on expressjs?
TIL - Text-decoration Shorthand!
Tags: todayilearned
Published: 2020-08-06 23:26:05

---
title: TIL - Text-decoration Shorthand!
published: true
date: 
tags: TIL
canonical_url: https://www.lindakat.com/blog/til-text-decoration
---

While I was testing my new dev site on different browsers today, I noticed that some of my links didn't have their text decoration showing. This was odd to me, since text decoration has been a thing for a long time. So I did a little investigating, and learned a bit about the `text-decoration` shorthand.

It combines a few different properties:
- text-decoration-line
- text-decoration-color
- text-decoration-style

And a new property: text-decoration-thickness! However, the thickness property is only supported in Firefox right now - it's part of CSS4, so not officially, fully available yet. So it doesn't work in Chrome or ~~Safari~~ yet. (Actually, thickness is available for Safari right now too - just not as part of the shorthand. It has to be declared separately.) Just happens to be my luck that Firefox is my current browser of choice. :)

So in my code, what I had was
```css
text-decoration: 2px solid underline var(--lightBasic)
```

But the `2px` part is the thickness property, so wasn't showing properly. Removed that, and all three browsers looked the same!That's my interesting tidbit for the day. 😎 Happy coding, friends!
What is Jetpack in Android and why Android developer should have to use Jetpack.
Tags: android, jetpack, androiddevelopers, androidjetpack
Published: 2020-08-06 22:21:51

According to Android officials 

"Jetpack is a suite of libraries to help developers follow best practices, reduce boilerplate code and write code that works consistently across Android versions and devices so that developers can focus on the code they care about. "



Let's Understand what actually it is.

Jetpack: Architecture 

The Architecture zone of Jetpack incorporates eight unique libraries and instruments that help you, modeler, your application and deal with the information utilized by and showed in the application. A large portion of these are existing libraries. In any case, there are three new libraries:  


    Navigation.
    Paging, and.
    WorkManager.



What is Android Jetpack? 

Android Jetpack is an assortment/collection of Android programming components which encourages us in building incredible Android applications. 
The Android Jetpack components bring together the existing Support Library and Architecture Components and arrange them into four categories.
These software components help in:

Following the prescribed procedures and composing the standard code. 

Making complex things basic. 

Prior there were numerous difficulties which are as per the following: 

    Managing activity lifecycles.
    Surviving configuration changes.
    Preventing memory leaks.

Deep dive in Android Jetpack follow the below link.
Android Jetpack:
https://www.javaoneworld.com/2020/08/what-is-android-jetpack.html
Composition Over Inheritance
Published: 2020-08-06 22:10:38

I will go to the journey with you to explain some design principles to help us to organize, clean our codebase and make it more extendable and maintainable. So let's go with important concept which make our code cleaner and reusable.


> What is the composition and when we should use it?

Let me explain and answer this question by example, we all love examples :)

Imagine you have super class called Duck

```
<?php 
class Duck 
{
    public function fly(){}
    public function quack(){}
    public function display(){}
}
```

This class has 3 normally methods and it's good for now and it works well for us until your client request a new type of duck to be added called RubberDuck, here you will notice the problem ? Lets see the problem

```
<?php
class RubberDuck extends Duck
{
    public function fly(){} // Why implement this method ?!
    public function quack(){} // also why too ?!
    public function display(){}
}
```

When you extend from parent Duck class you will inherit a method called fly() and Quack() which are useless to Rubber Duck so what is the solution ? The answer will be to pull out the fly and Quack methods outside Duck class and make a new interface called something like FlyableInterface and QuackablInterface which both have one method for example called fly() at FlyableInterfance and quack at QuackablInterface after that the Duck class can implement these interfaces methods based on its function
so the code will be refactored to

```
<?php
Interface Flyable
{
    public function fly();
}
Interface Quack
{
    public function quack();
}
```

Now the new version of RubberDuck class will implement the new interface method
```
<?php 
class RubberDuck implements FlyableInterface, QuackableInterface 
{
    public function fly(){} // from interface
    public function quack(){} // from interface
    public function display(){}
}
```
and the Duck class has one method which in common for all types called display()
```
<?php
class Duck
{
    public function display(){}
}
```
So here we partially solve the problem but we will notice some problems also after this update but let's discuss that in other articles or write your comments about the problems.
So from the example above we can summarize the meaning of **composition** by saying it's a process to pull out some methods outside the class and create the interfaces to enable the that class implement the suitable interfaces methods not every method from the super class.
I hope that I succeeded in clarifying the idea, even in a simple way.
Thanks for your reading and sorry for my english as it's not my tongue language
You can follow me on [Twitter](https://twitter.com/mgdev92) or [Github](https://github.com/mgamal92)
Can you create a landing page by COPY-PASTE?
Tags: webdev, html, css, startup
Published: 2020-08-06 21:49:30

Hello Everyone, 👋

My friend and I were asking the same question 3 months ago. 

------------------------
As indie hackers, we are sure we need to build dozens of landing pages for our new ideas, products, etc. But, we have noticed that many of us trying to buy ready templates from other marketplaces, However, they are often complex templates that are difficult to modify or perhaps even arrange. From here we got an idea! 💡:

WHY NOT CREATE OUR OWN LIBRARY BUT ALL LANDING PAGE COMPONENTS SEPARATE. 

------------------------
From here we started our project journey and we focused on two essentials gaols:

👉Neat code, easy to customize
👉Separate blocks, easy to integrate

This way, we can build a new landing page every time just by copying the HTML & CSS from our library. 

------------------------
🎉Finally, after 90 days we are extremely excited to announce http://frontendor.com 🙌. A library of reusable and separate HTML blocks to help us or developers to build modern landing pages by COPY-PASTE.

------------------------
🤔 So my question is for you now. Did you create any project small or big, just because you needed something specific?


Thanks for reading this, you are special 😻
Choose the life of Blazor  and WebAssembly
Tags: webassembly, webdev, csharp
Published: 2020-08-06 21:44:19

## The early humble beginning

I started my programming career creating websites using HTML, CSS, and plain JavaScript in 1999-2000. It was very early on I realize that JavaScript with all its power comes with weird quirks which made my life miserable.

## The disillusion

Then I discovered PHP, MySQL, and the entire LAMP stack which moved me to start writing web backend code. Well, PHP was even worse than JavaScript and after a few years of dabbling around with Django, Flask, etc, I quickly gave up on web development for good.

Enter `WebAssembly`, the new natively supported runtime for the web. JavaScript for all its popularity is still a rage-inducing language if you have been used to sane languages or even half-sane ones. 

Blazor a new offering, which is closely tied to ASP.NET Core and the .NET Core ecosystem is based upon WebAssembly seeks to bring C# to the client-side. One might be horrified at the thought of C# on the client-side, but ask yourself
    
`"Is it worse than the entire existence of JavaScript in the first place?"`

{% youtube MetcuX1OHD0 %}

## The good times

With my limited experience of Blazor, I am indeed enjoying this new technology stack. I have written absolutely zero JavaScript and created some really interactive and fun-filled web app with extreme amounts of code sharing between client and server. Thanks to the Visual Studio ecosystem, it was one-click deployment on Azure and in-built authentication to Active Directory or any other login systems.

## But but ASP.NET Core?

How is Blazor different than ASP.NET Core? In the case of ASP.NET Core, you still have to write JavaScript intermixed with Razor template code, whereas in Blazor all your HTML elements are bound to C# objects and you do manipulations using C# which get reflected in the DOM. Using Blazor you don't directly modify the DOM, but you use data and event binding to control the behavior of the elements.


Try out Blazor yourself and you will be pleasantly surprised. It's a bit rough given that is a brand new technology, but I am very confident that it will improvise dramatically over time.

I am going to share more posts with my experiences in the coming weeks.
Day 190: Demonstration
Tags: hiphop, code, coding, lifelongdev
Published: 2020-08-06 21:33:55

_liner notes_:
- Professional : Got up early so I could integrate the OCR feature I worked on into our project for the hackathon. Wasn't too bad, one of the team members used State Machines and React. Just had to look at a couple of files to figure out what was going on and include my part. Got it working. Then it was demonstration time. Got to see what everyone else made. Some really cool projects were created. We demoed ours and the OCR worked, everytime. Awesome!

- Personal : After the demo, I had to take a nap. haha It was exhausting, but fun. Never really did OCR to that level and with live video! I was able to get it working pretty well, at least well enough to read a card and then hit an API to get more data. Don't really remember what I did last night. Probably worked on the hackathon project and my side project.

![A strip of land with a road running down the middle with greenery and water on both sides.](https://dev-to-uploads.s3.amazonaws.com/i/i5vlmhgcepbufe2sm5j9.png)

Ordered some food and juice that arrived today so that's good. Another thing that got delivered was the screen protector for the Google Pixel 4a I ordered. But it went to my folks place, so I'll pick it up later. By the time my phone arrives, I should be in the van. Didn't know they would ship things separately. Having the screen protector doesn't do me any good without the phone. haha. I'm off to my parent's place before it rains too much.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube buUXi4u9okk %}
Building a text-based clock using Swift
Tags: swift
Published: 2020-08-06 21:22:38

If you are looking for a fun project to get into command-line tools development, I think you'll enjoy this article:

https://rderik.com/blog/building-a-text-based-application-using-swift-and-ncurses/

It uses the C `ncurses(3)` library via `SwiftCursesTerm` to create a clock modelled as a 7-segment display.


![text-based clock application](https://dev-to-uploads.s3.amazonaws.com/i/e1vtxootoz5erle9pjsl.png)

I hope you like it.
Um README para o seu user do Github?
Tags: github, git, codenewbie, brasil
Published: 2020-08-06 21:15:18

# Dê um upgrade para o seu perfil =]

Em poucos passos podemos modificar a página do nosso perfil e acrescentar uma cara mais bacaninha como se fosse um "about me". 🖖

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


Bora lá e sem enrolação! 

Passo a passo:

- Qualquer editor de texto (se tiver suporte para tipografia Markdown é bem vindo).
- Um repo com o mesmo nome de seu **USERNAME** do Github.
    - no meu caso, eu já tenho como podem ver na imagem 😛

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

- Esse repo tem de ser **PÚBLICO**.

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

- Na raiz do repo criar o arquivo **README.md** ou na própria página de criação de repo deixar clicado a opção de criar o arquivo junto do repo.

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

- Pronto! Agora basta customizar o README.md como quiser! 🙌

Se quiser pode usar o meu de exemplo [[readme-exemplo](https://bit.ly/30z0OT1)] 👈

**Dica:**

- Caso não apareça o README renderizado no seu perfil, vá no repo e clique no botão "**Share to Profile**"

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8hjxm3n4azewbi4yb4as.png)
My first site/small Blog is online! I appreciate every Dev feedback 🤠
Tags: html, css, javascript, help
Published: 2020-08-06 21:05:40

Hi Community! 👨‍💻

This is my first site; i developed a small blog about my passion: running around the world.
**https://therunnerpost.it**
It's created with Laravel mix, SCSS, jQuery, Chart.js, Handlebars; and is all in Italian (my language).
I appreciate every feedback about it... Mobile view looks more good for me 🙃 ("Mobile first" is my best quote).