teleren/devto huggingface dataset:
🕒Another yet TimeTracker
Tags: productivity, showdev, electron, react
Published: 2021-07-17 21:20:39

Hello, I would like to introduce my app - [TimeTracker](https://github.com/Yadro/time-tracker/releases). This app would be helpful for people who want to know how much time was spent on their tasks. It was written on Electron using TypeScript. 

## Technical part
The app is based on [electron-react-boilerplate](https://github.com/electron-react-boilerplate/electron-react-boilerplate). It uses React for rendering, Mobx for storing the state, and [Ant](https://ant.design/) for CSS. Also, I've attached jss to declare styles.

## App description
You can track time, add notes, view reports of the tracked time, and more.  
Start and stop time, jump between tasks, and add details on how the time was spent.

### 💎Features:
- create projects (choose project color)
- create tasks with subtasks (drag&drop supported)
- track time in tasks
- change start time and end time of tasks
- add details on how time was spent
- receive notifications when task is in progress or when you idle
- switch between profiles

### Screenshots
{% collapsible Press me %}
Tasks:

![tasks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i5wvjqpflxeyte36d8d8.png)

Task description:
![task description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uje50t9c6gjinm99gora.png)

Hours tab:
![hours](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qdikr2nh6n0cfsotw57m.png)

Edit time range description:
![Time range](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fkehxuycef9j6ovkfqkb.png)
{% endcollapsible %}

👉 [Download link](https://github.com/Yadro/time-tracker/releases) (Windows, Linux, Macos)
{% github Yadro/time-tracker no-readme %}
Glad if the app would be helpful 😊
How to useEffect()
Tags: react, tutorial, javascript
Published: 2021-07-17 20:56:04

> What is useEffect and what exactly this hook does?

I'm going to teach you (or at least try) these topics here in this post.

# What is useEffect?

useEffect is a hook from React that receives two parameters. The first one is a **function** and the second one is a **dependency array**.

#What this hook does?

There's a lot of things that you can do with this hook like trigger a function when your component is mounted or when a variable is updated. Look at this example:


```react
useEffect(() => {
//first parameter
}, [/*second parameter*/]);
```

The first parameter is the function that will execute your code and the second parameter is when we want to execute this code. For example, with second parameter you can put all variables that you want and when these variables receives an update, useEffect will trigger the function.

If you want to trigger the function when your component mount, you just need to leave the array empty.

That's it! Now you can do what we want with useEffect. You can even make api requests with fetch.

Thanks for reading. Feel free to comment anything or correct me if I'm wrong.
Let’s say you’ve decided to start a startup in 2021

Tags: startup, productivity, podcast
Published: 2021-07-17 20:52:24

If you have just decided to begin your first startup journey — then you probably know nothing about startups. But no worries, the good thing about startups is that you will learn a lot. 82% of early-stage founders say they have to operate in areas they had almost no experience in before. For example, if you are a [former] Software Engineer (which is very common for early Tech startups), you are going to be involved in the design, marketing, management, sales, and even finance processes.

Read more: https://medium.com/projectium-network/lets-say-you-ve-decided-to-start-a-startup-in-2021-8171ce5af694
How I Deployed my First Machine Learning Model Using Streamlit (Part 2)
Published: 2021-07-17 20:34:48

In this article I will be explaining how to deploy your machine learning model online.

But before then here is the link to the part 1 of this article:
https://dev.to/codinghappinessweb/how-i-deployed-my-first-machine-learning-model-using-streamlit-part-1-31h9

After signing up on streamlit, you will get an invite from the app which would look like this.

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

It takes 1-2days before it could get accepted, the acceptance invite looks like this.

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

After signing in, you create a github repository and name it i.e Loan Prediction. Add the project files to the repository created.

Some of the files you should add to the repository includes:
1. The code for the project
2. The python script for the project
3. The pkl file which is classifier.pkl for this project
4. Requirement.txt file

To get the requirement.txt file just type "pip install pipreqs" on your command prompt, Locate the folder where your python file for the streamlit app is, open a terminal inside that folder and run this command "-pipreqs". It will scan through all the python file there and create a requirement.txt file for you.

Next, Sign into streamlit share: you will create a new app, link your github repository to it and specify the main python file for the app, then you deploy.

Finally your app deployment is ready!!!
You can now share the links to your friends.

# End Notes
Congratulations! We have now successfully completed loan prediction model deployment using Streamlit. The deployment is simple, fast, and most importantly in Python. I encourage you to first try this particular project, play around with the values as input, and check the results. And then, you can try out other machine learning projects as well and perform model deployment using streamlit. 

Lastly, I would love to hear your feedback and suggestions for this article. If you have any questions related to the article, post them in the comments section below. I will actively look forward to answering them.

Link to part 1 of the article:https://dev.to/codinghappinessweb/how-i-deployed-my-first-machine-learning-model-using-streamlit-part-1-31h9

You can view the app via[Streamlit](https://share.streamlit.io/codinghappiness-web/loanprediction/main/loan_prediction.py/)

You can access the dataset[Github](https://github.com/codinghappiness-web/streamlit_app.py/blob/main/train_u6lujuX_CVtuZ9i.csv)

And my jupyter notebook[Github](https://github.com/codinghappiness-web/streamlit_app.py/blob/main/Loan%20Prediction.ipynb)
Ionic for Cross Platform Mobile App Development - Overview
Tags: ionic, mobile, webdev, capacitor
Published: 2021-07-17 19:57:01

## Have you ever wanted to make a mobile app? 


Are you a web developer how wants to try something new, or 
Maybe you are new to coding but don't want to specialize in one operating system or language. 

Either way, Ionic can make the most of common web development skills and bring this goal into reach.

## What is Ionic?


Ionic is an UI toolkit that is open source and cross platform
 compatible.

   When used in combination with capacitor, it is used for mobile application development. 

   With these tools you can develop a progressive web app, an
 iPhone app, and an Android app all with one code base!

## What do you need to know?


   I recommend that you are familiar with HTML5, CSS3, and vanilla JavaScript. 

   Although is is not necessary, React, Angular, and Vue are also able to be used to build an Ionic application.

## Where to start?

Head over to [Ionic](https://ionicframework.com/)

Start by reading through and following their well written documentation.

Ionic is great for anyone but especially web developers who want to try their hand in mobile development. 

Good luck and happy building!
Scrape all images using dom parser php
Tags: php, html
Published: 2021-07-17 19:41:54

Here you scrape all images from [Top Follow](https://topfollow.org) website using HTML Dom parser.

Here is php code and try with it

```php
include("simple_html_dom.php");

$link = "https://topfollow.org";


    $html = file_get_html($link);


    $images_array = array();

    foreach ($html->find('table.infobox vcard td, img') as $element) {
        $allimages = strtok($element->src . '|', '|');
        array_push($images_array, $allimages);
    }
print_r($images_array);
```
Delete Node Modules like a PRO 😎
Tags: javascript, tutorial, node, npm
Published: 2021-07-17 19:39:15

Node modules are famous for being the heaviest object in the universe 😂 and deleting them is no joke. It takes a long of time and we even end up with freezed and unresponsive screens, but not anymore. 

![node-modules joke](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xqpdulrw4vi4ixw5ka0q.png)

There is an npm package that could help us to delete node modules faster and without any hassle.

[npkill](https://www.npmjs.com/package/npkill) comes to the rescue!
![npkill logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o10ebu73j9myoshw2mah.PNG)

You don't need to install npkill , just run npx npkill in your terminal

![npx npkill](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/km2rl5f0u105qjx9g6kf.PNG)

It will then scan for node_modules starting at the path where npkill command is executed and list them.

Move between the listed node modules folders with arrow keys, and press Space to delete it. 

![Select nodemodules and delete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxgsuwz2u60gd00osjph.PNG)

Simple, isn't it?

Hope you liked the post and learned a trick along the way! 😃

✋ Hey! Before you go 🏃‍
If you enjoyed this trick, You can also follow me on

[LinkedIN](https://www.linkedin.com/in/yamansharma27/) | [Dev.to](https://dev.to/yaman27) | [Github](https://github.com/YyamanSharma) | [Twitter](https://twitter.com/YyamanSharma)

Stay tuned for more such tricks ✨
Dreamhost vs Bluehost Comparison: Which one to choose 2021
Published: 2021-07-17 18:49:57

Here in this post, I take a closer look at two of the popular web hosts around; this is my short Dreamhost vs Bluehost web hosting comparison.

There are too many companies out there, each claiming to give you the best deal. For beginners (and even advanced users) having too many choices and little information can confuse you.

One pro tip, if you are an advanced user (eg have more then 100 visits per day or want hosting for a corporate website) then choosing shared hosting is not recommended VPS hosting is the one you should go for.
Yes, both are official WordPress partners and are recommended by them along with Siteground.

DreamHost (review) provides highly optimized WordPress Hosting with expert WordPress support. You can use any plugin or theme of their choice. Also noteworthy is optimized WordPress Configuration and uptime of up to 100%. DreamHost also comes with cloud storage services and with DudaMobile for building mobile websites. Customers also appreciate the unlimited domain hosting and the 97-money-back guarantee.

Bluehost is configured to protect shared hosting users from other potentially abusive users on the same server. Customers and users can install an application using SimpleScripts 1 click installations. Also available are VPS and Dedicated Hosting.

Overall though, Dreamhost came up the winner over Bluehost, with stronger features and better value for money. Both are extremely strong though, hosting millions of websites across the globe, so you'll be in good hands whichever one you choose.
Fix WSL2 Connection Issue to Docker Daemon | Notes
Tags: notes, wsl2
Published: 2021-07-17 19:06:02

---
title: Fix WSL2 Connection Issue to Docker Daemon | Notes
published: true
date: 2021-07-17 18:38:15 UTC
tags: notes,wsl2
canonical_url: https://abhi.page/notes/fix-wsl2-connection-issue-to-docker-daemon/
---

Recently while setting up docker for Hyperledger in WSL2, I got the following error:

```bash
====> hyperledger/fabric-peer:2.3.2
Cannot connect to the Docker daemon at tcp://localhost:2375. Is the docker daemon running?
```

After a quick research, it turns out that if you are upgrading from WSL to WSL2, Windows leaves behind a few legacy settings from WSL that causes this issue.

Here is the fix that worked for me:

### Step 1: Check if you have the same issue [§](https://abhi.page/notes/fix-wsl2-connection-issue-to-docker-daemon/#step-1-check-if-you-have-the-same-issue)

1. In WSL2 terminal, run the command: `docker info | head -15`
2. You should see the following error: `ERROR: Cannot connect to the Docker daemon at tcp://localhost:2375. Is the docker daemon running?`

### Step 2: Check if the fix works for you [§](https://abhi.page/notes/fix-wsl2-connection-issue-to-docker-daemon/#step-2-check-if-the-fix-works-for-you)

1. Run the command: `unset DOCKER_HOST`
2. Follow the previous step again. The error should be gone now.

### Step 3: Make the fix permanent [§](https://abhi.page/notes/fix-wsl2-connection-issue-to-docker-daemon/#step-3-make-the-fix-permanent)

1. Edit the `.bashrc` script with: `vi ~/.bashrc`
2. Search for the line with DOCKER\_HOST and comment it out like this:  
`# export DOCKER_HOST=tcp://localhost:2375`
3. Save the file and reload the terminal settings with `source ~/.bashrc`

* * *

[**Read on abhi.page**](https://abhi.page/notes/fix-wsl2-connection-issue-to-docker-daemon/)
NestJS: Получить текущего пользователя когда не подключён AuthGuard
Tags: node, nest, auth
Published: 2021-07-17 18:01:51

Я хочу, чтобы GET-запрос работал для всех пользователей: авторизованных и анонимных. Но мне бы хотелось, чтобы ответ авторизованному пользователю ещё дополнялся некоей дополнительной информацией. Например, заметку может получить анонимный пользователь, а зарегистрированный пользователь ещё получит информацию о статусе этой заметке: Она в избранном, автор у пользователя в друзьях и т.п.
На момент написания этой заметки у NestJS для этого функционала нет настроек. Но их можно написать самому. Я предлагаю на мой взгляд простое решение. 
Сперва вводная часть: Авторизация у меня проходит при помощи [jwt](https://ru.wikipedia.org/wiki/JSON_Web_Token), поэтому в проекте обязательно должны быть сделаны [рекомендованные шаги](https://docs.nestjs.com/security/authentication#jwt-functionality) *(переписывать их сюда я не стал)*. Вот только AuthGuard *(по ссылке это класс JwtAuthGuard)* должен быть другим. В поставленной задаче нам **не нужно** выбрасывать ошибку, так что если пользователь не авторизован, то вместо его id, email или что там у Вас в токене зашифровано, можно вернуть **null**. 
Вот реализация этого:
**jwt.guard.ts**
```ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

/**
 * Неавторизованные пользователи могут воспользоваться службой.
 * При этом user будет равен null
 */
@Injectable()
export class AllowNullUserGuard extends AuthGuard('jwt') {
  handleRequest(err, user) {
    // Если пользователь на авторизован, то user = null
    return user || null;
  }
}
```

- **JwtAuthGuard** - это обычный guard, который следит за тем, чтобы неавторизованный пользователь не прошёл.
- **AllowNullUserGuard** - это кастомный guard, который не будет выбрасывать ошибку, если пользователь не авторизовался, а будет выдавать null.
Использование его в деле может быть например таким:
```ts
  @Get(':slug')
  @UseGuards(AllowNullUserGuard)
  async getSingleArticle(
    @Param('slug') slug: string,
    @User() currentUser: UserEntity | null,
  ) {
    return currentUser;
  }
```

Здесь используется декоратор **@User** :
```ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

import { ExpressRequest } from '@app/types/expressRequest.interface';

export const User = createParamDecorator((data: any, ctx: ExecutionContext) => {
  const request = ctx.switchToHttp().getRequest<ExpressRequest>();
  if (!request.user) return null;

  if (data) {
    return request.user[data];
  }
  return request.user;
});
```
Get Faster Creating React Project with Vite
Tags: vite, react, createreactapp
Published: 2021-07-17 17:46:52

I am new in react and also still learning how to use react. I'm using create-react-app to make react project. The first thing that I notice whenever I created react project with create-react-app are;
1. The time it took to make a single project .
2. The time it took to start the project.

But all that changed when I got to know ViteJs

### What is ViteJs?

According to vite website, Vite is a French word that means "Fast". So, vite is a build tool that aims to provide a faster and leaner development experience for modern web projects. ViteJs is made by the creator of VueJS.

### Why using Vite?

When starting the project server, a bundler-based build setup has seek to your application and build entire application before it can be served.

Vite improves the time that dev server took by dividing the modules in an application into two categories:
1. Dependencies, Vite pre-bundles dependencies using esbuild. Esbuild is written in Go and pre-bundles dependencies 10-100x faster than JavaScript-based bundlers.

2. Source code often contains non-javascript like JSX, CSS, or React components that used to be edited very often. Vite only needs to transform and serve source code on demand, as the browser requests it. Code behind conditional dynamic imports is only processed if actually used on the current screen.



### Performance between Vite vs create-react-app
To do this testing, I measure the time that both of them took to create and launch react project. And here is the difference between both of them.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l02ylqet3g3t5atqz05b.png)
As you can see the result has significant difference. Either create project or launch project, Vite has a better performance.

### How to create react with Vite

To make react project with Vite is very simple. All you need to do is follow this instruction.

1. `npm init vite@latest`
2. Enter project name and select framework (in this case I use React)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24ah47tekp8r3uxxb8yw.png)
3. Then select react variant (I choose react)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jp1gvj3zha9yrw4qnsz.png)
4. Go to your project app folder and enter `npm install` command. Your project will be ready within a minute.


So that's it what I could share. I'm truly sorry if my English is not good because it isn't my mother tongue. But I keep learning English to make it better. Writing blog also my learning method to improve my English. So if you have any feedback related to the content or to my English, feel free to share!
 
References
[Vite 2.0 Crash Course by codeSTACKr](https://www.youtube.com/watch?v=LQQ3CR2JTX8&ab_channel=codeSTACKr)
[Vitejs and React by Roberto Butti](https://medium.com/swlh/vitejs-and-react-eb3f1afc6e6)
[Getting Started by Vite](https://vitejs.dev/guide/#index-html-and-project-root)
manage the large code
Tags: javascript, react, node, git
Published: 2021-07-17 17:45:47

When we are working on project there are some code which kept on re-using.

So we make a function out of it. let's say we want to convert a number into the currency

```typescript
const numberWithCurrencyAndComma = (number: number): string => {
  return number.toLocaleString('en-IN', {
    currency: 'INR',
    currencyDisplay: 'symbol',
    minimumFractionDigits: 0,
    style: 'currency',
  })
}
```

and generally, with this, we try to keep this function in the lib/utils so we can import and use this function whenever we want

that's how the beauty of the pure function :heart_eyes:

but let's say there is a another project and we want to get the same result then sharing the code would be the better approach as a module which [rushjs](https://rushjs.io/) helps managing the code better

so let's try our hands dirty

```shell
npm install -g @microsoft/rushjs
```

```
mkdir rush
cd rush
rush init
```

This will configure the basic intial setup for our monorepo config

i am using [pnpm](https://pnpm.io/) (verify with this with rush.json) so start setting up different projects

```
mkdir apps
yarn create react-app my-app --template typescript
```

and add this project to rush by adding to the rush.json under projects

```json
{
      "packageName": "my-app",
      "projectFolder": "apps/my-app"
}
```
then under the project root run this commands

```
rush update
```

this will link all the projects to the rush and install all the dependencies

now let's make the sharable code to this project

```
mkdir utils
cd utils
npx tsdx create lib
``` 

this will prompt you to choose 
1. basic
1. react
1. react-with-storybook

let's choose basic this will configure the basic boilerplate.

and add this project to the `rush.json` 

```json
{
      "packageName": "@utils/lib",
      "projectFolder": "utils/lib"
}
```

now try to run this command one more time

```
rush update --purge
```

`Note: if there is an permission issue try to run this command with sudo`

Now it's the time link the package to our own react app 

```
rush add -p @utils/lib
```

now you can import the function

```js
import { numberWithCurrencyAndComma } from "@utils/lib";
```


This how we manage project with single one manager 
let me know down in the comments about your thoughts :smile:

Here is link for the sample repo `https://github.com/palashgdev/rushjs`
Solving sudoku - notes from a tutorial
Tags: python, sudoku, tutorial, beginners
Published: 2021-07-17 17:43:25

I have been working on a little Sudoku solver, mainly in order to familiarise myself with Atom and try to reinforce the testing-first approach.

Nothing fancy, just an implementation of a tutorial by [ComputerPhile](#https://www.youtube.com/watch?v=G_UYXzGuqvM). Testing was made easier by the recursive function returns a value instead of logging the console output. The benefit of this is that it can therefore be incorporated into other code.

At the heart of the software lies a recursive algorithm, that I'm going to talk about to crystallise my thinking:

```
def next_value(puzzle):
    for y in range(0, 9):
        for x in range(0, 9):
            if puzzle[y][x] == 0:
                for n in range(1, 10):
                    if Sudoku.poss(puzzle, x, y, n):
                        puzzle[y][x] = n
                        if Sudoku.next_value(puzzle):
                            return puzzle
                        puzzle[y][x] = 0
                return
    return puzzle
```

What it does: goes through each list in the array and when it hits a zero, it replaces it with the first possible number (checked using the poss function).

Then next_value() calls itself, and so the process continues until it encounters a '0' with no possible solution - it then backtracks - returns through the layers of the function until it reaches a point where more than one value is possible, and proceeds as above with the next possible value.

This is where the code diverges from ComputerPhile's tutorial:

```
if Sudoku.next_value(puzzle):
    return puzzle
```

This passes up the answer from the last run of the recursive function to the allow the final return puzzle to provide us with a solution, rather than 'None'.

The poss function (that checks whether a number is allowed) is simple enough - it checks a input value against the rows and columns according to the rules of Sudoku. The more complicated aspect of these checks are the 3x3 squares. This is dealt with as follows (I take no credit for it - it is taken verbatim from ComputerPhile):

```
x_sq = (x//3)*3
y_sq = (y//3)*3
for a in range(0, 3):
    for b in range(0, 3):
        if puzzle[y_sq+a][x_sq+b] == n:
            return False
```

The // operator is Floor Division. It returns full values, so 3//3 == 1, but 2//3 == 0. This allows squares to be defined - the first three checks will all floor divide to 0, so script can check through all and only the values in the 3x3 square.

At some point it would be good to incorporate an easy way to input puzzles. There are also some tutorials for building a GUI to show the puzzle being solved (albeit much slower that the runtime of the function) - I hope to look into those.

[The code is available here.](#https://github.com/qxcross/sudoku-solver)