teleren/devto huggingface dataset:
138. Copy List with Random Pointer
Tags: cpp, algorithms, 100daysofcode, programming
Published: 2022-03-12 12:37:24

# Description

A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.

Construct a **[deep copy](https://en.wikipedia.org/wiki/Object_copying#Deep_copy)** of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.

For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.

Return *the head of the copied linked list*.

The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:

- `val`: an integer representing `Node.val`
- `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.

Your code will **only** be given the `head` of the original linked list.

## Example 1:



```
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
```

## Example 2:



```
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
```

## Example 3:



```
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
```

## Constraints:

- `0 <= n <= 1000`
- `104 <= Node.val <= 104`
- `Node.random` is `null` or is pointing to some node in the linked list.

---

# Solutions

## Solution 1

### Intuition

1. copy nodes, in other words, use the new node as the original node’s next
2. copy random points
3. put points back to original nodes

    

### Code

```cpp
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    Node* copyRandomList(Node* head) {
        Node *p, *q;
        for (p = head; p; p = p->next->next) {
            q = new Node(p->val);
            q->next = p->next;
            p->next = q;
        }

        for (p = head; p; p = p->next->next) {
            if (p->random)
                // why random->next, because it needs to point copy node
                p->next->random = p->random->next;
        }
        Node *dummy = new Node(-1), *curr = dummy;
        for (p = head; p; p = p->next) {
            q = p->next;
            curr->next = q;
            curr = curr->next;
            p->next = q->next;
        }
        return dummy->next;
    }
};
```

### Complexity

- Time: O(n)
- Space: O(1)
Difference between Null and Blank in Django Model
Tags: django, python, webcomponents, backend
Published: 2022-03-12 12:16:44

In **Django**, many of us have some confusion between these two fields in a model **Null** and **Blank**, in short:


- **Null** is related to a database.
- **Blank** is related to an HTML form.

![sirkif-django-python.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1647082356121/f8W-DdfoN.png)

When we set:

- `null=True` which means that we inform our database that we can store empty value as NULL, no-value, without any data, ( Default value of `null` is False ).

- `blank=True` which means that our Form, our input will have a **required attribute** set to false ( by default is true ), then allow the user to enter an empty field, ( Default value of `blank` is False which means the required attribute is True ).

## Question

You may ask yourself when we have **string-based** fields in a model such as **CharField** and **TextField**, `Null` and `Blank` fields are set to True, then Django stores an empty string `(" ")` in a database instead of `Null`, **WHY** 🤔🤔?

## Answers

1. First because when our user submits an empty value, our input will return an empty string ( HTML inputs `type="text"` are always return string values ).

2. Second, and this important is `Null` in **SQL** world is treated as **Falsy value** and `Blank` ( empty string ) in **Python** world is also **Falsy**.

Therefore, it would be inefficient and redundant for Django to deal with two possible values that are treated as **Falsy values** ( No data & Empty String ).

## Summary

Since the HTML input returns a string value at the end, Django preferred to use an empty string `(" ")`, not `Null`.
Writing Architecture Decision Records
Tags: adr, adrs, documentation
Published: 2022-03-12 11:58:05

---
title: Writing Architecture Decision Records
published: true
tags: adr, adrs, documentation
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8di3spoal8fl38u4w5oe.png
canonical_url: https://carloscuesta.me/blog/writing-architecture-decision-records
description: An architecture decision record also known as ADR, is a document that captures an important architecture decision, including the context and the consequences.
---

An **architecture decision record** also known as _ADR_, is a document that captures an important architecture decision, including the context of how the decision was made and the consequences of that change.

### What are the benefits?

#### Sharing context

ADRs capture a decision at the time it's being made. They're the outcome of all of those asynchronous discussions in Slack that'll be lost over time ⏰

When you materialize them into docs, you're allowing your future teammates, to get the context for this specific change. So they'll be able to understand the issues, the decision that was taken and the impact it had on the project.

Writing docs will **help** you and your **future** peers in the **long run**! 🚀

#### Alignment

Writing decisions leads the team to consensus and ensures that all the assumptions of a change are clear 📏.

This will have a positive impact after the architecture decision has been implemented. Everyone on the team will have a deep understanding which will help on moving forward faster with the new approach.

### Writing ADRs

#### Define a template

When writing them, a common practice is to have a template to write ✍🏼 all the documents in the same way.

You'll find a lot of templates online, but here's the one I use it's very simple but easy to write.

```markdown
# Title

- Status: <!-- PENDING/APPROVED/DEPRECATED -->
- Date: DD/MM/YYYY
- RFC: <!-- Link to the RFC that ended up into the ADR -->

## Context

<!-- What is the issue that is motivating the decision or change? -->

## Decision

<!-- What is the change we're doing? -->

## Consequences

<!-- What becomes easier or more difficult because of this change? -->
```

#### Store them next to the code

I believe that **documentation** should be **next** to the **code** to make it easy to contribute to it. Whenever you add an external tool you're increasing the complexity to contribute and reducing the visibility of the docs 👀.

The solution is simple, check out the ADRs into your project repository and keep things simple and clean ✨

I recommend you to create a folder 📁 where you store all the decision records, for example: `docs/adrs/`.

#### Use a naming convention

When saving the files use a naming convention `title-of-the-adr-DD-MM-YYYY.md`

### Conclusion

**Write more ADRs** 😜, if you're not doing it yet, it's never too late to start!

In my experience as a team grows larger and a codebase becomes more complex, architecture decision records are a **great tool** to help your current and future team ❤️
DativeJs {{#each}} block
Tags: javascript, programming, tutorial, dativejs
Published: 2022-03-12 11:52:20

The `each` block in dativejs is used to iterate `array|object`

In the Formal Versions Of Dativejs

It Was Hard to Achieve This

So We Made this to be a betterment for that :)

### Usage




```html
<div>
  {{#each foods as food}}
      <li>{{food}}</li>
  {{/each}}
</div>
```

`each/each.dative.js`

```ts
import Template from './each/each.dative.html'
export let Each = Dative.extend({
   el: "#app",
   data(){
      return {
        foods: ["Rice","Noodles","Vegetables"]
      };
   },
   template: Template
})
```


You Can Also Catch the Index number of each array 

```html
<div>
  {{#each foods as i,food}}
      <li>{{i}}:{{food}}</li>
  {{/each}}
</div>
```


> **NOTE** When Using the `#each` block with `object` the `i` in the `#each` block will not be index again we are working on that





#### Don't Do This You'll Get A Messy Error
```html
<div>
  {{#each foods as food}}
      <li>Type: {{food.type}}</li>
      <li>Name: {{food.name}}</li>
  {{/each}}
</div>
```

`each/each.dative.js`

```ts
import Template from './each/each.dative.html'
export let Each = Dative.extend({
   el: "#app",
   data(){
      return {
        foods: {
           type: "Fruit",
           name: "Guava"
        }
      };
   },
   template: Template
})
```
### Do This

```html
<div>
  <!-- `i` will give you the key here not the index -->
  {{#each foods as i,food}}
      <li>{{i}}:{{food}}</li>
  {{/each}}
</div>
```

#### Thanks For Reading 

### You Want to Test DativeJs Online

{% embed https://stackblitz.com/edit/dative-vite?embed=1&file=src/app/app.dative.js %}

You Can Hit the Follow button on twitter i really appreciate
[My Twitter Profile](https://twitter.com/tobithealpha_)



## Thanks Once Again For Reading and Supporting Me
Candy - new way of styling react components
Tags: javascript, react, webdev, css
Published: 2022-03-12 11:48:13

Hello! My name is Dan.

I developed a new approach to styling react components. In this article, I want to tell you about it.

The idea is very simple. We write the usual `css`, `sass`, `less`.

```css
/* styles.css */

.root {
    color: white;
}

.red {
    backgroung-color: red;
}
```

And then we import html-tags-components from the style file. Each such component tag has boolean properties associated with the names of css classes.

```jsx
import { Div } from './styles.css'

function Component(props) {
    return (
        <Div root red={props.red}>
            ...
        </Div>
    )
}
```

This opportunity is provided by a special webpack-loader - [candy-loader](https://www.npmjs.com/package/candy-loader).

We get the opportunity to write the usual `css` and the same familiar `html`. You can import any standard `html` tag. Tags are capitalized and extended with an additional set of properties, from which the `className` property is generated under the hood.

You can include css files and access their styles.

```css
/* styles.css */
@import 'grid.css';

/*...*/
```

```jsx
import { Div } from './styles.css'

function Component(props) {
    return (
        <Div root red={props.red} col_xs_12 col_sm_8>
            ...
        </Div>
    )
}
```

## Easy configurable

`candy-loader` is based on `postcss`, so you can use the standard config file for further customization.

```javascript
// .postcssrc.js

module.exports = {
    plugins: {
        autoprefixer: isProduction,
    },
    processOptions: {
        map: isDevelopment,
    },
}
```

## Intellisense

There is a [typescript-plugin-candy](https://github.com/iminside/typescript-plugin-candy`) for that. A fairly easy to install and configure plugin that allows you to get autocomplete and type checking.

![Intellisense](https://habrastorage.org/webt/pi/qo/-4/piqo-4rah6gmsgmhpirvdd-xip8.png)

## Conclusion

What do you think about this idea? Should it be further developed and improved?

Below I have provided links to the source code and a pre-made starter repo in case you want to play around with it.
 
- [candy-loader](https://github.com/iminside/candy-loader)
- [typescript-plugin-candy](https://github.com/iminside/typescript-plugin-candy)
- [candy-boilerplate](https://github.com/iminside/candy-boilerplate)

I will be glad to your comments and suggestions for development. 

Thanks!
Why Learn Next.js? Why do React Developers Love Next?
Tags: react, javascript, webdev, beginners
Published: 2022-03-12 11:45:58

This is the second episode of my next.js course on YouTube. Let's see why next.js is becoming so popular before we get to the good stuff later in the course. 

The following video is more detailed. If you are not a video person read the summary below the video.

{% youtube 4jqA0kDvngM%}

- Flexibility in rendering
    - **Client** **rendering**- useEffect + axios ⇒ page loads layout, browser requests for data, html is generated using the data. require at least 2 responses from server (bad for SEO, a bit slow)
    - **Pre-rendering on the server** - _static generation_(all html is generated at build time, this makes the pages to load very fast and it's the best for SEO), _server side rendering_(html is generated at page request time, faster than client rendering). require 1 response from the server ( faster and better for SEO) ⇒ less work on the browser
    - **Incremental Static Regeneration**
- Better developer experience
    - Built in routing system
    - CSS/SCSS support
    - Typescript support
    - Image optimization
- Others
    - API routes support
    - Better performance out of the box (code splitting, minified code)
    - Active community

If you wish to learn next.js, follow my YouTube playlist. I will be doing daily uploads: https://youtube.com/playlist?list=PL63c_Ws9ecISruH1craAtJCJBOcVWQ4Rt

Happy coding 🤝
Creating a Loader with HTML and CSS
Tags: html, webdev, css, beginners
Published: 2022-03-12 11:34:54

Creating a Loader for website is very simple and exciting thing. 

Today in this post we will Make a Loader using HTML and CSS.

The main concept used here is **@keyframes** . @keyframes is used when we deal with animations. In simpler way it specifies what animation should happen at what value. You will understand here how to use keyframes.

{% codepen https://codepen.io/hrushikesh41/pen/QWaWjXo %}

As you can see in CSS I've used keyframes named spinnerLoad to rotate the div. The animation goes on for infinity. 

You can improvise this by giving container as inline-block.

Hope you like it. meet You in the Next Post

Till Then Happy Coding 👨‍💻👨‍💻👨‍💻
Importance of keys when rendering elements in react
Tags: react, keys, map
Published: 2022-03-12 11:15:09

---
title: Importance of keys when rendering elements in react
published: true
description: Why do we need to use unique keys when render elements in the loop in React
tags: react, keys, map
---

![Importance of keys in react -- Barcelona Code School](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbell187rn10hcbbrvyi.jpg)

We know that React wants us to use keys for each element rendered in the loop. The reason for that is that once data changes React can identify which element was changed and re-render elements properly. 

By default if no keys provided React will use indexes from the array and often we default to using them as well. But we need to remember that it can cause some issues in case of changes in the data. 

In this video we can see a simple example of these sort of problems and an easy way to avoid them.
Performance of anomaly detection cloud platform with MVTec dataset
Tags: python, machinelearning, deeplearning, cloud
Published: 2022-03-12 11:10:34

I verified the performance of the anomaly detection model automatic creation platform “ADFI” written in the previous article!

See [the previous article for ADFI](https://dev.to/umapyoi/image-anomaly-detection-how-to-create-models-quickly-and-easily-i9l).

Screen of ADFI:

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

<br>
# Experimental settings
## Dataset

For the verification experiment, I used the MVTec dataset, which is a very famous image dataset for anomaly detection.

It contains datasets of 15 categories that are frequently used in verification experiments of anomaly detection related papers.

Dataset image example:

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

<br>
## The number of data

Since the number of normal images and abnormal images differs depending on the data set, the below is used for each data set.

Training images were randomly extracted from the dataset. Test images are randomly extracted from images not used in Training images.

**Normal training data: 50**

**Anomaly training data: 10**

**Normal test data: 20**

**Anomaly test data: 20**

**Verification items**
 - Learning time
Time taken to train the model

 - Test time
Time from running the test to getting the results of all test data (40 images)

 - AUC (Area Under the Curve)
An evaluation index often used for anomaly detection.
ROC (Receiver Operating Characteristic) The area corresponding to the lower part of the curve.
The closer the AUC is to 1, the higher the performance of the model. (If predicted completely randomly, the AUC will be 0.5.)
I downloaded the score result CSV and calculated the AUC.

<br>
# Experimental results

The table below shows the results of creating a deep distance learning (DML) model with ADFI for all datasets.

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

The average learning time is about 11 minutes.

The average test time is about 4 seconds.

The average AUC is 0.947.
Very good results with AUC above 0.9 for datasets other than Cable and Screw.

<br>
## Performance comparison with methods of deep metric learning

I compared the AUC of the model of ADFI and the AUC of the model created by each method of deep metric learning without using ADFI.

AUCs of each method in the MVTec dataset:


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

It is not possible to simply give a superiority or inferiority because the experimental settings are different.

But the AUC values of ADFI are the highest in many datasets.

See also [the previous article for ADFI](https://dev.to/umapyoi/image-anomaly-detection-how-to-create-models-quickly-and-easily-i9l).

https://dev.to/umapyoi/image-anomaly-detection-how-to-create-models-quickly-and-easily-i9l
Angrymals P2E on the Solana Blockchain
Tags: nft, metaverse, blockchain, crypto
Published: 2022-03-12 10:54:37

🐷 Angrymals P2E on the Solana Blockchain!

Have you heard of Angrymals? They are minting on March 15th and have a P2E game that you can already play on mobile. I had a play and its super fun and addictive. I think it could be the next big P2E project

The Quirkiest Play-to-Earn PvP Game
Inspired by Worms and Angry Birds, this new crazy videogame lets you challenge your friends with a barrage of carrots, exhausts and sperm whales! Blockchain integration will enable Angrymals to bring its game to the next level and expand to new audiences


Fully Developed and User-Tested Gameplay
You will take control of a team of three crazy Angrymals garrisoned inside a fortress of junk. Shot after shot, the players will fling junk at each other to smash open the fortress and take down the other team.
Games are played 1v1 between two players. Players each take control of a team of three customized Angrymals firing a huge range of absurd weapons at each other to destroy the enemy fortress and knock out the opponent’s Angrymals.

Play in the app store today!
https://apps.apple.com/us/app/angrymals/id1513545169
https://play.google.com/store/apps/details?id=com.sionera.angrymals.one

https://twitter.com/angrymals?s=21
https://discord.gg/angrymals
https://angrymals.io/
Creating Membership Website
Tags: membershipsite, beginners
Published: 2022-03-12 10:50:36

In this E-Book you will learn how to create a membership website. Membership website is a content restricted website where users needs to pay to join the membership and access the content. **Membership website can be of any type like services, value added service, videos, streaming, articles, audios, e-books, software or applications etc**.

**Description:** Inside this eBook, you will discover the topics about the benefits of membership sites, what kind of site to make, background on using word press to set up the site, wp-member and using ClickBank for payment processing.

This E-Book Contains 31 Pages.

## Table of Contents
**Chapter 1:**
The Benefits Of Membership Sites
**Chapter 2:**
What Kind Of Site To Make
**Chapter 3:**
Background On Using Word Press To Set Up The Site
**Chapter 4:**
wp-Member
**Chapter 5:**
Using Clickbank For Payment Processing
Wrapping Up

Download [This E-Book here](https://www.w3courses.org/how-to-create-a-membership-website/)

---

Please like share and give positive feedback to motivate me to write more.

For more tutorials [visit my website](https://www.w3courses.org/tutorials/).

Thanks:)
Happy Coding:)
Lineer ve Lineer Olmayan Veri Yapıları
Published: 2022-03-12 10:20:43

## Lineer [Doğrusal] Veri Yapıları 

- Veri öğeleri birbiri ardına sıralı olarak düzenlenir. 
- Tüm öğeler tek katmanda bulunur.
- Tek seferde geçilebilir. Yani, ilk elemandan başlarsak, tüm elemanları sırayla tek bir geçişte geçebiliriz.
- Bellek kullanımı verimli değil.
- Veri boyutu ile zaman karmaşıklığı artar.
Örnek: Arrays, Stack, Queue [Popüler Olanları]

**1. Array [Dizi] Veri Yapısı**

Bir dizide, bellekteki öğeler sürekli bellekte düzenlenir. Bir dizinin tüm elemanları aynı tiptedir. Ve diziler biçiminde saklanabilecek öğelerin türü, programlama dili tarafından belirlenir.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cef4g8gcz6dcm8ip3ka7.png)
 
**2. Stack [Yığın] Veri Yapısı**

Yığın veri yapısında, elemanlar LIFO ilkesinde saklanır. Yani, bir yığında depolanan son eleman önce kaldırılacaktır.
LIFO -> Last in First Out [Son giren ilk çıkar]
Tıpkı yığında tutulan son plakanın ilk önce kaldırılacağı bir plaka yığını gibi çalışır.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/allhgihc0j7w1ai92iqy.png)
 
**3. Queue [Kuyruk] Veri Yapısı**

Yığından farklı olarak, kuyruk veri yapısı, kuyrukta depolanan ilk öğenin önce kaldırılacağı FIFO ilkesine göre çalışır.
Tıpkı kuyruktaki ilk kişinin bileti önce alacağı bilet gişesindeki bir insan kuyruğu gibi çalışır.

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

## Lineer [Doğrusal] Olmayan Veri Yapıları

Tıpkı yığında tutulan son plakanın ilk önce kaldırılacağı bir plaka yığını gibi çalışır.

- Veri öğeleri sıralı olmayan bir düzende (hiyerarşik şekilde) düzenlenir.
- Veri öğeleri farklı katmanlarda bulunur.
- Birden fazla çalıştırma gerektirir. Yani, ilk elemandan başlarsak, tüm elemanları tek bir geçişte geçmek mümkün olmayabilir.
- Farklı yapılar, ihtiyaca bağlı olarak belleği farklı verimli şekillerde kullanır.
- Zaman karmaşıklığı aynı kalır.
- Örnek: Tree, Graph, Map [Popüler Olanları]
 

**1. Tree [Ağaç] Veri Yapısı**

Bir grafiğe benzer şekilde, bir ağaç da bir köşeler ve kenarlar topluluğudur. Ancak ağaç veri yapısında iki köşe arasında yalnızca bir kenar olabilir.

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

**2. Graph [Graf] Veri Yapısı**

Grafik veri yapısında her bir düğüme köşe adı verilir ve her bir köşe diğer köşelere kenarlar aracılığıyla bağlanır.

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



Kaynakça: Programmiz.com Data Structures