teleren/devto huggingface dataset:
Next.js: Replace React with Preact
Tags: react, preact, nextjs, performance
Published: 2021-02-28 08:07:33

One option to increase performance in production is to replace React with Preact. I can't take credit for this as in my case, I got the idea and code from [https://leerob.io/](https://leerob.io/).

Its' really simple to do, however a word of caution, this may not work if certain features of React are required in production. If you go down this route make sure you test fully before deploying to live.

To get started if you haven't already, create a `next.config.js` and include the following code

```jsx
module.exports = {
  webpack: (config, { dev, isServer }) => {
    // Replace React with Preact only in client production build
    if (!dev && !isServer) {
      Object.assign(config.resolve.alias, {
        react: 'preact/compat',
        'react-dom/test-utils': 'preact/test-utils',
        'react-dom': 'preact/compat',
      });
    }

    return config;
  },
};
```

The above checks that we are in production and the webpack function is being executed on the  client side. 

Don't forget to install Preact like i did, `yarn add preact` otherwise you'll get a build error for `Module not found: React`

Run `yarn build` to see the bundle size. I ran that before and after the changes, as you can see in the below screenshot the js size is about half:

**React**

![React bundle size](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ofujh67yaol82adcd9ot.png)

**Preact**

![Preact bundle size](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0g1mp5k842wmnpr1zap4.png)

## Preact difference to React

If you use the [preact-combat](https://github.com/preactjs/preact-compat) like in the example above then there is very little that isn't supported. For example, PropTypes are not supported in the core but are included in preact-combat. 

A full list of what is and isn't included or is different can be found on the Preact website: [https://preactjs.com/guide/v8/differences-to-react/](https://preactjs.com/guide/v8/differences-to-react/) 

## Resources

**Repositories**

- React: [https://github.com/dwhiteGUK/preact-bundle-test](https://github.com/dwhiteGUK/preact-bundle-test)
- Preact: [https://github.com/dwhiteGUK/preact-bundle-test/tree/preact](https://github.com/dwhiteGUK/preact-bundle-test/tree/preact)

**Demo**

- React: [https://preact-bundle-test.vercel.app/](https://preact-bundle-test.vercel.app/)
- Preact: [https://preact-bundle-test-7sh8vcshq-dwhite.vercel.app/](https://preact-bundle-test-7sh8vcshq-dwhite.vercel.app/)
Copying array of Objects is not that straightforward
Tags: csharp, oop, beginners, dotnet
Published: 2021-02-28 07:34:06

So, you want to copy an array to create another new array, and not just copying the array reference to another variable. In C#, there are several ways to achieve this. 
Some of the ways are:
+ `Array.CopyTo()`
+ `Array.ConstrainedCopy()`
+ `Array.Clone()`

These ways provide you with a new array that is different from the original array and not just two variables with the same reference.

But, any object when created, is created in the heap and it's address is assigned to the reference variable. 

For example:
`Student s1 = new Student()`

Here, `new Student()` is the creation of an Student object in the heap, and `s1` holds its address.

Same happens in an array. An array of objects or any complex type consists of reference variables holding the addresses of the actual objects present in the heap.

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

As, we can see from the image, we can now understand that when we copy a similar array, we end up with a new array but with the elements holding addresses, or references to the same objects.

Now, if we want a new set of objects with the same data, we may need to recreate the objects linearly. We can use the `Array.ConvertAll()` method for that purpose.

Refer to [this](https://www.telerik.com/blogs/copying-and-cloning-arrays-in-c) article by **Peter Mbanugo** for more details on the methods mentioned in this article.

> Note: This only applies to array of complex types. Array of primitive types will contain values as opposed to complex types which have references. So copying an array of primitive types will have no issues to deal with.
Two weeks in! 100 Bytes Of Wisdom: Day 14
Tags: career, journey, advice
Published: 2021-02-28 07:14:57

---
title: Two weeks in! 100 Bytes Of Wisdom: Day 14
published: true
description: Bytes of Wisdom is a new project by Sam Jarman that brings together snippets of advice for software engineers
tags: career, journey, advice
//cover_image: https://direct_url_to_image.jpg
---

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

This byte of wisdom from [@sammio2](https://twitter.com/sammio2) on Twitter talks about trying to keep your code simple and lean. Write no more (or no less) code than you need. If you can avoid writing something without compromising quality or features, then do so. The more code you have, the higher the chances for bugs and the higher cost to maintain. New devs can often get carried away writing something that wasn't asked for because they were in the moment and having fun. That's ultimately bad engineering and gives your team a burden to carry forward.

Heads up: As with any terse bit of advice, there will be exceptions of course, and subtleties and nuance that can't possibly be captured in a Byte of Wisdom. This has been what I've experienced, I'd love to hear yours in the comments too!

You can catch up with all the other bytes at http://bytesofwisdom.com/
100 Bytes Of Wisdom: Day 13
Tags: career, journey, advice
Published: 2021-02-28 07:08:46

---
title: 100 Bytes Of Wisdom: Day 13
published: true
description: Bytes of Wisdom is a new project by Sam Jarman that brings together snippets of advice for software engineers
tags: career, journey, advice
//cover_image: https://direct_url_to_image.jpg
---

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/44i4w92ynebyzjtv9ef1.png)

When entering data for testing, it's best to use ones that will never work or ones, that if they're ever used, will result in no real-world effect. This includes using real phone numbers, emails and postal addresses. My tip for emails is to use one on your own domain, eg test@mycompany.com. 
This of course may never be an issue, but it's a good habit to get into to be safe rather than sorry.

Heads up: As with any terse bit of advice, there will be exceptions of course, and subtleties and nuance that can't possibly be captured in a Byte of Wisdom. This has been what I've experienced, I'd love to hear yours in the comments too!

You can catch up with all the other bytes at http://bytesofwisdom.com/
Windows command line cheatsheet
Tags: programming, cmd, windowscommandline, codenewbie
Published: 2021-02-28 06:45:06

 
1. Go forward : `cd path\to\folder`
2. Go backward : `cd ../..`
3. Show lists of files and directories : `dir`
4. Show lists of files and directories with hidden files also : `dir /a`
5. Clearing screen : `cls`
6. Show specific type of files: `dir *.png | dir *.jpg`
7. Help for a specific command: `ipconfig /?` | `cls /?`
8. Create a new directory : `mkdir myDir` | `mkdir path\to`
9. Remove or delete directories: if your directory is empty `rmdir myDir` else `rmdir /S myDir`
10. Changing drivers : `C:` | `D:`
11. Show path variables: `path`
12. Show available drive names: `wmic logicaldisk get name`
13. Change color: `color 0B | color 90`  or back to default just use `color`
14. Creating a file : `echo somecontent > file.txt`
15. Deleting file: `del filename.ext`
16. Reading contents of a file: `type file.ext`\
17. Override to a file : `echo newcontent > samefile.ext`
18. Appending to a file : `echo appendingcontent >> samefile.ext`
19. Copying files: `copy test.txt mydir`
Understanding Iterations & Enumerators
Published: 2021-02-28 06:15:11

Staring my first CLI project I notice I was falling behind on iterations which made things hard to even get my code started. follow and join me on my journey of going back to review the lessons of iteration and Enumerators in ruby.


Starting with the word iteration itself - means that is a way to operate on a collection object, like an array, and do something with each element in that collection. I notice there are different types of iterations and Enumerators for example; EACH, COLLECT/MAP, FIND/DETECT FIND_ALL/SELECT, let's go over these iterations, and Enumerators find out how they operate.

Starting with Each, this iterator is just another method of an object. the main feature is that iterates on each element of the collection always returning the original collection. you can use it also on an array, hashes, and range. see below example,

  [ 1, 2, 3 ].each { |n| puts n }
1
2
3
 => [1, 2, 3] 

The next iteration that will be looking at is Collect/Map these two iterations are aliases that can be used interchangeably. It passes each collection item to the block and returns a new collection containing the values returned by the block. see below example,

a = [ "lydia", "Anthony", "mike" ]

a.map { |x| x.upcase } 

 =>  ["LYDIA", "ANTHONY", "MIKE"] 




Now let's take a look at the next ones, select/find_all these methods will not do calculations on collection, but it will allow us to select specific elements from the base collection based on logical conditions. If an element of the collection will fulfill the condition, then it will stay in the collection. If no, element will be removed from the collection. see below example


           array = [1,2,3,4,5,6]

array.select {|num| num.even?} => [2,4,6]
array.find_all {|num| num.even?} => [2,4,6]


This Enumerator is very useful when you want to choose only a specific group of elements. You are not interested in all collection, but with a small part of it. but only when it comes to arrays, we can use .select and .find_all interchangeably.

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


but When it comes to iterating over hashes, this is when we see the difference between .select and .find_all. 

       hash= {a:1,b:2,c:3,d:4,e:5,f:6}

hash.select {|key,value| value.even?} 
=> {:b=>2, :d=>4, :f=>6}

hash.find_all {|key,value| value.even?} 
=>[[:b, 2],[:d, 4],[:f, 6]]



Notice in the above example how .select  returns the value in the original input in this case a hash. but .find_all return the key: value pairing in an array. so .find_all output is always an array.

So far we already know how iterations and Enumerator work! having this understanding help me figure out how I was going to manipulate my data that I scraped on an API. and gave my project a solid ground to rise up. Thank you for following throughout on this journey now we have an understanding of iterations and Enumerators. 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2d3owcldkatfp7pjh87t.png)
Introduction to Tesseract & Pytesseract
Published: 2021-02-28 06:04:30

Hi! I'm my video I explain what Tesseract is and how you can use it. Tesseract is a tool for extracting text from images.

{% youtube BK4mejo8uK0 %}

➤ Github Tesseract: https://github.com/tesseract-ocr/tesseract
➤ Github PyTesseract: https://github.com/tesseract-ocr/tesseract

➤ Timestamps:
0:00 Introduction
0:26 What is Tesseract?
0:57 Install and use Tesseract
2:47 Install and use pyTesseract
A New Way to Draft MTG
Published: 2021-02-28 05:57:17

In part, this project was motivated by self serving means. Magic the Gathering has always had the corner on the market regarding high fantasy trading cards and collectables; while additionally having a vast competitive scene. Part of that competitive landscape is a popular format that its subdivisions all fall under the label of 'limited' which involves deck construction on the spot from a limited pool of cards. Anyone who has played the game above the very most casual level can tell you that Magic (MTG) is heavily pay-gated at every step. Drafting or limited is one of the formats that can circumvent the general level of expense, however it largely costs $20 minimum to draft either digitally or in person. 

The Cube Draft CLI project is functionally a free limited draft program, I've included a data/cube.txt file in the repo which is an accurate representation of the 'vintage-cube'; one of the more coveted limited card pools, which is unthinkably expensive in paper magic. The project simulates the experience of sitting down and drafting magic through the command-line-interface. Players are able to shuffle up the shared card pool, each draws 15 at random and begins selecting their deck. Players are able to grab pertinent pieces of information from individual cards that are displayed with index to the player.

The def_lookup! method really disciplined my coding toward being as informed as possible regarding my objects and their assigned attribute accessors from the API. Binding.pry was not only instrumental in my understanding of exactly what these objects qualities looked like, but it was nigh requisite. I spent a great deal of time trying to figure out why it is my color assignment method wasn't functional. I knew these objects had a key value pair for [:colors] and I foolishly assumed it was simply a string that looked like "red". I was confident to the degree that I looked absolutely everywhere else but precisely my problem. A simple binding.pry underneath puts "Cmc: #{card.cmc}" informed me to my dismay that it was ["Red"]. Sometimes a simple return to the basics will humble your process. 

Despite being fairly harrowing overall at first, the road blocks and dysfunctional methods overall led to the solidification of a great deal of our materials for phase-1. The cliche' of the blank page is more real that it isn't, certainly for your first program. Once the program was constructed in a meaningful way, I rather enjoyed incorporating a small number of flourishes to the CLI, for instance coloring the text of a card in its corresponding color in MTG. The net result is something I'm proud to have done, and excited to share.
821. Shortest Distance to a Character
(javascript solution)
Tags: algorithms, javascript
Published: 2021-02-28 05:33:11

###Description:
Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.

The distance between two indices i and j is abs(i - j), where abs is the absolute value function.


###Solution:
Time Complexity : O(n)
Space Complexity: O(n)

```javascript
// Scan twice, one time starting at the front and another starting at the back
// Populate the answer array with Infinity as a place holder until we find an index of 'c'
// Find the distance between the current index and the previous index of 'c' 
// The final 'ans' array will be populated with the smallest difference found at each position between the two approaches of scanning from the front and scanning from the back
var shortestToChar = function(s, c) {
    const N = s.length;
    const ans = new Array(N);
    let prev = -Infinity;
    
    // Populate difference from starting from the front
    for (let i = 0; i < N; ++i) {
        if (s[i] === c) prev = i;
        ans[i] = i - prev;
    }
    
    // Populate the 'ans' array with the min difference between starting from the front and starting from the back
    prev = Infinity;
    for (let i = N-1; i >= 0; --i) {
        if (s[i] === c) prev = i;
        ans[i] = Math.min(ans[i], prev - i);
    }

    return ans;
};
```
Images disappear upon scrolling flatlist 
Published: 2021-02-28 05:10:14

I'm using clojurescript for react native. The code essentially compiles to javascript. I have a flat-list like so:
```
[flat-list {:refreshControl
                  (r/as-element
                   [refresh-control {:refreshing @(subscribe [:refreshing])
                                     :onRefresh #(dispatch [:load-videos])}])
                  :data (reverse @(subscribe [:videos]))
                  :renderItem (fn [item]
                                (r/as-element
                                 [video-press (get (js->clj item) "item")
                                                        navigation]))
                  :keyExtractor (fn [item] (str (random-uuid)))}]
```
where video-press is the following:
```
(defn video-press [video navigation]
  (js/console.log "video is" video)
  (js/console.log "thumbnail is " (get video "thumbnail"))
  [pressable {:key (random-uuid)
              :style {:borderWidth 1
                      :borderColor :gray
                      :height 300
                      :margin 1
                      :marginTop 3
                      :marginBottom 3
                      }
              :onPress #(doall
                         (.navigate navigation :Video)
                         (dispatch [:show-info video]))}
   [image {:source {:uri (str "https://d211alragp6msc.cloudfront.net/"
                              ;;"https://d1i5nt38vlltuu.cloudfront.net/"
                              (get video "thumbnail"))}
           #_{:uri (get video "photo")} :style {:height "80%" :width "100%"
                                                :resizeMode :contain}}]
   [view {:style {:flex 1 :flexDirection :column}}
    [text {:style {:fontWeight :bold}} (get video "title")]
    [view {:style {:flex 1 :flexDirection :row}}
     [image {:source {:uri (get video "photo")}
             :style
             {:height 40
              :width 40
              :borderRadius 1000}}]
     [text {:style {:margin 5}} (get video "name")]]]
   #_[:> Text {:style {:fontSize 20}} (get video "name")]
   #_[:> Text (get video "description")]]
  )
```
However, upon scrolling the flatlist, I’m seeing the images disappear. Moreover, the images take a long time to show as well. How do I fix this?
Laravel Middleware Untuk Akses Route Berdasarkan Role
Tags: laravel, middleware
Published: 2021-02-28 05:07:11

Hallo semua ini adalah tulisan pertama saya di DEV, pada tulisan pertama ini saya ingin memberikan tutorial sederhana, yaitu penggunaan middleware pada laravel untuk membatasi user yang dapat mengakses route berdasarkan role yang dimiliki, tanpa basa basi lagi langsung saja keintinya. Disini saya asumsikan teman - teman semua sudah memiliki project laravel.

Langkah Pertama, Buka terminal dan masuk ke path projek yang ingin kamu implementasikan trik ini

![Direktori Projek](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wowhlufm1kzs5ooqdb0m.png)

pada gambar diatas saya menuju ke direktori dimana projek saya disimpan, untuk direktori ini relatif dimana teman - teman meyimpan projek nya

Setelah Melakukan Langkah Diatas,ketikan perintah berikut pada terminal

![Pembuatan Middleware](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i6a6o03aknfn3ifvckzl.png)

# Membuat Middleware
perintah ini berguna untuk membuat middleware baru, middleware ini akan disimpan dalam direktori App\Http\Middleware. Sebelum bisa menggunakan middleware kita harus registrasikan middleware ini pada file Kernel.php

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

perhatikan 
'admin' => \App\Http\Middleware\Admin::class,
ini merupakan cara untuk meregistrasikan middleware pada laravel.

setelah itu buka file is_admin.php atau Admin.php pada App\Http\Middleware, lalu ketikan code dibawah ini

![Admin Middleware](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmod98dqbtmjz4s2qdwy.png)

# Penjelasan Code
yang berada didalam block if adalah code yang akan dieksekusi jika syarat terpenuhi dimana syaratnya adalah harus memiliki role sebagai admin, dan yang didalam block else adalah perintah yang akan dieksekusi jika tidak ada syarat yang terpenuhi dimana dalam skenario ini kita akan melakukan redirect terhadap user yang bukan admin ke url sebelumnya dia berada.

# Penggunaan Middleware
1. ![Cara 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mw8jtp12es2onduu6pt.png)
2. ![Cara 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5oxpkjl3ny28x2qehubr.png)
Day 50,51,52:100DaysOfCode
Tags: 100daysofcode, productivity, programming
Published: 2021-02-28 04:34:38

best day,,
hashcode day...solved the problem with the total score of 7,888,092 points.
we ranked 4104 worldwide and 1201 in India which was way good than our last year's performance.

studied priority queue and its app ...

started with striver sliding window ques...solved a few will try to complete it by today :),

gave uber hacktag coding round solved 3 out of 4 ques in the first set on codesignal platform ...

it was a good round with one easy 2 medium and one hard question.
studied spring boot further...did some work on ongoing flutter project.

(PS: I just completed 50 days)

You can Follow me->
https://github.com/singhtaran1005
https://www.linkedin.com/in/taranpreet-singh-chabbra-27517918a/
CSS decoded ::before and ::after
Tags: css, html, webdev, ux
Published: 2021-02-28 04:25:12

# What is a **Pseudo Element** in CSS?

A CSS **Pseudo Element** is a keyword added to a selector that lets you style a **_specific part_** of the selected element(s). For example, `::first-line` can be used to style the first line of a paragraph, `::before` can be used to prepend an element and style it as well, etc.

The main utility of the **Pseudo Element** is for cosmetic purpose only.

In CSS3 the **Pseudo Elements** are represented by `::<pseudo-element>`, even though the CSS2 syntax `:<pseudo-element>` still works on most browsers for the **Pseudo Elements** that were available in CSS2.

# What is the use of `::before` and `::after`?

In CSS, `::before` and `::after` creates pseudo-elements that is the prepended and appended to the selected element respectively.

# How do I use `::before` and `::after` in my website?

One really important thing to keep in mind while using `::before` and `::after` is to set `content` property in the css

```css
selector::before{
  /* without content the pseudo-elements will not work */
  content: "";
}
```

After adding the content, you can style them just like any other element

Some simple examples of how `::before` and `::after` can bring you website to life are given below.

## Quotes

Adding opening and closing quotes from CSS using `::before` and `::after`. The **quote** class can be used on any element to add quote-like styling.

{% codepen https://codepen.io/ruppysuppy/pen/rNWJPbR %}

## Underline on Hover

CSS `::after` is used to create an animated underline for links on hover (style prevalent in navlinks).

{% codepen https://codepen.io/ruppysuppy/pen/ExNQrOz %}

## Info on Hover

CSS `::after` is used to create animated info displaying on hover (similar to the popups in **Hacker Earth** and **Leet Code**).

{% codepen https://codepen.io/ruppysuppy/pen/rNWdWNp %}

Finding **personal finance** too intimidating? Checkout my **Instagram** to become a [**Dollar Ninja**](https://www.instagram.com/the.dollar.ninja/)

# Reference

### MDN Web Docs

  1. [Pseudo-elements](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements)
  2. [::before](https://developer.mozilla.org/en-US/docs/Web/CSS/::before)
  3. [::after](https://developer.mozilla.org/en-US/docs/Web/CSS/::after)

# Thanks for reading

Reach out to me on:

-   [Portfolio](https://tapajyoti-bose.web.app)
-   [GitHub](https://github.com/ruppysuppy)
-   [LinkedIn](https://www.linkedin.com/in/tapajyoti-bose-429a601a0)