teleren/devto huggingface dataset:
Code Smell 95 - Premature Classification
Tags: oop, programming, webdev, tutorial
Published: 2021-10-16 15:11:52

*We are over generalizers. We shouldn't create abstractions until we see enough concretions.*

> TL;DR: Don't guess what the future will bring you.

# Context

Aristotelian Classification is a big problem in computer science. 
We tend to classify and name things **before** gathering enough knowledge and context.

# Problems

- Futurology

- Bad designs

# Solutions

1. Wait for concretions

2. Refactor late

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/e6ca123df9f10f291a92e863bf168cc0)
```java
class Rectangle 
 { 
       int length; 
       int breadth; 
       
       int area() 
       {
         return length * breadth;
       } 
 } 
//We are creating a premature abstraction 
//And misusing is-a relation since a Square "is a" Rectangle

class Square extends Rectangle
 { 
       int length;  
       
       int area() 
       {  
         return length * length; 
       } 
 } 
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/d3232090ebc0c1360c85dd1079aebe14)
```java
class Rectangle 
 { 
       int length; 
       int breadth; 
       
       int area() 
       {
         return length * breadth;
       } 
 }  

class Square 
{ 
       int length;  
       
       int area() 
       {  
         return length * length; 
       } 
 } 
//Square might-be a Rectangle
//But it does not follow behaves-like relation so we won't go ahead
//and create a strong relation between them
//Maybe they are shapes. We don't have enough examples and protocol yet
//We will not guess until further knowledge

```

# Detection

An abstract class with just one subclass is an indicator of premature classification

# Tags

- Bad Design 

- Classification

# Conclusion

When working with classes, we name abstractions as soon as they *appear*. 

Our rule is to choose [good names](https://dev.to/mcsee/what-exactly-is-a-name-part-i-the-quest-61k) after the behaviour.

We should not name our abstractions until we name our concrete subclasses.

# Relations

{% post https://dev.to/mcsee/code-smell-11-subclassification-for-code-reuse-1136 %}

# More Info

- [What is in a name](https://dev.to/mcsee/what-exactly-is-a-name-part-i-the-quest-61k)

# Credits

Photo by <a href="https://unsplash.com/@fcornish">Faye Cornish</a> on <a href="https://unsplash.com/s/photos/tree">Unsplash</a>
  
* * *

> Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

_Donald E. Knuth_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
2 in a Row ! Hacktoberfest 2021
Tags: hacktoberfest
Published: 2021-10-16 14:38:54

It was a good learning in the month of October by contributing to open source every year. I successfully completed Hacktoberfest 2020 & 2021. Cheers to all other contributors, maintainers, sponsers, organizers of #hacktoberfest. Let the festive ends with joy!
Design for your developers, not just your users
Tags: design, startup, ux, productivity
Published: 2021-10-16 14:15:35

As a developer, I have worked on many feature definitions, tickets, and mockups. Working on both freelance projects and at companies, I have come across unclear requirements more times than I can count. Though it's impossible to be perfect, there are ways to improve developer productivity and establish a better foundation for how your apps are built.

### It starts by designing for your developers.

Though users are typically the primary stakeholders, recognize that developers are the bridge between concept and execution. Developers are limited by similar factors; time and budget being two of the most common. However, some limitations are entirely within a designer's control.

For example, designs that are overly complex or ambitious can be a nightmare for developers. Even if the design looks eye-catching (think most [Dribbble](https://dribbble.com) shots), it might simply be too difficult to implement or even use. Similarly, developers can perform higher quality work at a much faster rate if there doesn't need to be a constant feedback-support loop. A developer shouldn't have to constantly ask what should be displayed in some input case (think failure/success handling), or why two elements are inconsistent in design despite supposedly being the same.

Here are some basic but common examples of design states that are often forgotten:

- Null/empty values
- New values (reassigning from null)
- In progress, loading, or pending states
- Error, success, etc. Should these be messages? Other visual cues?
- Consistency in implementation, such as text size and color, padding, grid spacing

While developers should be responsible for making reasonable assumptions and maintaining autonomy, their job is to produce a fluid, functional application from what's provided. If given something difficult to work with, there's no guarantee that the actual app will be any better.

Confusion breeds chaos and makes it tough for many devs – especially those who have little interest or background in design – to accomplish their work in the expected amount of time. For an application to be well-executed, all three points need to interact and consider each other's needs: designers, developers, and users.

As a designer, you’re probably dealing with different sets of requirements, communication across different departments, and responsible for designing flows. You may be constrained by deadlines or financial limitations, and so it’s tough. But keep developers in mind, and they’ll return the favor through a beautifully executed user experience.

---

In exploring this idea, I found that Invision's *Inside Design* [published an article](https://www.invisionapp.com/inside-design/design-for-development/) that covered a similar idea. It's more in-depth and put together than this article, and I highly suggest you read it if this idea interests you.

You can find more of my content [here](https://romansorin.com/blog).
Manual de sobrevivência: Hacktoberfest 2021
Tags: beginners, braziliandevs, hacktoberfest
Published: 2021-10-16 14:03:09

Essa é sua primeira vez no **Hacktoberfest**? Não tema! Temos aqui recursos pra você não perder esse evento mundial!

---

## Afinal, o que é Hacktoberfest? 🤔

O Hacktoberfest é um evento que acontece no mundo todo durante o mês de outubro já faz alguns anos. O **objetivo** dele é incentivar a contribuir no *Open Source*.

Open Source são projetos de código aberto, ou seja, projetos que qualquer pessoa pode contribuir para melhorá-lo.

---

## Primeiro, se inscreva! ✍🏽

No site da dona [DigitalOcean](https://hacktoberfest.digitalocean.com), você deve se inscrever para participar.

👉🏽 [[PDF] Como se inscrever para o Hacktoberfest 2021](https://drive.google.com/file/d/1-sF8xavvTx72CTxlFCspdBwHz6pNd5hZ/view?usp=sharing)

---

## Comece a contribuir! 🤩

Para participar do evento, você deve criar **Pull Requests** no site [Github](https://github.com/).

O pull request (ou PR) é a forma de você contribuir e ganhar pontos no evento.

Importante: São válidos para o evento os PRs para repositórios com a tag **#hacktoberfest**.

👉🏽 [[PDF] Tutorial: Meu primeiro Pull Request para o Hacktoberfest](https://drive.google.com/file/d/1c7c-w0lDUdjI5Eg11fO-rGP4WVJA8-sN/view?usp=sharing)

---

## Não sei onde contribuir 😿

A parte de procurar um repositório para ajudar é realmente a mais chatinha, mas também trouxemos uma coisinha para ajudar!

👉🏽 [[PDF] 10 dicas para achar repositórios e contribuir no Hacktoberfest](https://drive.google.com/file/d/1SNgqsYc4qFSgTeI6zjHiCcDdV9ilvKIg/view?usp=sharing)

---

## Dúvidas frequentes 🤓

**1. Preciso saber programar para participar?**

Não! Você pode ajudar sem programar uma única linha de código.

**2. É muito difícil ganhar a camiseta? 👕**

Também não! Se seguir os PDF's acima direitinho, sua camiseta e stickers do evento poderão ser enviados pela dona DigitalOcean. 

Às vezes, encontrar um repositório legal para contribuir pode levar um tempo, mas mesmo assim vale a pena. Já encontrei e ajudei em diversos repositórios legais, é bem gratificante!

**3. E as regras do evento?**

Penso que a mais importante é: não faça spam ou conteúdo inapropriado, se não você poderá ser **desclassificado**!

Para resolver isso, basta realmente ajudar um projeto, e não participar apenas para ganhar a camiseta.

Leia as [regras e mais informações aqui](https://hacktoberfest.digitalocean.com/faq).
How to simplify and organize imports in Typescript
Tags: typescript, javascript, webdev
Published: 2021-10-16 13:53:19

 

Sometimes we have a long  list of imports, with files that come from the same place, it makes our code noisy and a bit longer, something like: 

```
import { BeersService } from './services/beers.service';
import { WhiskyService } from './services/whiski.service';
import { WineService } from './services/wine.service';
```

We can simplify it by exposing all files, from a single file, to point to all of them.

Create drinks.ts into the service directory and export all services.

```typescript
export * from './beers.service';
export * from './whiski.service';
export * from './wine.service';
```
Now we can update our files, to the new path.

```typescript 
import { BeersService, WhiskyService, WineService } from './services/drinks';
```

> Thanks @lissetteibnz , If rename the filename from drinks.ts to index.ts, Javascript understand the file index like the entrypoint for the directory, so  it works only using the directory name.

```typescript
import { BeersService, WhiskyService, WineService } from './services';
```

The code looks clean and easy to ready because all of them comes from the same place.

Photo by <a href="https://unsplash.com/@marcinjozwiak?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Marcin Jozwiak</a> on <a href="https://unsplash.com/s/photos/imports?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Strong Connectivity in Graphs
Tags: algorithms, graphs, directedgraphs
Published: 2021-10-16 13:38:03

Strong Connectivity is a thing we use only in directed graphs. Definition of Directed Graphs HERE

Def
Nodes a and b in a graph are mutually reachable if there is both a path from a to b and also a path from b to a. If all the nodes in the graph are mutually reachable in directed graph it is strongly connected .

Lemma. Let s be any node in graph G, Graph G is strongly connected if and only if (iff) s is reachable from every other node and every node is reachable from s.

Read more at https://hecodesit.com/strong-connectivity-in-graphs/
Asp.net core Handle Errors; Dosyaya Errors Loglamak Giriş.
Tags: dotnet, csharp
Published: 2021-10-16 13:33:46

İlk başta aşağıdaki yazımdaki adımları teker teker uygulayalım : 

https://dev.to/mustafasamedyeyin/asp-net-core-logging-serilog-giris-200d

Daha sonra HomeController'ının Index action'ını aşağıdaki gibi değiştirelim : 

```
public IActionResult Index()
        {
            throw new Exception(Environment.NewLine + Environment.NewLine + Environment.NewLine + "Bu öylesine fırlatılmış hata;");
            return View();
        }

```

Daha sonra Error action'ınnı içini aşağıdaki gibi değiştirelim : 

```
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {

            var exHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
            var exception = exHandlerFeature.Error;
            Log.Error(exception,"Bir hata oluştu."); 

            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

```

Uygulamayı çalıştırdığınızda belirttiğiniz yolda aşağıdaki dosyalar ve loglar oluşacaktır : 

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

Aşağıdaki linkteki her şeyi yaptıysanız seq'de de loglarını görebilirsiniz.

https://dev.to/mustafasamedyeyin/asp-net-core-logging-serilog-giris-200d

Bir dahaki yazımda görüşmek dileğiyle.

En iyi dileklerim ile.

Mustafa Samed Yeyin.
Read Data From Firebase Firestore (V9)
Tags: javascript, react, firebase, beginners
Published: 2021-10-16 13:25:31

For reading data from firestore database we will need some starter files so clone this repo https://github.com/abhisheks-12/Blog-dev-to

1) Go to https://firebase.google.com/ then click on Go to console.

2) Now create project with name parking system and after that turn off google  analytics.

3) After that click on </> icon which represents web app.

4) Register app with any name , then copy firebase configuration and if you don't have firebase install firebase first.


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



5) After that go to your editor open src/Firebase/config.js 
and paste configuration here

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

6) Again go to firebase click on firestore database.

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


7) Click on start collection and create your data base like this 
picture
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f540jgyhgsz37r8tu034.png)

8) Now come back to your text editor open src/App.js.

9)Import following statements
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/va2qfy8bvysir2ta1pgs.png)

10) Now we will fetch data from firestore so we will use async function so first see this code
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/be0n1x6mp9ezi1xz8ohp.png)

11) Here we are using getData function to fetch data ,now we will save data in parkingData first console log parkingData after logging we will find doc value in this value there will be objects of our  data.

12) In setCars we are setting data in array using map method . All properties will come in different objects so we are destructuring 
this properties into one object with unique id .

15) Now we have data and now we are going to loop over that data 
using map and access every property and set it in our html .

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

16) Here is final code https://github.com/abhisheks-12/Blog-dev-to/tree/final/src
Hacktoberfest 2021 - Join the Festivities!
Tags: hacktoberfest, contributorswanted, memgraph, github
Published: 2021-10-16 12:31:09


The annual **[Hacktoberfest](https://hacktoberfest.digitalocean.com/)** is
underway! We may be a bit late in joining the festivities because of our
**[Memgraph 2.0 launch](https://memgraph.com/blog/memgraph-2-0-release)**, but
we are very much committed to furthering the open-source spirit and contributing
to such noteworthy efforts.

For those who are not familiar with the concept, the basic idea is:

1. Register on the [Hacktoberfest
   website](https://hacktoberfest.digitalocean.com/).
2. **Open 4 pull requests** during October 2021 in repositories with the tag
   `hacktoberfest`.
3. If successful and the PRs are merged, you can choose between **planting a
   tree** or **receiving some swag**!

What's more, you can also **fix any bugs** or provide **better implementations
for certain features**! Feel free to inform the community by filling an issue
and start hacking! If you're new to contributing code, you can always ask for
help on our [Discord server](https://discord.gg/memgraph).

[Memgraph](https://github.com/memgraph) has repositories with different
programming languages and technology stacks, so find what works for you and
start coding there:

- **[MAGE](https://github.com/memgraph/mage)** - an open-source graph algorithm
  library with algorithms written in **C**/**C++**/**Python**/**Rust**.
- **[Memgraph](https://github.com/memgraph/memgraph)** - the Memgraph core
  repository for **C**/**C++** wizards.
- **[GQLAlchemy](https://github.com/memgraph/gqlalchemy)** - a library developed
  to assist in writing and running queries on Memgraph written in **Python**.

If you want to contribute to any other of our repositories, just follow the same
principle and open an issue. We will handle the rest.

## What can you do to participate?

1. Read the **Contribution Guidelines** in the selected repo.
2. **Open an issue** (for big ideas you may want the community to know) or
   **comment on the Hacktoberfest 2021 issue** for your new implementations,
   fixes, or functionalities.
3. **Start hacking!**
4. **Open a pull request** for your contribution.
5. **Wait until your pull requests get reviewed or merged!** In the meantime,
   you can review someone else's pull requests too.

## Last remarks

- Join our [Discord server](https://discord.gg/memgraph) to get started. It's
  definitely easier with the help of the Memgraph engineering team or other
  community members.
- As part of the event, we would like to invite everyone to adhere to
  [Hacktoberfest's
  values](https://hacktoberfest.digitalocean.com/resources#values) and our [Code
  of Conduct](https://github.com/memgraph/mage/blob/main/CODE_OF_CONDUCT.md).
- Please observe Hacktoberfest's rules, terms, and FAQ. If a pull request is
  marked `invalid` or `spam` it would not be counted, and the person may be
  disqualified from the event.
- Hacktoberfest 2021 is an event presented by _DigitalOcean_, _Intel_,
  _appwrite_, and _deepsource_.
return vs print inside function
Tags: python
Published: 2021-10-16 12:26:56

reference 
https://realpython.com/python-return-statement/
```python
def print_greeting():
    print("Hello, World")


print_greeting()
# outuput : Hello, World


def return_greeting():
    return "Hello, World"

return_greeting()
# output : 

print(return_greeting)
# output :  <function return_greeting at 0x000001C1F88C6950>

print(return_greeting())
# output : Hello, World
```
A Nice Developer Joke For Today
Tags: jokes, dailydeveloperjokes, watercooler
Published: 2021-10-16 12:00:20

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

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

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

---

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

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

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

<!--
Joke text:
___Q:___ What did the Network Administrator say when they caught a nasty virus?

___A:___ It hurts when IP
 -->
Text To Speech | gTTs Python Module
Tags: python, gtts, texttospeech
Published: 2021-10-16 11:47:59

Now a days TextToSpeech feature are used in various applications as android apps website and many more.
python has couple of module which help us to integrate in our application with minimum instruction and easy to use.

Python module for Text to Speech :

## pyttsx3 2.90

pyttsx3 is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline, and is compatible with both Python 2 and 3.

type below command in terminal to install pyttsx3.
`pip install pyttsx3`

pyttsx3 python module has it own advantage as it work offline but it's output voice a bit not like human it's like robotic.  

for more information [pyttsx3 Document](https://pypi.org/project/pyttsx3/)


where as we have also alternative python module from Google.
That's called **gTTs**.

## gTTS 2.2.3
gTTS (Google Text-to-Speech), a Python library and CLI tool to interface with Google Translate's text-to-speech API. Write spoken mp3 data to a file, a file-like object (bytestring) for further audio manipulation, or stdout. Or simply pre-generate Google Translate TTS request URLs to feed to an external program.

type below command in terminal to install gTTs
`pip install gTTS`

for more information [gTTs Document](https://pypi.org/project/gTTS/)

Let's try couple of examples...

Text to speech in English language | gTTs

![Text to speech in English language | gTTs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n936bxg07ab02c9b7rf8.png)
 
Text to speech in Hindi language |gTTs

![Text to speech in Hindi language |gTTs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zb29ui5mhrr19tld5okb.png)


                            
                                Thank You!
find gcd with recursion
Tags: python
Published: 2021-10-16 10:50:51

```python
def gcd(a,b):
    assert int(a) == a and int(b) == b, 'the number must be integer only ! '
    if a < 0 :
        a = -1 * a
    if b < 0 :
        b = -1 * b
    if b == 0 :
        return a 
    else :
        return gcd(b, a%b)

print(gcd(48, 12))                   
```
recursion sum of array
Tags: python
Published: 2021-10-16 10:39:08

```python 
arr = [90,2,3,4,5,6,7,8,9,101]
n = len(arr)
i = 0
Num = 0
def recursor(n,i,Num):
    if n == 0:
        return n
    else:
        #print(arr[i])
        Num = arr[i] + Num
        print(Num)
        i += 1
        return recursor(n-1,i,Num)

(recursor(n,i,Num))

```
Mocking scala method calls containing type parameters with context bounds
Tags: scala, testing
Published: 2021-10-16 10:33:03

In our example we will be looking at a very simple auditing mechanism. Every time a resource changes we want to store its previous and its new state as json.

While investigating the code base we come across a trait like this:

```scala
trait AuditLogHandler {
    def addAuditLog[A: Writes](previous: A, next: A)
            (implicit session: Session): Unit
}
```
We find out that `Writes` is needed to create the json form of the object, and we notice that Session takes care of actually storing the values in the database.

After creating a class which utilizes an instance of the trait above we start to write tests. We decide to use mocking.

Our first attempt to mock the `addAuditLog` method will most likely look like this:

```scala
(auditLogHandler.addAuditLog(_: A,_: A)(_: Session))
    .expects(*, *, *).anyNumberOfTimes().returning(())
```
which will result in the error message:

```
Unspecified value parameters: session: Session
```

We scratch our heads in disbelief. How can it be unspecified if it is right there?! We think that our IDE got confused, which happens from time to time. So we decide to recompile it with sbt which gives us the same error.

After spending some time looking up the issue without results we analyze our dependencies. Their versions seem to be quite behind. Full of hope we update `scalatest` and other related dependencies just to see the same outcome.

Still:
```
Unspecified value parameters: session: Session
```

Hopefully we eventually remember that `A: Writes` is just syntactic sugar for an implicit parameter of type `Writes[A]`.

So:
```scala
def addAuditLog[A: Writes](previous: A, next: A)
        (implicit session: Session): Unit
```

is actually:
```scala
def addAuditLog[A](previous: A, next: A)
        (implicit writes: Writes[A], session: Session): Unit
```
After trying it out it proves to be the solution:

```scala
(auditLogHandler.addAuditLog(_: A, _: A)
    (_: Writes[Assembly], _: Session))
    .expects(*, *, *).anyNumberOfTimes().returning(())
```

Looking at the solution we can't help but feel a bit irritated that it took us that much to figure out, while still being happy that we actually got it to work in the end.