teleren/devto huggingface dataset:
Sieve of Eratosthenes - Program to find all prime numbers smaller than a given number
Tags: mathematics, programming, cpp
Published: 2022-04-17 12:05:40

---
title: Sieve of Eratosthenes - Program to find all prime numbers smaller than a given number
published: true
description: 
tags: mathematics,programming,cpp
cover_image: https://drive.google.com/uc?export=view&id=1KHCBy81TWmLfBuIotYXyWfXPDE_0RfTQ
---

**Sieve of Eratosthenes** is a very old algorithm to find all the prime numbers up to a given limit. For example, we can find all the prime numbers up to, say 101, using this algorithm in a very efficient manner.

It does so by iteratively marking as composite the multiples of each prime, starting with the first prime number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime, with constant difference between them that is equal to that prime.

Instead of checking every number as prime(brute force approach), we would work on the groups. First, we will create a vector of boolean values where all values are **true**. The rest of the work is going to be on this vector only.

The length of the vector is equal to the limit up to which we find all prime numbers, say **N**. Now, in that vector, assign all the even index starting from 3 as **false** as all even numbers except 2 are non primes.  

Now, for all odd numbers, mark their multiples as **false** as well as they are non prime as well. 

Now mark 0th and 1st index as **false** as well.

All other indexes set to **true** are the prime numbers upto **N**.

```c++
#include <bits/stdc++.h>
using namespace std;

void sieveOfEratosthenes(int n)
{
	// Create a boolean array of length n+1 for all numbers from 0 to n
	bool isPrime[n + 1];
	// Set all the elements to true in the isPrime array
	memset(isPrime, true, sizeof(isPrime));

	for (int p = 2; p * p <= n; p++)
	{
		// If isPrime[p] is true, then it is a prime
		if (isPrime[p] == true)
		{
			// Update all multiples
			// of p greater than or
			// equal to the square of it
			// numbers which are multiple
			// of p and are less than p^2
			// are already been marked.
			for (int i = p * p; i <= n; i += p)
				isPrime[i] = false;
		}
	}
	for (int p = 2; p <= n; p++)
		if (isPrime[p])
			cout << p << " ";
}

// Driver Code
int main()
{
	int n = 30;
	cout << "Prime numbers smaller "
		<< " than or equal to " << n << endl;
	sieveOfEratosthenes(n);
	return 0;
}
```

Time complexity of classic Sieve of Eratosthenes algoeithm is **O(N log (log N))**.  Many variations of this algorithm can also be found with even better time complexities.

Read the original article [here](https://codeunlock.in/posts/how-to-find-all-prime-numbers-smaller-than-a-given-number-sieve-of-eratosthenes)

Read more such articles [here](https://codeunlock.in/)
Vue 3 w/ Composition API + Firebase for production ready app?
Tags: vue, firebase
Published: 2022-04-17 11:58:35

Do you think Vue 3 with Composition API and Firebase for the backend, is a good approach to build a production ready application facing 1000 users?

I am planning a web app where users may interact with a single page while the admin has control to change data and display to the users. It will be a basic functionality, though. 

Opinions and critics are most welcome.
Hibernate - HQL vs SQL
Tags: sql, hql, hibernate, database
Published: 2022-04-17 11:57:02

Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't depends on the table of the database. Instead of table name, we use class name in HQL. Therefore, it is database independent query language.

## Characteristics of HQL

- **Similar to SQL:** HQL's syntax is very similar to standard SQL. If you are familiar with SQL then writing HQL would be pretty easy.

- **Fully object-oriented:** HQL doesn't use real names of table and columns. It uses class and property names instead. HQL can understand inheritance, polymorphism and association.

- **Reduces the size of queries**

## Let's see the difference of the syntax 🍎🍏

In **SELECT** statement:

`SQL
ResultSet rs=st.executeQuery("select * from diet");
HQL
Query query= session.createQuery("from diet");`

In **WHERE** statement

`SQL
ResultSet rs=st.executeQuery("select * from diet where id=301");
HQL
Query query= session.createQuery("from diet where id=301 ");`

In **UPDATE** statement

`SQL
String query = "update User set name=? where id = ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, "diet2");
preparedStmt.setlnt(2, 5);
preparedStmt.executeUpdate();
HQL
Query q = session.createQuery("update User set name=:n where id=:i");
q.setParameter("n", "diet2");
q.setParameter("i",55);
int status = q.executeUpdate();`

In **INSERT** statement

`SQL
String sql = "INSERT INTO Stock VALUES (100, 'abc')";
int result = stmt.executeUpdate(sql);
HQL
Query query = session.createQuery("insert into Stock(stock_code,
stock_name) select stock_code, stock_name from backup_stock");
int result = query.executeUpdate(); `

❗ HQL only support insert from another table so you have to do this by creating and persisting new entity.


## To sum up

1. HQL is similar to SQL and is also case insensitive.
2. HQL and SQL both fire queries in a database. In the case of HQL, the queries are in the form of objects that are translated to SQL queries in the target database. 
3. SQL works with tables and columns to manipulate the data stored in it while HQL works with classes and their properties to finally be mapped to a table structure in a database.
4. HQL supports concepts like polymorphism, inheritance, association, etc. It is a powerful and easy-to-learn language that makes SQL object oriented. 
5. SQL lets you modify the data through insert, update, and delete queries. You can add tables, procedures, or views to your database. The permissions on these added objects can be changed.
Weekly Challenge 160
Tags: perl, python, theweeklychallenge
Published: 2022-04-17 11:32:36

[Challenge](https://theweeklychallenge.org/blog/perl-weekly-challenge-160/), [My solutions](https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-160/sgreen)

Two straight forward tasks, so lets get stuck into it.

## TASK #1 › Four Is Magic

### Task

You are given a positive number, `$n < 10`.

Write a script to generate English text sequence starting with the English cardinal representation of the given number, the word ‘is’ and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue until you reach four.

### Solutions

So both Python and Perl have modules that can convert integers to numbers in English (and other languages), but since we are only dealing with 10 numbers (zero to nine), I just hard code the strings.

I have a loop where I calculate `l` being the length of the word representing the number `n`, and add the phrase `word[n] is word[l]` to the `phrases` list (array in Perl), and then set `n` to the value `l`. The loop exits when `n == 4`.

Then it's a matter of capitalizing the first letter, and adding the final phrase and printing the string.

### Examples

```
$ ./ch-1.py 5
Five is four, four is magic.

$ ./ch-1.py 7
Seven is five, five is four, four is magic.

$ ./ch-1.py 6
Six is three, three is five, five is four, four is magic.
```

## TASK #2 › Equilibrium Index

### Task

You are give an array of integers, `@n`.

Write a script to find out the Equilibrium Index of the given array, if found.

For an array A consisting n elements, index i is an equilibrium index if the sum of elements of subarray `A[0…i-1]` is equal to the sum of elements of subarray `A[i+1…n-1]`.

## Solution

As we don't know the order of the string, I just brute force the solution (if one exists). Starting at 1 (the 2nd element) and ending at `n-1` (the second last element), I see if the sum of digits to the left is equal to the sum of digits to the right. If it does, I set the value `idx`, and exit the loop.

## Examples

```
$ ./ch-2.py 1 3 5 7 9
3

$ ./ch-2.py 1 2 3 4 5
-1

$ ./ch-2.py 2 4 2
1
```
Hibernate - Flush
Tags: hibernate, database, spring, performance
Published: 2022-04-17 11:27:23

One of the most confusing points about JPA/Hibernate is the flush operation and its relation to the transaction. 

> Flush is the operation that transfers the changes related to the existing entities to the database with SQL statements in the PersistenceContext managed via Session in Hibernate and EntityManager in JPA.

> Transaction, on the other hand, ensures that persistence operations (insert, update or delete) performed in the database between the beginning and the end (commit) become permanent with the “all-or-nothing” logic.

When working with JPA/Hibernate, the SQL equivalents of persist, merge, and remove/delete operations on the PersistenceContext are not immediately reflected in the DB. These changes are accumulated in the PersistenceContext. This is called the transactional write behind feature of the ORM. 


These accumulated changes are reflected to the DB with the **flush** operation. However, in order for these changes to become permanent, the current transaction must be successfully terminated (commit).

## Do I need flush after every operation? 💧

Flush operation is run automatically in the background when the transaction is committed under normal conditions. Normally there is no need to run a manual flush on the PersistenceContext.

With **FlushMode**, you can control when the flush operation will run. 

JPA has 

- AUTO
- COMMIT

Hibernate has 

- AUTO
- COMMIT
- MANUAL
- ALWAYS

modes. **By default, FlushMode is AUTO**. In this case, the flush operation is automatically triggered immediately before the ORM queries run regarding the entities that have changed on the PersistenceContext and during the transaction commit.


**To sum up**
If the Flush method is run manually at any stage, changes on the PersistenceContext are detected and reflected in the database as INSERT, UPDATE, DELETE SQL statements. However, these changes can become **permanent only if the transaction commits**.
Now & Later
Tags: beginners, javascript, tutorial, startsmall
Published: 2022-04-17 11:08:57

## You Don't Know JS - Async & Performance

I'm currently reading `You Don't Know JS series `(Async & Performance) book, I'm planning to make notes of important concepts and code snippets in this series.

More details about the series:https://github.com/getify/You-Dont-Know-JS

## Now & Later

In JavaScript, program/function can either run *Now* or *Later*. The relationship between them is the heart of asynchronous programming.

```js
let answer = 1;

function now() {
  return answer;
}

function later() {
  answer = answer * 2;
  console.log("Answer:", answer);
}

now(); // 1

setTimeout(later, 1000); // Answer: 2
```

All the statements in the above program run *Now* except for the body of later() function. i.e,

```js
  answer = answer * 2;
  console.log("Answer:", answer);
```

Another example is how we make Ajax requests to fetch data from the server.

```js
  // ajax() is some utility to make Ajax requests
  const data = ajax("example.com");
  console.log(data); // Oops, you won't get data as expected

  // Both the above statements run Now, ajax calls is a Network call so it would take some time to fetch results. That's the reason we won't get data to be resolved. 
```

## Event Loop

Javascript just recently before (ES6) has never had asynchrony built into it. JS engine doesn't run in isolation, it is always supported by *Hosting environment* like Browsers, and NodeJs. 

One common "thread" of all the environments does the magic to execute multiple chunks of your program *over time* at each moment invoking the JS engine, called the "**Event Loop**"

- Find more about the [Event Loop]( https://dev.to/yo08315171/event-loop-439g)
- Visualise how Event Loop works (Call Stack, Micro Task Queue, Task Queue)

## Jobs

As of ES6, there is a new layer on top of the event loop called Jobs queue. There are a few special async events handled by this queue like Promises. There is a difference in how the event loop handles timers like `setTimeout` and `Promises`. 

**Timers**
Timers are always added to the next tick of the event loop.

**Promises** 
Promises are added to the Jobs queue which is handled by end of the ongoing tick in the event loop instead of the future tick.

```js

console.log('A');

// Timers
setTimeout(function () {
  console.log('B');
}, 0);

// Promises
const p = Promise.resolve('C');
p.then(function (value) {
  console.log(value)
});

```

**Output**: A C B instead of A B C though we set the timer to 0 milliseconds.
Xbox Blog
Tags: xbox, gamming, console, xboxone
Published: 2022-04-17 10:01:24

Welcome to my Xbox blog https://xboxreviewer.com/ with reviews and tips! In this blog, I will be discussing my thoughts on various Xbox games and what I think could be improved. I hope you enjoy reading and please feel free to leave your comments below!

Xbox One

This week, I finally got my hands on the Xbox One and I have to say, I'm really impressed! The console is sleek and sexy, and the games look and feel amazing. The only downside is that the console is a bit on the expensive side, but I'm sure that it will be worth it in the end.

In the meantime, I've started playing Batman: Arkham Knight
Javascript Tutorial and Projects Course (John Smilga)
Published: 2022-04-17 10:00:49

---
title: Javascript Tutorial and Projects Course (John Smilga)
description: Learn Javascript by Building Many Interesting Projects!.
---

## Javascript Tutorial and Projects Course (John Smilga)

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

## Why did it take this course?

As you may know by now, the fundamentals knowledge of web developers are HTML & CSS and Javascript, so after I finished this, [HTML & CSS course](/blog/HTML-CSS-course), I knew the best next thing was to start my javascript adventure.

Choosing the course was the simplest thing, I already knew I wanted to take John Smilga Javascript Course, which you can check by clicking [clicking here](https://www.udemy.com/course/javascript-tutorial-for-beginners-w/).

I knew javascript was not going to be easy to understand at first, but I did not know I was going to like that much so quickly and that I was going to start understanding it sooner than I thought.

Of course, there are many things I don’t know about Javascript, and it will take years to be an expert on it, but I really like it so far.

## About the course

As usual, John delivers the best content you can look for, the course is perfect from the beginning to the end. The course covers everything thing you need to know about this language, from the most basic things to the lasted ES6 featured and more.

After you finish this course, you will definitely start feeling like a web developer.

## What you will learn

This is what John tells us we are going to learn during the course.
- Know what is Javascript
- Know how to add Javascript to their projects
- Know the basics of working with Javascript
- Build projects using Javascript

## Prerequisite

Basic knowledge of HTML and CSS.

## Course content and Course Projects

This course is divided into 18 sections with a total of 357 lessons and a total duration of 40 hours.

Since it is a beginner’s course, during the first sections we learn the basics and most important thing about Javascript and manipulating the DOM after that, there is an entire section with more than fifteen projects where you get to put into practices everything you had learned.

After this first part, we start learning about ES6, Modules, AJAX and so more and again we get to use all this knowledge in some different projects.

In the last section of the course, we build an online store called “Comfy Store”.

To see all the course projects, [click here](https://www.johnsmilga.com/projects).

## My thought about this course

All John courses are great, I al will eventually take all of them. The way the course and the lessons are structured, the projects, and the explanations are perfect.

Here is really a great teacher and as I said before, I keep recommending his channel and courses to anyone how is interested in learning about web development.

I will always remember this course as the cornerstone of my web developer career.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zphky0jqh1pfhl2gvvq.jpeg)
Render a DateTime Object in Twig
Tags: twig, php, tutorial, webdev
Published: 2022-04-17 09:17:17

### The date filter
In Twig, the `date` filter uses the same [DateTime format](https://www.php.net/manual/en/datetime.format.php) of PHP
to render DateTime instances in server-side.

```php
require_once './vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('./themes');

$twig = new \Twig\Environment($loader);

$twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('Australia/Melbourne');

$dt = new DateTime("2010-07-05 06:00:00", new DateTimeZone("Australia/Melbourne"));

echo $twig->render('render-a-datetime.twig', array("myDateTime" => $dt));
```
In the above PHP code snippet, the function `setTimezone` is used to set the default timezone globally in Twig. The new DateTime instance `$dt` is created with the timezone of `Australia/Melbourne`. After that, it is passed to the template file render-a-datetime.twig. In the template file, we can render the DateTime variable `myDateTime` like this:
```html
{{ myDateTime|date("d M Y H:i") }}
```
The output will be:
```html
05 Jul 2010 06:00
```

If want to show the current date in Twig, we can use the word `now`.
```html
{{ "now"|date("d M Y H:i") }}
``` 

### The date filter with a timezone
We can override the default timezone in the `date` filter with a given timezone string. For the details of the supported timezones, you can refer to [List of Supported Timezones](https://www.php.net/manual/en/timezones.php). For example, you can display the current date instance for different cities.
```html
<p>
   New York: {{ "now"|date("d M Y H:i", "America/New_York") }} <br>
   Paris: {{ "now"|date("d M Y H:i", "Europe/Paris") }} <br>
   Hong Kong: {{ "now"|date("d M Y H:i", "Asia/Hong_Kong") }} <br>
   Melbourne: {{ "now"|date("d M Y H:i", "Australia/Melbourne") }}
</p>
```
The above code will output:
```html
New York: 20 Oct 2020 20:30
Paris: 21 Oct 2020 02:30
Hong Kong: 21 Oct 2020 08:30
Melbourne: 21 Oct 2020 11:30
```

Thanks for reading!
To find more programming tutorials, please visit: [CodeBilby.com](https://www.codebilby.com)
Conversational AI in VRChat 1
Tags: ai, vr, vrchat
Published: 2022-04-17 09:44:34

## What's this?

- Introduction of a voicebot that implemented conversational AI in VRChat
  - https://youtu.be/8u22YDqhY6Y


## System

- ASR: googletrans
  - https://pypi.org/project/googletrans/
- Text Generation: ILYS-aoba-chatbot (seq2seq model pretrained with Japanese dialog data)
  - https://github.com/cl-tohoku/ILYS-aoba-chatbot
- TTS: tyc-talksoft
  - https://shirowanisan.com/tyc-talksoft

- Sound Pipeline
  - application -> speaker -> dialog.py -> mic -> application
  - Direct loop also exists.. (application -> speaker -> mic -> application)

- (TBD) Release the scripts in GitHub
  - Need to clean the codes and write documents..


## Prerequisites

- Ubuntu 18.04.5 LTS
- Voice chat application (VRChat for example)


## Setup

`
$ sudo apt install portaudio19-dev pavucontrol python-xlib scrot
$ git clone https://github.com/Lunran/sts.git
$ cd sts
$ python3 -m venv venv
$ . venv/bin/activate
$ pip install --upgrade pip
$ pip install -r requirements.txt
`


## Usage

- Run VRChat
  - Open "Settings", "Audio Volume"
    - Mute "UI/Menu", "World" and "Avatars" 
- Run the script
  - refer to "$ python dialog.py -h" for details
บันทึกการเรียน TypeScript [1 : พื้นฐานการติดตั้ง - ตัวแปร]
Published: 2022-04-17 09:08:20

ส่วนนี้จะเป็นการบันทึกการเรียน TypeScript จากคลิปกับช่อง Programming with Mosh 

https://www.youtube.com/watch?v=NjN00cM18Z4


1. TypeScript จัดเป็น Superset ของ JavaScript
2. การติดตั้ง : node install -g typescript 
3. ตรวจสอบ version : tsc --version  
4. การ declaring ตัวแปร ก็เหมือนกับ JS คือ let var const
5. การ compile เป็นไฟล์ .js : ตัวอย่างสร้างไฟล์ที่ main.ts 
วิธี compile ก็ใช้ tsc main.ts ซึ่งจะจะได้ main.js 
6. การ run ไฟล์ .js ก็ใช้เป็น node ชื่อไฟล์ เช่น node main.js
String Concatenation and Interpolation in Twig
Tags: twig, php, webdev, tutorial
Published: 2022-04-17 08:55:43

Twig has two useful operations, `~` and `#{}`, for string concatenation and interpolation respectively.

### String concatenation
We can use the operator `~` to convert all operands into strings and append one string to the end of another. For example, in PHP, we pass two variables to the template string.twig.
```php
echo $twig->render('string.twig', array("numA" => "1", "numB" => "9"));
```

In the template file string.twig, we can use the operator `~` to concatenate the strings.
```html
<P>{{ "Number A is: " ~ numA}}<br>
   {{ "Number B is: " ~ numB}}
</p>
```

The output will be:
```html
Number A is: 1
Number B is: 9
```

### String interpolation
Within a double-quoted string, we can use the interpolation operator `#{}` to evaluate a valid expression and the result is converted to a string for display. In the template file, we can do like this:
```html
<P>
   {{ "A + B = #{numA + numB}"}}
</p>
```

The numbers `numA` and `numB` will be added together, and the output will be:
```html
A + B = 10
```

Thanks for reading!
To find more programming tutorials, please visit: [CodeBilby.com](https://www.codebilby.com)
Turning MPA to SPA with Virtual DOM
Tags: webdev, javascript, opensource, react
Published: 2022-04-17 08:05:03

> _Plug: I help develop [`Million`](https://github.com/aidenybai/million): Virtual DOM into the future! 💥🦁✨_

## Motivation

Whether you use a static site generator like Eleventy, have a server rendered application with Ruby on Rails, or just have a plain HTML/CSS/JS site, you're probably using some sort of multi-page application.

The main issue with MPA is that each navigation (e.g. clicking a link, form submission) requires a full page reload, meaning more time is wasted. 

We could rewrite our entire app as a SPA with React/Vue, but that would be time consuming and unnecessarily complex.

This is why tools like [Turbo Drive](https://turbo.hotwired.dev/handbook/drive) exist. Turbo Drive _"watches for link clicks and form submissions, performs them in the background, and updates the page without doing a full reload."_ 

However, I feel like Turbo Drive is sometimes too overcomplicated -- I just want something small that works without much configuration.

## Usage

Using [Million](https://millionjs.org), a modern Virtual DOM library, I created a [MPA to SPA router](https://millionjs.org/docs/api/extra/router). 

All you have to do is add this in your HTML files

```js
import { router } from 'https://unpkg.com/million?module';

router();
```

And it's that easy!
Today's Fun Joke For Developers - Daily Developer Jokes
Tags: jokes, dailydeveloperjokes
Published: 2022-04-17 08:00:21

---
title: "Today's Fun Joke For Developers - Daily Developer Jokes"
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
---

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/5e1259a922f36.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 is a developer's favorite country song?

___A___: Hello World - by Lady Antebellum
 -->