teleren/devto huggingface dataset:
Design folder change monitor in C++ (Windows)
Tags: cpp, tutorial, design
Published: 2022-05-03 16:10:03

## What's a hot folder?
**Hot folder** is like any other folder. Makes it **hot** is when a program (which we gonna code in C++) monitors the change. 

## Who uses it?
Software input can be file. File's source could be hardware like camera generating images or third-party software. Module watches a folder for change, to consume the input. 

## How to design?
Let's think! About what all we need:

> We may heard about observer design pattern. Observers will get notified when a Subject updates. Observer design pattern fits well for this situation. 

- Watcher - Object responsible to receive events from OS about folder changes. Say watching the folder. Watcher is Subject, because Watcher behaves like subject, which gets update, and will notify the observers.

- Update Listener - Object hold the list of changes received from Subject. Update Listener is Observer. Module listens to subject and adds the upcoming changes to thread safe collection. This is needed, why? Because assume a scenario where producer producing the N files per second, but when you don't have any listener like module then you may miss the events while processing the previous. 

- Handler - Object instantiate receiver and listener object respectively. 


## Let's start!


First we define our two basic interfaces 'ISubject' and 'IObject'

```
template <typename T>
class ISubject
{
    public:
        ISubject()          = default;
        virtual ~ISubject() = default;
        virtual AddObserver(const IObserver<T>* pObserver) = 0;
        virtual RemoveObserver(const IObserver<T>* pObserver) = 0;
        virtual NotifyObservers(const T& data) = 0;
};
```

```
template <typename T>
class IObserver
{
    public:
        IObserver()          = default;
        virtual ~IObserver() = default;
        virtual Uptdate(const T& data) = 0;
};
```

```
class DirectoryWatcher : public ISubject
{
    protected:
        std::string _strDirectory;
        HANDLE      _pChangeHandle;
        
        bool IsHandleValid();
        void Reset(const std::string& strDirectory);
    
    public: 
        DirectoryWatcher();
        ~DirectoryWatcher();
        
        bool Start(const std::string& strDirectory);
        void Stop();
        void AddObserver(const IObserver<std::string>* pObserver);
        void RemoveObserver(const IObserver<std::string>* pObserver);
        void NotifyObservers(const T& data);
};

```
```
class UpdateListener : public IObserver
{
    protected:
        code_machina::BlockingCollection<std::string> _changeCollection;

    public: 
        UpdateListener();
        ~UpdateListener();
        
        bool Start(const std::string& strDirectory);
        void Stop();
        void AddObserver(const IObserver<std::string>* pObserver);
        void RemoveObserver(const IObserver<std::string>* pObserver);
        void NotifyObservers(const T& data);
};

```


Please comment for more info!
Day-79 Training At Ryaz
Tags: javascript, webdev, beginners, programming
Published: 2022-05-03 16:05:31

- Date:3/05/2022
- Day:Tuesday

Today, I started at about 10:45 am as I was in progress to complete the java script course so, today I started with rest over part firstly I started with Channing promises as  we have a sequence of asynchronous tasks to be performed one after another  for instance, loading scripts. How can we code it well? Promises provide a couple of recipes to do that. Sometimes, you have multiple asynchronous tasks that you want to execute in sequence. In addition, you need to pass the result of the previous step to the next one. after this I started with handling rejected promises The Promise.reject() method returns a Promise object that is rejected with a given reason.When we invoke a function that returns a promise, we chain the then() method of the promise to run a function when the promise resolves. after this I switched towards my project and did some necessary changes with it and I a left over with little changes to make this project working.so, this way my dad ended up and I got to learn many new things.
Top 7 Featured DEV Posts from the Past Week
Tags: top7
Published: 2022-05-03 15:58:17

 ---
title: Top 7 Featured DEV Posts from the Past Week
published: true
description: A round up of the most-read and most-loved contributions from the community this past week
tags: icymi 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sfwcvweirpf2qka2lg2b.png
---

_Every Tuesday we round up the previous week's top posts based on traffic, engagement, and a hint of editorial curation. The typical week starts on Monday and ends on Sunday, but don't worry, we take into account posts that are published later in the week._ 

## The Battle to Master CSS!

As a beginner developer, learning CSS can be quite the challenge. Here’s how @justtanwa learned to make CSS art by dueling other creators online!

{% embed https://dev.to/justtanwa/how-i-got-better-with-css-fe7 %}

## Why Should I Use Angular?

In this post, @chadwinjdeysel goes over the basics of Angular and covers some of their favorite features “to, hopefully, entice you over to the dark side”.

{% embed https://dev.to/chadwinjdeysel/how-angular-works-and-why-you-should-be-using-it-1b93 %}

## The 5 Golden Rules of Code Review

Code reviews are key to the development process. They are a great tool for teaching and mentoring new recruits as well. @stephsema covers the 5 golden rules of code reviews and how you can use them to improve your process. 

{% embed https://dev.to/stephsema/the-5-golden-rules-of-code-reviews-5bg0 %}

## Common Interview Questions for Front-End Devs

The hiring process is unpredictable and that can be a source of dread for job applicants. @melguachun shares some of the most common questions asked to front-end developers looking for a junior position. 

{% embed https://dev.to/melguachun/common-frontend-interview-questions-ive-been-asked-7dk %}

## Analyzing Trends on DEV

Looking for some data-backed guidance to help you create the next viral article on DEV? Look no further, @hunghvu has you covered with this excellent post!

{% embed https://dev.to/hunghvu/forem-analytics-visualize-the-trends-on-devto-502p %}

## Don't Remove Focus

@colabottles has been seeing a lot of focus indicators being removed from sites with no forethought on the impact it will have on accessibility. We need to stop doing this because it is harmful and here’s why.

{% embed https://dev.to/colabottles/stop-removing-focus-2o7b %}

## Simple Twitter Screenshot Bot

@dhravya created a selenium script that uses poet.so to take screenshots of a tweet! The project is shockingly simple, but super handy.

{% embed https://dev.to/dhravya/i-made-a-twitter-bot-to-take-beautiful-screenshots-of-a-tweet-3kk5 %}


_That's it for our weekly Top 7 for this Tuesday! Keep an eye on dev.to this week for daily content and discussions...and be sure to keep an eye on this series in the future. You might just be in it!_
Create a random quote generator using HTML, CSS, and Javascript
Tags: html, css, javascript, incoder
Published: 2022-05-03 15:48:12

Hello friends, today in this blog, you will learn how to create a random quote generator using HTML, CSS, and Javascript. In our previous blog, we saw [how to create a random password generator using HTML, CSS, and Javascript](https://incoderweb.blogspot.com/2022/04/random-password-generator.html). Now it's time to create a random quote generator. Earlier, I shared many projects related to [javascript](https://incoderweb.blogspot.com/search/label/Javascript), you can check if you want, and don't forget to check [HTML, CSS, and Javascript projects](https://incoderweb.blogspot.com/search/label/HTML%20CSS%20Javascript%20Mini%20Project).

Random Quote Generator is used to generate random quotes. There is a quote that will be changed randomly, a button, and some icons, as you can see in the image above.

Each time you reload the page or click on the new quote button, then the quote will be changed randomly, You can also convert a quote to speech, and copy the quote. When you click on the share button, a pop-up will open with some icons and you can share the quote on Twitter, Whatsapp, and, mail by clicking the share button.

##You may like these:

- [Responsive Personal Portfolio design](https://incoderweb.blogspot.com/2022/04/responsive-personal-portfolio-design.html)
- [How to Detect User Location](https://incoderweb.blogspot.com/2022/03/how-to-detect-user-location.html)
- [Responsive Image Lightbox Design](https://incoderweb.blogspot.com/2022/04/responsive-image-lightbox-design.html)
- [Text to Speech Converter](https://incoderweb.blogspot.com/2022/04/text-to-speech-converter.html)

When the quote is loaded, the preloader will be shown. The background of the preloader will be blurred. As you can see in the image below.


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

If you are unable to understand or felling difficulty understanding so you can check the source code and preview it as well.

Visit here to check [Source Code](https://incoderweb.blogspot.com/2022/05/create-random-quote-generator.html).
Connect to MySQL Database using JPA And Spring Boot
Published: 2022-05-03 15:41:28

In this article we are going to discuss about ,how to connect to MySQL database using JPA and Spring Boot.

As we know JPA is an ORM extension to ORM tool, used to store data in the form of Objects.

## How To Configure JPA and MySQL in Spring Boot
We need to follow below steps for doing configuration of JPA and MySQL in Spring boot.

1.First , We need to add JPA dependency, Spring Boot web, MySQL driver starter in the **POM.XML** file in the dependencies section.

```
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
```
2. After that, we need to add below listed details in the **application.properties** file for doing configuration.

```
server.port=1200
spring.datasource.username=root
spring.datasource.password=*****
spring.datasource.url=jdbc:mysql://localhost/****
spring.jpa.hibernate.ddl-auto=update
```
3. At last, we need to run the application and our application will be ready to connect to MySQL database.

Thank you
[Conceito] - Sofra com Embasamento Matemático
Published: 2022-05-03 15:32:33

> Conteúdo original [nessa thread do Twitter](https://twitter.com/zanfranceschi/status/1521508748816052226)

---

Ei dev,

Vou te mostrar como sofrer com embasamento na teoria de redes em eventos sociais pro caso de você ser uma pessoa super introvertida assim como eu. É muito mais bonito e sexy sofrer matematicamente.

cc @sseraphini
 
↓

![img](https://pbs.twimg.com/media/FR18JJkVIAA2kv7?format=jpg&name=medium)

---

Geralmente, a gente que é introvertido sofre antecipadamente dependendo da possibilidade de interações entre pessoas no evento. Ou seja, quanto mais pessoas, a ansiedade pré evento cresce aritmeticamente.

A fórmula é:

```I = P x (P - 1) ÷ 2```

(I = Interações e P = pessoas)

![img](https://pbs.twimg.com/media/FR18JdmVUAAHMRF?format=jpg&name=medium)

---

Mas a gente sabe que o nosso sofrimento realizado quase nunca é tão grande quanto o antecipado, né?

O sofrimento realizado é o número real de interações durante o evento. Nesse exemplo, só houve 2 interações de fato.

![img](https://pbs.twimg.com/media/FR18J6WVEAY5ueg?format=png&name=900x900)

---

Sabendo do sofrimento antecipado e sofrimento realizado, você consegue obter uma razão que se chama densidade da rede, que nada mais é do que o realizado ÷ antecipado. No caso, seria 2 ÷ 6 que resulta na dízima periódica 0,333... ou também 33%.

---

Ou seja, nesse exemplo você entendeu que pra calcular seu sofrimento é necessário obter o sofrimento antecipado ─ que é o número possível de interações ─ e do sofrimento realizado ─ que é o número praticado de interações.

---

Faz um exercício de sofrimento agora: calcula o quanto de sofrimento haveria num evento com 200 pessoas e com 345 interações realizadas.

---

Se você chegou até aqui, faz uma oração pra mim, por favor. Semana que vem vou participar dum evento em que não conheço ninguém. E o pior de tudo é que nem sofrer direito antecipadamente eu posso pq não sei quantas pessoas irão. 🥲
A checklist for setting up a cloned rails application locally
Tags: rails, ruby
Published: 2022-05-03 15:30:33

I don't think that I set up cloned rails projects that often, but it now happens often enough that I need a checklist. 
So this is my general checklist after I have cloned the repo

1) Set the correct ruby version. I use [asdf-vm](https://asdf-vm.com/) to manage my ruby and JS version. It can also manage other languages, but these two are my main. I also typically want any changes I make to the ruby version to be local to that project only. Which asdf can do through the command `asdf local language version # => asdf local ruby 2.7.4`

2) `bundle install`. This one is obvious, but I normally run it first and get the error that I'm on the wrong ruby version, so I have to place it as the second step to remind myself.

3) `yarn install`. Most projects I know will use some JS libraries and this will install them all.

4) Assuming bundle install went off without issue, `rails db:setup` is typically my next step. I have postgres installed locally and most of the projects I have met this year all use it. This should initialize the databases that the project will be using for development and testing.

5) `rails db:migrate` I don't know about you, but I keep forgetting to run migrations. So this is a crucial step. Be better than me. Remember to run migrations.

5.1) I have met projects where I was given a DBDump so that I have some test data to work with. So this is the part where you add that data to your DB. on postgres it would be something like `psql YourDB < /path/to/dump/` Alternatively, the project may have seed files defined in which case run `rails db:seed`

6) Now you have the correct libraries, and data in the DB it's time to start the server. Far as I have seen (probably not that far), most major projects use the a Procfile defining the processes that should be running. The Procfile is fed to the [Foreman gem](https://rubygems.org/gems/foreman/versions/0.87.2) to initialize the server with background processes running as well. If that is the case, first thing you then need to do is install the foreman gem `gem install foreman`. Once that is set up you can run `foreman start -f /path/to/Procfile`

If however the project does not use a Procfile, good ol' `rails s` will start the server and you should be good to go.

I may have missed a couple steps, but this is my general process to getting started. What's yours? lmk in the comments.
Paracetamol.js💊| #112: Explica este código JavaScript
Tags: javascript, beginners, spanish, webdev
Published: 2022-05-03 15:02:44

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Avanzado</mark></center>

```js
const f = (arr=[]) => {
  return arr.map((item) => {
    return (item * 2 ?? item + 1)
  })
}

console.log(f())
console.log(f([1,2,3]))
console.log(f([1,2,0]))
```

A. `TypeError`, `[ 2,4,6 ]`, `[ 2,4,0 ]`
B. `[]`, `[ 2,4,6 ]`, `[ 2,4,0 ]`
C. `SyntaxError`, `[ 2,4,0 ]`, `[ 2,4,0 ]`
D. Ninguna de las anteriores. 

Respuesta en el primer comentario.

---
Build a Minimal API with HereDoc and Docker
Tags: docker, dotnet, api, beginners
Published: 2022-05-03 15:00:56

With Docker supporting HereDoc we are now able to create a full minimal API within a docker file, allowing us to use a single file build everything we need.

You can watch the full video on YouTube 
{% embed https://youtu.be/xo4eSOhHRaI %}

``` Dockerfile
# syntax=docker/dockerfile:1.4

# specify base image
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env

# create directory
WORKDIR /app

# Create the csproj file with Here Dock
COPY <<EOF demo.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
    </PropertyGroup>
</Project>
EOF

# restoring the csproj file
RUN dotnet restore

# creating the program.cs for out .net application with heretic
COPY <<EOF Program.cs
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    app.MapGet("/hello", () => "Hi There from docker file");
    app.MapGet("/teamLH", () => "7 times world champion");
    app.Run();
EOF

# publishing our application
RUN dotnet publish -c Release -o out

# preparing the final image
FROM mcr.microsoft.com/dotnet/aspnet:6.0
EXPOSE 80
EXPOSE 443
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT [ "dotnet", "demo.dll" ]
```

Please reach out for any questions or clarifications
Fake data in tests
Tags: ruby, testing, programming
Published: 2022-05-03 14:55:31

Tests are not only a tool to automatically check the code and its correctness, but also an excellent documentation. Every time I don't understand something in the documentation of a library, I look at the specs and quickly find an answer to my question.

In tests it is the best to use data as close to real-life as possible: "User" → "Ivan Pavlov", "ip" → "82.100.200.3", empty file → jpeg with your cat. This way we get good documentation and good examples of how to use our API.

To make the tests consistent, I prefer to use a single domain for the test data. For example, I often use:

1\. Characters and quotes from The Simpsons:
```ruby
user = User.new(name: "Bart Simpson", email: "bart@simpson.dev")

expect(user.to).to eq "Bart Simpson <bart@simpson.dev>"
```

2\. Characters and quotes from '90s action movies:
```ruby
comment: "Dead or alive... you're coming with me"
```

3\. Lyrics of Eminem's or Beyoncé's songs (please don't ask):
```ruby
do_request(text: "In my shoes, just to see what it's like to be me")
```

P. S. Some of you might mention Faker. I don't use it as I think it's an anti-pattern. I'll elaborate on this [in next post](https://dev.to/vasily/using-faker-is-anti-pattern-1jgl).
Made a Photo Gallery web-app for Appwrite Hackathon
Published: 2022-05-03 14:04:59


There is an ongoing [appwrite + DEV hackathon](https://dev.to/devteam/announcing-the-appwrite-hackathon-on-dev-1oc0). And I wanted to take part in it but I had never used appwrite before. I was worried that learning appwrite will take a lot of time, plus I came to know about this hackathon very late so I may not be able to submit anything in this hackathon. But appwrite was really easy to understand and implement. I thought that making a photo gallery will teach me the core concepts of appwrite plus I can submit it to the hackathon.
After reading through the [docs](https://appwrite.io/docs) and 30 Days of Appwrite [blog posts](https://30days.appwrite.io/), I finally finished the site with bare minimum functionality. :D


![Photo Gallery Web-app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vs3k7dfs4o4ksgwjbc2g.png)


Github repo: https://github.com/PlabanKr/photoz
Djangoで既存モデルにForeignKeyなフィールドを追加する場合のMigrationについて
Tags: django
Published: 2022-05-03 14:34:12

Djangoでは割と使い物になるMigration生成機能がありますが、既存モデルにForeignKeyでフィールドを追加する場合、当該フィールドがNOT NULL制約付きなため、Migration時に適当な初期値を渡す必要があります。

具体的にコードで書くと、下記のような変更を行った場面です。(Postモデルのデータをいくつか作成したものの、TagでPostをまとめたくなった、という想定)

既存コード
```
class Post(models.Model):
    text = models.TextField("本文",blank=False)
```

追加後
```
class Tag(models.Model):
    name = models.CharField("名前",max_length=10,blank=True)

class Post(models.Model):
    text = models.TextField("本文",blank=False)
    tag = models.ForeignKey(Tag,on_delete=CASCADE)
```

この場合既存データが存在するため、普通にMigrationでフィールドを追加、というのが難しくなります。
そこでTagモデルのデータを作りつつ、既存のPostについては全て一旦生成したTagに紐づけるようなMigrationを、一回のMigration生成で行う方法を考えてみます。

先程のコードの変更を行ったあとに `manage.py makemigrations` を実行すると、既存データにNOT NULLな列が追加されるからデフォルト値が必要だよ!どうする?みたいなプロンプトが出るので、one-off default値を渡すことにして適当な値を突っ込みます(本来ならここでPythonコードが書けるのでTagモデルのデータを作りつつその値を渡す…ということが出来るのかも知れませんが、私が試した限りでは実現出来ませんでした。)

そうすると下記のようなMigrationコードが生成されます。
```
class Migration(migrations.Migration):

    dependencies = [
        ('application', '0011_auto'),
    ]

    operations = [
        migrations.AddField(
            model_name='post',
            name='tag',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='application.tag'),
            preserve_default=False,
        ),
    ]
```

当然、このまま実行するとあまり良くない結果になるので、migrateコマンドは実行せずmigrationファイルを修正します。

処理の方針としては
1. NOT NULL制約無しで列を追加
2. Tagモデルのデータをとりあえず作り、既存データを紐づけるように更新
3. NOT NULL制約を付ける

という順序でやってます。

migrationsには[RunPython](https://docs.djangoproject.com/en/4.0/ref/migration-operations/#runpython)というMigration中に関数を実行する機能があるのでこれを利用します。因みにこの機能はRollback用関数も定義出来るので中々強力です。

またRunPythonで呼び出す関数については、ドキュメントにある通り引数の apps及びschema_editorを利用してDBへの接続やModelの取得を行います。

これらを踏まえ、前述した処理の通りに、既存のPostを全てTag「日常日記」に紐づけるようなMigrationに修正したものが下記です。

```
def create_tag(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    Tag = apps.get_model("application", "Tag")
    tag = Tag.objects.using(db_alias).create(name="日常日記")
    Post = apps.get_model("application", "Post")
    Post.objects.using(db_alias).update(tag=tag)

class Migration(migrations.Migration):

    dependencies = [
        ('application', '0011_auto'),
    ]

    operations = [
        migrations.AddField(
            model_name='post',
            name='tag',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='application.tag'),
            preserve_default=False,
        ),
        migrations.RunPython(create_tag),
        migrations.AlterField(
            model_name='post',
            name='tag',
            field=models.ForeignKey(null=False, on_delete=django.db.models.deletion.CASCADE, to='application.tag'),
            preserve_default=False,
        ),
    ]
```
これで一つのmigrationで既存データを破壊せずに外部キーを追加する事が出来ました。
ただもっとスマートな方法がある気がしていますので、ご存知の方は是非コメント欄で教えていただけるとありがたいです。
Made With Appwrite - Final Post - Appwrite Hackaton
Tags: appwritehack, javascript, webdev, vue
Published: 2022-05-03 14:30:40

## This is the final post for Made With Appwrite

First you must create your account, after this you are ready to submit your projects.

## Submit Project

The available fields are the following:

- Name, Description, Webpage, Repo, URL, Appwrite (Select the Appwrite services your application uses), License type selector and the promotional image.

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

## Review Published Project

Once your project is approved you can view it on our website. 

You can see the link to your website and the link to your repository.

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

You can also see which Appwrite services each project uses, and clicking on its name will take you to the official Appwrite documentation.

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

## Review your published projects

From the dashboard you can review the projects you have posted and you have the possibility to delete them if you wish.

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

## Admin panel

From the admin panel the manager can review the project submission request and has the possibility to enable, disable or delete them if desired.

![Image admin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9wycbk4vuj6dsuu25rfn.png)


## Enjoy submitting your projects made with Appwrite ! !!! 🙂 🚀


### Project page
{% embed https://madewithappwrite.com %}

### Repository URL
{% embed https://github.com/reyesmfabian/made-with-appwrite %}

## Made from the heart with Appwrite, Happy Coding!


![Image appwrite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8l13ic6h3iubr0s2vcug.png)