teleren/devto huggingface dataset:
Is there any reason to use ZoneId.of("UTC") instead of ZoneOffset.UTC?
Tags: java, timezone, api
Published: 2022-06-24 17:48:14

I came across this question on StackOverflow:

[Is there any reason to use ZoneId.of("UTC") instead of ZoneOffset.UTC?](https://stackoverflow.com/questions/69972061/is-there-any-reason-to-use-zoneid-ofutc-instead-of-zoneoffset-utc)

Since I had to deal with an issue related to this question in production, I wanted to share my answer here because I think it might be useful to anyone serializing `ZonedDateTime` with Jackson.

**Tl;dr** if you use Jackson, you might be better of using `ZoneId` instead of `ZoneOffset`.

---

I can think of one situation where `ZoneId.of("UTC")` might be preferable over `ZoneOffset.UTC`. If you use **jackson-datatype-jsr310** to deserialize `ZonedDataTime` from JSON, you get dates with `ZoneId`.

For example, let's say we have this POJO (getters/setters omitted for brevity):

```java
class Example {
    private ZonedDateTime date = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS);
}
```

If you print an instance of the class you get:

```java
Example example1 = new Example();
System.out.println(example1);

// output:
// Example(date=2022-06-17T00:00Z) - as expected
```

What happens when you deserialize JSON containing the above string `2022-06-17T00:00Z`?

```java
String json = "{\"date\":\"2022-06-17T00:00Z\"}";
Example example2 = mapper.readValue(json, Example.class);
System.out.println(example2);
// output:
// Example(date=2022-06-17T00:00Z[UTC]) // now with ZoneId(!)
```

So now we have two variants, one with `ZoneOffset` and one with `ZoneId`:

- `2022-06-17T00:00Z`
- `2022-06-17T00:00Z[UTC]`

And these are not equal to each other. For example:

```java
Instant instant = Instant.now();
ZonedDateTime z1 = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
ZonedDateTime z2 = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));

System.out.println(z1.equals(z2)); // => false
```

As a result `example1.equals(example2)` will also be `false`. This could be a source of subtle bugs.

**Note**: you get same result if your serialize `new Example()` to a JSON string and deseralize the string back to an object. You will get a date with `ZoneId`.

Tested with Jackson `2.13.1`.
What is REST API?
Tags: api, webdev, rest
Published: 2022-06-24 17:44:04

**REST** stands for **representational state transfer** and was created by computer scientist _Roy Fielding_.

## What's an API?

> Quoting to Red Hat

If you want to interact with a computer or system to retrieve information or perform a function, an API helps you communicate what you want to that system so it can understand and fulfill the request. 

You can think of an API as a mediator between the users or clients and the resources or web services they want to get. It’s also a way for an organization to share resources and information while maintaining security, control, and authentication—determining who gets access to what. 

## REST

> **REST is a set of architectural constraints, not a protocol or a standard**

> Quoting TechTarget

A RESTful API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources.

## CRUD

![CRUD Operations](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fz0vka3t10reo87mx3km.png)

## HTTP METHODS
![HTTP METHODS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shpkzvpj7h08zsnrjad5.png)
 
{% embed https://www.youtube.com/watch?v=qVTAB8Z2VmA %}
Fruity Health
Tags: webdev, beginners, programming
Published: 2022-06-24 17:40:16

### Brief Intro
Keeping up with changing technology is important. Fruit Health shows you nutrients in a fruit. 
Eating fruits provides health benefits, people who eat more fruits & vegetables as part of an overall healthy diet are likely to have a reduced risk of some chronic diseases. Fruit Health shows you nutrients in a fruit. You can check out using this  [link
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oedf42qtngafef1o5unr.png)](carreuky.github.io/fruity-health/)
Язык программирования Си. Глава(Chapter) 2
Tags: c, russian
Published: 2022-06-24 17:35:25

![Statements in C](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90bidey451nmd022cuii.png)

**1.** Предварительная обработка(_Preprocessing_) инструкций препроцессора(_Preprocessor Instructions_), пример: `#include`.
Заголовочный файл(_Header File_), пример: `stdio.h`, содержит объявления переменных и функций, определённых, то есть заранее скомпилированных, в библиотечном файле(_Library File_).

**2.** Прототип(_Prototype_) или объявление(_Declaration_) функции состоит из заголовка(_Header_), с возвращаемым типом(_Function Return Type_), идентификатором(_Identifier_) и типами принимаемых аргументов(_Function Argument Type_).
Определение(_Definition_) функции состоит из заголовка(_Header_) и тела(_Body_), с различными операторами.
```c
int foo(int, int); //function declaration
int foo(int a, int b) { return a + b; }; //function definition
```

**3.** Синтаксические ошибки(_Syntax Errors_) или грамматические ошибки(_Grammatical Errors_) и семантические(_Semantic Errors_) ошибки и их отладка(_Debugging_) с помощью отладчика(_Debugger_), то есть просмотра состояния программы(_Program State_).
```c
+ a b = int sum //syntax error
int sum = a * b; //semantic error
```

**4.** Ключевые слова(_Keywords_), например: `return`, `while`; и зарезервированные идентификаторы(_Reserved Identifiers_) начинающиеся с `_` - нижнего подчёркивания: `_identifier` или `__identifier`.
  
**5.** Идентификаторы или имена переменных и функций(_Variable and Function Identifier or Name_):
- должны содержать только цифры и буквы, включая знак нижнего подчёркивания;
- не должны начинаться с цифры;
- не должны именоваться так же как и ключевые слова или зарезервированные идентификаторы;
- иметь длину в 31 или 6 символов для локальных(_Local_) и для внешних(_Extern_) идентификаторов, соответственно стандарту ANSI C.

```c
//not valid identifiers
int x*y#!;
int 3d;
int return;
int __DATE__;

//valid identifiers
int xy;
int dimension3;
int returnValue;
int current_date;
```

**6.** Структура и пример простой программы(_The Structure and Example of a Simple Program_).
```c
//это комментарии, они не влияют на выполнение программы
#include <stdio.h> //подключение заголовочного файла
//объявление функции sum()
int sum(int, int n2); //ANSI прототип функции
//в каждой программе обязательно должен быть main()
int main() //заголовок функции
{ //начало блока
    int num_1 = 9, num_2 = 3; //объявление и инициализация переменных
    printf("%d\n", sum(num_1, num_2)); //функция вывода в терминал из stdio.h
    return 0; //оператор возврата
} //конец блока
//определение функции sum()
int sum(int a, int b) //функция sum() возвращает значение int
{ //начало тела функции
    int result; //объявление переменной
    result = a + b; //присваивание значения
    return result; //возврат значения в main()
} //конец тела функции
```

> Язык программирования Си 6 издание. Стивен Прата
> C Primer Plus 6th edition. Stephen Prata
Install Microsoft Sql Server php drivers in Laravel Sail
Tags: laravel, docker, php, devops
Published: 2022-06-24 17:22:11

If you ever have a Laravel Sail container that needs to connect to a mssqlsrv database, this is how you can install the drivers. 

After installing Laravel Sail and running sail:publish, you need to add this block after the RUN update-alternatives ...

``` bash
#Add repository ODBC and Install the Microsoft ODBC driver for SQL Server
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \
    && curl https://packages.microsoft.com/config/ubuntu/21.04/prod.list > /etc/apt/sources.list.d/mssql-release.list \
    && apt-get update \
    && apt-get install -y unixodbc-dev \
    && ACCEPT_EULA=Y apt-get install -y msodbcsql17 \
    && ACCEPT_EULA=Y apt-get install -y mssql-tools \
    && apt-get install -y gcc musl-dev make

# Install the PHP drivers for Microsoft SQL Server

RUN curl -O https://pear.php.net/go-pear.phar \
     && php go-pear.phar

RUN pecl channel-update pecl.php.net \
    && pecl install sqlsrv pdo_sqlsrv \
    && printf "; priority=20\nextension=sqlsrv.so\n" > /etc/php/8.0/mods-available/sqlsrv.ini \
    && printf "; priority=30\nextension=pdo_sqlsrv.so\n" > /etc/php/8.0/mods-available/pdo_sqlsrv.ini \
    && phpenmod -v 8.0 sqlsrv pdo_sqlsrv \
    && pecl clear-cache \
    && rm -rf /tmp/* /var/tmp/*
```
Now add your DB config to the .env Laravel file.
Nx for Angular developers
Tags: nx, angular, books
Published: 2022-06-24 16:53:56

---
title: Nx for Angular developers
published: true
description: 
tags: nx,angular,books
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zrm61b7n3sbg36mph0e.jpg
# Use a ratio of 100:42 for best results.
---

I started writing another book, it's called [The Angular Developer's Nx Handbook](https://leanpub.com/the-angular-developers-nx-handbook) and you can download the early draft for free (or choose to donate). The final version will also be free on Leanpub in their online formats. I plan to publish Kindle and print copies at as low a price as possible once it's *done*.

## Why another book?
My wish is that this book will increase the adoption of the Nx build framework in the Angular community and ecosystem. Nx is an incredible toolchain that I have enjoyed seeing grow over the past 5 years. I have had practical experience using it in a variety of projects over the past 3 years.

This book intends to give you everything you need to get going with Nx as an Angular developer. All features that I consider essential are covered.

## The Nx Handbooks
Following this book is a series, *The Nx Handbooks*, of paid books that build on top of the essentials introduced in *The Angular Developer's Nx Handbook* but with a focus on specific roles:
- Software architects
- Open-Source Software Developers
- Nx plugin developers
- DevOps Engineers

I hear the same questions asked again and again and I especially see Angular developers struggle to see how Nx is better than our trusty Angular CLI.


## Contents
*The Angular Developer's Nx Handbook* is a curated guide to learning Nx and it will take you a long way on your Nx journey.

It currently covers:
- Nx workspace generation
- Basic Nx CLI commands
- Creating a standalone Angular application
- Configuring tooling for code consistency
- Nx library traits
- Nx library types

To come:
- Advanced Nx CLI commands
- The Nx graph
- A CI workflow using GitHub Actions
- Implementing a GitHub clone using Angular Material and the GitHub REST API

## Media

Recently, [I discussed this book with Nacho Vazquez on his show](https://www.twitch.tv/videos/1511110392). I will also talk about the book on [the Adventures in Angular podcast](https://topenddevs.com/podcasts/adventures-in-angular/) soon.

Feel free to send me feedback on the early draft and which topics you would like to see covered in *The Nx Handbooks* series.
Working with emits in Vue 3 + Typescript
Tags: vue, typescript, javascript
Published: 2022-06-24 16:51:45

In this post I will show you'll how to work with emits Vue 3 + Composition API using `<script setup>`, there's few ways to work with it, let's take a look!

**_Using the defineEmits() macro we can declare emits like:_**

**1 - Array of strings**

```javascript
<script setup>
const emit = defineEmits(['inFocus', 'submit'])

function buttonClick() {
  emit('submit')
}
</script>
```

**2 - Object syntax**

```javascript
<script setup>
const emit = defineEmits({
  submit(payload) {
    // return `true` or `false` to indicate
    // validation pass / fail
  }
})
</script>
```

**3 - Runtime or base type declaration**

```javascript
<script setup lang="ts">
// runtime
const emit = defineEmits(['change', 'update'])

// type-based (TS)
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()
</script>
```

That's it!

If you want to read and learn more details about component emits declaration, please make sure to visit the [Vue 3 official documentation about emits](https://vuejs.org/guide/components/events.html).

**See'ya!**

---

**<u>Article references:</u>**
https://vuejs.org/guide/components/events.html
https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits
multi-processing vs multi-threading
Tags: tutorial, programming, architecture, performance
Published: 2022-06-24 16:43:00

I was given the question "what is difference between multi-processing and multi-threading" as an interview question. Today, I will not use big grammatical words to explain the differences between multi-processing and multi-threading to make it very easy for everyone to understand.


![BMC](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aw19bysg8wr8kc17arun.gif)

first, we need to understand these terms 
1. Processor **(CPU)** is a chip that exists on the computer's mother-board, it executes the basic instructions that are given to it. It receives commands and perform the operations the user has requested. For example, the CPU processed the instructions to use a web browser to open and display this web page on your computer. [refrence](https://www.computerhope.com/jargon/c/cpu.htm)

2. Process is a program in execution.

Now that we have established the facts, let us get into the details.

#### Multi-processing 
This is when a computer has two or more processors (CPUs). Todays' computers can have 2,4,8 CPUs. Device manufacturers leverage multiple CPUs to increase application performance and responsiveness (no lagging).
In multi-processors, we can run multiple programs (music app, gaming app, MS-word) at the same time.

#### Multi-threading
Firstly, a thread is a unit of a process.

Multi-threading means many threads run in the same parent process (program) at the same time. For example, using MS-word is a process (program), while using spell-check and copy-paste in MS-word is a thread.

Creating processes for each task is not an effective method. Therefore, a process is divided into multiple threads. These multiple threads are running on the process at the same time.

**Differences between muti-processing and multi-threading**

| Mult-processing      | Multi-threading |
| :-----------:        | :-----------: |
| Multi-processing means a computer having two or more CPUs (processors) and it is able to run multiple programs at the same time.                  | Multi-threading means many threads run in the same parent process (program) at the same time.       |
| Multi-processing; a lesser amount of time is taken for processing a task (job).            | Multi-threading; a moderate amount of time is taken for processing a task (job).        |
| Multi-processing executes many programs at the same time | Multi-threading executes many threads at the same time. |

**Thank You, please follow me**

[twitter](https://twitter.com/ifeanyiTchima)
[github](https://github.com/MasterIfeanyi)
[linkedin](https://www.linkedin.com/in/ifeanyi-thankgod-chima/)

<a href="https://www.buymeacoffee.com/ifeanyichima" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>
What was your win this week?
Tags: discuss, weeklyretro
Published: 2022-06-24 16:41:27

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Hey there! 


Looking back on this past week, what was something you were proud of accomplishing?

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Hiking in the great outdoors... or whatever else might spark joy ❤️ 

---

Have a wonderful weekend!


![kitty cat napping with the words "Happy Weekend!" floating above it](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aentctfve4i9hhnkv450.gif)
NPM - CLI tool to generate .gitignore file
Tags: showdev, javascript, news, programming
Published: 2022-06-24 16:35:41

*Generate .gitignore file with template for your project*

## Features ✨
* Choose a template based on [https://github.com/github/gitignore](https://github.com/github/gitignore)
* Choose a custom path to create `.gitignore` file

## Install 🐙
```
npm i -g cligit
```

## Usage 💡
```
cligit <commands> [options]
```

OR

```
npx cligit <commands> [options]
```
*Use this if you don't want install this package globally.*

### Commands
*Commands are optional but allow you to skip question for choosing template*.

You can find the template availables in this [github repository](https://github.com/github/gitignore) where template name is filename without the extension.

> **Example** - Supposing you'like to create a `.gitignore` file and your project works with NodeJs you should run this `cligit Node`

### Options
* `--path` **optional**, The path to create the `.gitignore` file.

## Exemples 🖍
*With template name*
```
cligit Node
```

*With custom path*
```
cligit --path dev/foo/
```

*With template and custom path*
```
cligit C --path dev/foo/
```

Good code and have fun 🧑‍💻

* [https://github.com/luctst/gitignore-cli](https://github.com/luctst/gitignore-cli)
* [https://lucastostee.com](https://lucastostee.com)
Gaming 🎮 in parallel with Programming 💻
Tags: webdev, beginners, programming, productivity
Published: 2022-06-24 16:30:10

I am a programmer for more than 3years now. Professionally working as a **Software Engineer** for more than 2years.

---

I've always been a fan of **mobile games**.

With programming I started Gaming 3 years ago.

The game I plays the most is **PUBG (or BGMI)**

So, recently I created a **YouTube channel**.

--- 

Link to the First Video

{% embed https://youtu.be/lFHbDsawl0Y %}

---

Thank You
Happy Coding 💻, Gaming 🎮
I developed a random quote generating app using react and api.adviceslip.com
Tags: react, webdev, javascript, node
Published: 2022-06-24 16:10:17

I used react and api.adviceslip.com to create a random quote generating app.Since i am a beginner to development,i am pretty sure that this is a best project for beginners in react.I am leaving the live link of the app along with the link of my github repo.

[Live link of project](https://nikquoteapp.netlify.app/)
[Github link](https://github.com/Nikeshkumar-tk/quote-generator)
JavaScript mini challenge: selectpicker and max options
Tags: javascript, codepen, challenge
Published: 2022-06-24 16:08:07

Hello coders!

I had to work on a simple problem this week and thought it could be a good idea for a mini challenge.

Here's the gist of it:
> users should be able to select as many cities as they like from a drop down as long as they're not located in more than 2 countries.

In the image below I've selected 5 cities and only 2 countries so it's all good.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6w1ksaj2whin587s285y.png)
 
I should not be able to select any city in Spain as it would result in 3 countries.

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

## Give it a go! 
Feel free to change anything that could make your life and code easier.

Our project uses [bootstrap-select](https://developer.snapappointments.com/bootstrap-select/) so you need to implement your solution with that plugin.

Here's a Codepen template for you to play with (I used the same to implement my solution):
{% codepen https://codepen.io/JoolsMcFly/pen/rNJXJdd %}

## Solution
I'll post a follow-up later to explain my solution and get feedback too.

## Have fun! :computer:
I'm looking forward to your entries. :fire:
1114. leetcode solution in CPP
Tags: cpp
Published: 2022-06-24 16:04:08

```
class Foo {
 public:
  Foo() {
    mutex2.lock();
    mutex3.lock();
  }

  void first(function<void()> printFirst) {
    printFirst();
    mutex2.unlock();
  }

  void second(function<void()> printSecond) {
    mutex2.lock();
    printSecond();
    mutex3.unlock();
  }

  void third(function<void()> printThird) {
    mutex3.lock();
    printThird();
  }

 private:
  mutex mutex2;
  mutex mutex3;
};
```
Integrate Cucumber in Playwright With Java
Tags: java, playwright, tutorial, testing
Published: 2022-06-24 16:03:20

Problem statement
This blog cover how we can integrate cucumber in playwright with java

https://www.linkedin.com/posts/kailashpathak_integrate-cucumber-in-playwright-with-java-activity-6946128754930782208-B25b?utm_source=linkedin_share&utm_medium=member_desktop_web
Environment Variables in NodeJs app
Tags: node, processenv, webdev, environmentvariables
Published: 2022-06-24 16:02:15

## What are Environment Variables?
**Environment Variables** are variables that are set by the Operating System. They are decoupled from application logic. They can be accessed from applications and programs through various APIs.

## Why to use them?
Using environment variables helps the app to behave according to the environment in which the app is to be deployed. Environment variables also help to encapsulate the data.

## How to use them in NodeJs application?
At first, we need to install a package named **dotenv**. We can use `npm i dotenv` or `yarn add dotenv` to install the package.

Then we need to create a file named `.env`. Note that we need to add `.env` file in `.gitignore.` This will help us in encapsulation of our data. Now we can define our variables in `.env` file.

Declare all the variables in `.env` file in **uppercase**, i.e, use **Snake Case**, but all letters should be in uppercase.
**For e.g.** `VARIABLE_NAME = 23`.

Once you declare the variables in `.env` file, then let's see how to access them in our app.
In our app, import the `dotenv` package where we want to access the environment variables as `require('dotenv').config()`. There is no need to save it in a variable like we save other packages such as, we import **express** as `const express = require('express')`
Now, to access the environment variables, just use the following syntax: `process.env.VARIABLE_NAME`

## Example with code
**1. `.env` file**

```javascript
TEST_VARIABLE = thereIsNoNeedToEncloseStringInQuotes
PORT = 5000
```

**2. `index.js` file**
```javascript
require('dotenv').config();

const hostname = '127.0.0.1'
const port = process.env.PORT;
const testVariable = process.env.TEST_VARIABLE;
console.log(testVariable);

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
```

**Console output**
```
Server running at 5000
thereIsNoNeedToEncloseStringInQuotes
```
184. leetcode solution in MYSQL
Tags: mysql
Published: 2022-06-24 16:01:31

```
SELECT
    Department.name AS 'Department',
    Employee.name AS 'Employee',
    Employee.Salary
FROM
    Employee
JOIN -- default is inner join
    Department
ON Employee.DepartmentId = Department.Id
WHERE
    (Employee.DepartmentId , Employee.Salary) IN -- so that if tie, both will appear in result
    (
        SELECT
            DepartmentId, MAX(Salary)
        FROM
            Employee
        GROUP BY DepartmentId
    )
;

```
626. Leetcode SOLUTION in mysql
Tags: mysql
Published: 2022-06-24 15:59:10

```
# Write your MySQL query statement below
select (
    case
        when id % 2 = 0 then id - 1
        when id = (select max(id) from seat) then id
        else id + 1
    end
) as id, student
    from seat
    order by id;

```