teleren/devto huggingface dataset:
Few tips to improve WebPage Performance
Tags: performance, beginners, webdev, javascript
Published: 2021-09-11 16:38:07

## Points to be considered while optimizing the performance of a webpage:

* Images Optimisation
* Fonts Optimisation
* Optimizing CSS and JS

### Image Optimisation

* Choose the Right File Format (PNG, JPG, Webp, SVG, etc.)
* Compress the image appropriately
* Use appropriate dimensions for the image, also specify height and width attributes for the image
* Use Lazy loading for below-the-fold images. (You can use different 3rd party libraries like [Unveil](https://luis-almeida.github.io/unveil/), [lazysizes](https://github.com/aFarkas/lazysizes), etc.)

To achieve the above steps(except lazyloading) you can use the Cloudinary service. It will automatically serve the right file format and compress the image and serve the right quality based on the device.

### Fonts Optimisation

* Use woff2 file format.
* Use font display swap CSS property in the font face to ensure that fonts remain visible while the fonts get downloaded
* Import only required fonts.
* preconnect the font domain

  `<link rel="preconnect" href="https://fonts.googleapis.com">`
* preload the fonts as style as shown below:

  `<link rel="preload" href="https://use.typekit.net/gwu7gbd.css" as="style" onload="this.onload=null;this.rel='stylesheet'" />`
* Use only the required glyphs while loading the fonts. For example, I am using only alphabets on my website, then I can load the fonts as shown below:

  <https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap&text=ABCBEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyz>
* It's better to use the required Unicodes only while loading the fonts.

For more details on best practices, visit this [web.dev artcile](https://web.dev/font-best-practices/)

### Optimizing CSS

* Remove Unused CSS. You can refer to [this article](https://css-tricks.com/how-do-you-remove-unused-css-from-a-site/)  to know about the tools that can be helpful for removing unused CSS,
* Extract Critical CSS and inline the crititical CSS inside the `<head>` tag. Refer to [this article](https://web.dev/extract-critical-css/) to know about the tools that help you to identify the critcial CSS.
* Defer the Non Critical CSS. Refer to [this article](https://web.dev/defer-non-critical-css/#optimize) to know how to defer the unused CSS.

### Optimizing JS

* Defer unused JavaScript

  * Code-split your bundle into multiple chunks
  * Defer any non-critical JavaScript, including third-party scripts, using `async` or `defer`
* Minimize unused polyfills
* Use a web worker
* For More details on optimizing JS, you can refer to [this article](https://web.dev/optimize-fid/).
Meeting Open Source for the first time in my life :)
Tags: opensource, github
Published: 2021-09-11 16:35:44

This is Irene Park, a student from Seneca College. 
In this time of era, with a tons of sources and data available, Open Source was got me very interested with the point where we can collaborate. Using existing sources to implement an application was very attractive. 

I am based in Toronto, Canada. Even during time of Covid, I live in Toronto. My home is Toronto :)

I am looking forward to learn and collaborate with other students in the course. I want to implement a project that handles a big data if possible during the term. 

https://github.com/irenejoeunpark/tech-interview-handbook
Being honest, the title of the repo made me chose this. This repo has all useful algorithms, data structures and its implementations. With those source of study, it is helping developers with their technical interviews and also for practicing (for fun).
Why is my GitHub contribution not showing and how to fix it?
Tags: github, git, beginners, opensource
Published: 2021-09-11 16:24:02

Recently I started contributing to an open source project, I have probably made 20+ commits on that project by now and a lot of the pull requests that I have made got merged in the end.

But one thing I realised is that **I wasn't showing up as a contributor** of that project on the GitHub repo!

![Surprised pikachu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ico3klr4crc98biy7sdg.jpeg)

If you ever find yourself in the situation, it can get super annoying since you have put in all the blood sweat and tears into the project and now your contribution is ignored.

![Angry Pikachu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/33if69hqoi0yontqairy.gif)

^this is precisely how I felt, so I did a bunch of angry googling on the issue. And I realised that the problem is the following:

# My local git user email is different to my GitHub user email!

It appears that this is by far the most common reason why you are not showing up as an open source contributor even after your pull request got merged. Because GitHub doesn't recognise that it is you, my@emailaddress.com (your GitHub email) if you used myother@emailaddress.org instead to make your commit on your local git.

To change that, either add your email to your GitHub account in your GitHub settings, or change your local git email address by typing in the following in your command line:

```bash
git config --global user.email = "My@emailadress.com"
```

To check what email address you are currently using for your local git, you can type in the following command within one of your git repository:
```bash
cat .git/config
```

Another way to check is by typing:
```bash
git log
```
which gives you a more detailed version of all your commits and the corresponding email address for each one of them.

Now that you have aligned your local git email and your GitHub email, you will finally get your well deserved recognition for your open source contribution!

This would hopefully make you one heck of a happy pikachu!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9d4keveuhqksys1nklz.gif)

I hope this helps! This is just one of the reasons why you are not showing up as an open source contributor, if this doesn't work, you might have to find the [coder's best friend](google.com) for extra help.

As always, happy coding!
Lets talk (HTML) Tables!
Tags: html, tutorial, codenewbie, webdev
Published: 2021-09-11 16:19:46

Tables are visually appealing. Tables deliver information in such a way that is intuitive and user-friendly and easily consumed in a grid-style format. Information at a glance if you will. 

Lets look at how to use HTML to format a table. Each block (in the grid) is called a table cell. The `<table>` element is used. Tables are written out row by row. To start out each row you will use the `<tr>` tag which stands for the table row. Inside the `<tr>` will be a series of `<td>` elements. `<td>` stands for table data. Each representing a row cell. After each cell, make sure to add a closing tag (`</td>`).

For example:

`<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>`

the result:
123
456

Happy Coding!
Mocking using pytest
Tags: python, beginners, unittest, pytest
Published: 2021-09-11 16:19:21

**Pytest** is a unit test module in python.
**Mocking** is a way of mimicking the working of a service in 
a way to substitute for the real one.
 
In this post I'll be focussing on mocking different types of methods present in a class. 

Class ABC has been defined in a python file python_class.py

```python
class ABC:

    def call(self):
        self.static_method()
        ABC.class_method()
        self.instance_method()
        self._ABC__private_instance_method()
        ABC._ABC__private_class_method()
        ABC._ABC__private_static_method()

    @staticmethod
    def static_method():
        print("static_method")

    @classmethod
    def class_method(cls):
        print("class_method")

    def instance_method(self):
        print("instance method")

    def __private_instance_method(self):
        print("private instance method")

    @classmethod
    def __private_class_method(cls):
        print("private class method")

    @staticmethod
    def __private_static_method():
        print("private static method")
```

Yeah I know this isn't how class methods and static methods should be used, but that's not on today's agenda.

In the call method, we can see that there are 6 other methods being called. That's where we need to **mock the methods - the place where they're being called/being used** instead of where they've been defined.

But before that we need to install 2 packages: pytest, pytest-mock

```python
from unittest.mock import Mock
from python_class import ABC


class TestPythonClass():
    def test_all_methods(self, mocker):
        directory = "python_class.ABC"
        instance_mock = mocker.patch(f"{directory}.instance_method", return_value=Mock())
        static_mock = mocker.patch(f"{directory}.static_method", return_value=Mock())
        class_method_mock = mocker.patch(f"{directory}.class_method", return_value=Mock())
        pvt_instance_mock = mocker.patch(f"{directory}._ABC__private_instance_method", return_value=Mock())
        pvt_class_mock = mocker.patch(f"{directory}._ABC__private_class_method", return_value=Mock())
        pvt_static_mock = mocker.patch(f"{directory}._ABC__private_static_method", return_value=Mock())
        
        ABC().call()

        assert instance_mock.call_count == 1
        assert static_mock.call_count == 1
        assert class_method_mock.call_count == 1
        assert pvt_instance_mock.call_count == 1
        assert pvt_class_mock.call_count == 1
```

**mocker** is a fixture that is shipped with the pytest-mock module. We can simply pass it on as an argument during the test method definition without importing.

In this way I've mocked 6 different types of methods:
  * instance method
  * class method
  * static method
  * private instance method
  * private class method
  * private static method


Lemme know in case I missed something or I need to add anything.
Adding Font Awesome Pro to your CI/CD Pipeline using GitHub Actions and Azure
Published: 2021-09-11 15:35:50

---
title: Adding Font Awesome Pro to your CI/CD Pipeline using GitHub Actions and Azure
published: true
description: How to add Font Awesome Pro via npm to a Nuxt.js project and deploy it to Azure with GitHub Actions
tags: 
//cover_image: https://direct_url_to_image.jpg
---

I've been working on an SSR flavored Nuxt.js app that needed to leverage [Font Awesome Pro](https://fontawesome.com). Font Awesome has excellent documentation how to install Font Awesome Pro with npm or yarn locally, but I needed to make a few tweaks to get it to play nicely with our particular app and CI/CD flavors. 

This post assumes you already have a working [Nuxt.js](https://nuxtjs.org) SSR app deployed to [Azure](https://azure.microsoft.com) with [Github Actions](https://docs.github.com/en/actions). 

First, since we are leveraging CI/CD, we want to set Font Awesome Pro up on a per project basis, so we need to create a .npmrc file in the root of our project.  

Contrary to the instructions provided, since we are leveraging Github Actions and Azure as part of our CI/CD pipeline our .npmrc file should *only* contain `@fortawesome:registry=https://npm.fontawesome.com/`  

Next, we need to install Font Awesome Pro locally by running ```FONTAWESOME_NPM_AUTH_TOKEN=YOUR_OWN_TOKEN_HERE npm install --save @fortawesome/fontawesome-pro```

Then, we need to set up the Font Awesome Pro Token as a [GitHub Secret](https://docs.github.com/en/actions/reference/encrypted-secrets) on our repo, so click on over to secrets on your repo and add your key there and click save. 

Next, we need to adjust the GitHub Actions workflows yaml file in our local branch to be able to reference our key in the CI/CD pipeline, as follows:  
```- name: Install dependencies using a safe clean install, build and test
  run: |
    npm config set '//npm.fontawesome.com/:_authToken' "${{ secrets.FONTAWESOME_NPM_AUTH_TOKEN }}"
    npm ci --ignore-scripts```  
Note, in our yaml file, [the pipe](https://yaml-multiline.info) after our `run:` is a block scalar that indicates new lines in our block should be preserved. 

Finally, let your scripts deploy your app to Azure and enjoy your lovely Font Awesome Pro icons.  

I hope this helps folks who run in to some of the same issues I did on first go round with these frameworks and services.
LEVEL UP with JavaScript! LVL 6
Tags: javascript, webdev, tutorial, beginners
Published: 2021-09-11 15:28:32

### In this blog series tutorial, I will be covering some of the basic JavaScript programming concepts.

This is geared toward beginners and anyone looking to refresh their knowledge.

### See the [<strong>Previous Level Here</strong>](https://dev.to/devcronin/level-up-with-javascript-lvl-5-1406 )

Level 6 will cover: 

* Use Bracket Notation to Find the Nth Character in a String
* Use Bracket Notation to Find the Last Character in a String
* Use Bracket Notation to Find the Nth-to-Last Character in a String



## Use Bracket Notation to Find the Nth Character in a String

If we want to find which character of a string is sitting at a particular value, we again use bracket notation with the number position we want to find [Nth].

```JavaScript

let player = "Druid";

console.log(player[2]);

"u"

```

## Use Bracket Notation to Find the Last Character in a String

When we want to find the last character of a string, we can subtract one from the string's length.

```JavaScript

let spell = "Fireball";

spell[spell.length - 1];

"l"

```

## Use Bracket Notation to Find the Nth-to-Last Character in a String

Just as we did before to find the Nth and the last character in a string, we can combine the two to find the last to Nth character.

```JavaScript

let enemy = "Goblin Mage";

let secondToLastLetter = enemy[enemy.length - 2];

console.log(secondToLastLetter);

"g"

```




### Thank you for reading my blog! This is the sixth of my series on JavaScript so if you would like to read more, please follow!


### See the [<strong>Next Level Here</strong>](https://dev.to/devcronin/level-up-with-javascript-lvl-7-l04-temp-slug-2957750)


## [<strong>Support and Buy me a Coffee</strong>](https://www.buymeacoffee.com/ZachCronin)
How not to include internal code in ts declaration file
Tags: typescript, webdev, javascript
Published: 2021-09-11 15:15:37

Typescript provides a mechanism to not include internal code in a declaration file. It can be useful for building a public library.

We can use the `stripInternal: true` property in our tsconfig.json file. This will enable typescript compiler to check the `/** @internal */` *JS DOC comment*.

#### main.ts
Add the `/** @internal */` *JS DOC comment* .
By default typescript compiler will ignore this comment but we can enable it in tsconfig.json file.

```javascript
/** @internal */
function init() {
  console.log('Hello!!')
}

```
#### In tsconfig.json
```json
{
  "compilerOptions": {
    "outDir": "./dist",
    "declaration": true,
    "stripInternal": true
  }
}
```

Compile and check your declaration `main.d.ts`(in this case it will have the same name as main.ts file) file to not include the init function declaration.
JavaScript Rest-API with CRUD Operations 2021 | Rest-API for Beginners 2021
Tags: javascript, node, express, crudoperations
Published: 2021-09-11 14:47:23

Hey Guys, In this video I clearly explained step by step how to create <b>RestAPI</b> using <b>JavaScript</b>, <b>NodeJS</b> and Express Server.

More importantly , I implemented all the <b>Curd</b> the operations from scratch and make it easy for <b>beginners</b> to understand the concepts easily.

<b>Time line </b>❤️‍🔥❤️‍🔥
00:00 Introduction to Course
00:32 Prerequisites for this Course
00:52 Tools Required
01:37 Create New Project
03:40 Install Express Sever and Nodemon

CRUD Operations ❤️‍🔥❤️‍🔥
— — — — — — — — — — — — — — — —
05:40 Read Operation- simple string
09:47 Testing Get Method using Post Man
11:53 Returning Array of Users Data
13:10 Wrap the Data in JSON
15:11 Create Module and Separation of Code
18:02 Read Data(Users data) from File
24:57 Search User
29:24 Create Operation
36:54 Update Operation
47:15 Delete Operation

Please watch complete video to get 100 % of it.
{% youtube k4HRR85Af-I %}
How to Check and Print Python Version?
Tags: python, programming, codenewbie, tutorial
Published: 2021-09-12 08:06:07

---
title: How to Check and Print Python Version?
published: true
date: 2021-09-11 14:42:04 UTC
tags: #python #programming #codenewbie #tutorial

canonical_url: https://itsmycode.com/how-to-check-and-print-python-version/
---

ItsMyCode |

In this tutorial, you will learn how to print the version of the current Python installation from the script.

## Print Python Version using sys Module

The sys module comes as a built-in utility with Python installation, and to check the Python version, use  **`sys.version`**  property.

```python 
import sys

# Prints current Python version
print("Current version of Python is ", sys.version)
```

**Output**

```python 
Current version of Python is 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)]
```

If you are looking for details on the version, such as major, minor, type of release, etc., you can use  **`sys.version_info` ** property.

The  **`version_info` ** property prints the Python version in tuple format, which gives detailed information as shown below.

```python 
import sys

# Prints current Python version
print("Current version of Python is ", sys.version_info)
```

**Output**

```python 
Current version of Python is sys.version_info(major=3, minor=9, micro=7, releaselevel='final', serial=0)
```

## Print Python Version using platform Module

The other alternative way is to use a platform module in Python where you can leverage the built-in function **`platform.python_version()`**  to print the current installed Python version in your machine.

```python 
import platform

# Prints current Python version
print("Current version of Python is ", platform.python_version())
```

**Output**

```python 
Current version of Python is 3.9.7
```

## Print Python version using command line

If you don’t want to write any script but still want to check the current installed version of Python, then navigate to shell/command prompt and type` python --version`

```python 
python --version

# Output 
# 3.9.7
```

The post [How to Check and Print Python Version?](https://itsmycode.com/how-to-check-and-print-python-version/) appeared first on [ItsMyCode](https://itsmycode.com).
Newbie frontend developer incoming
Tags: html, css, frontend, help
Published: 2021-09-11 13:29:31

Hey everyone,
This is my first post on any social platform, I would like to apologize 🙏 for any mistakes that I would have made.

I need the help of the community at this time. 
I am currently a computer science major student trying to pursue a career in web development, and I am having a problem mastering one of the most basic topics in web development i.e. HTML and CSS.

I have already taken a couple of courses from YouTube and other platforms teaching Html and CSS and I have a basic knowledge about Html and CSS.

The problem I am facing is that although I know how to use Html and CSS, I am having a lot of problems in applying these concepts to real-world projects. I have read many blogs suggesting replicating some websites as the best form of practice of Html and CSS and I have also done that, but the issue with these websites is I am unable to practice complex topics like forms and tables. For a time I found a resource https://devchallenges.io, 
the resource was very good but after completing the frontend part It only took me so far, and now I am running short on ideas on how to practice any further 

Please, I would like to ask for your help. Suggest me some way to overcome this plateau condition. Any website similar to https://devchallenges.io any other resource, idea, suggestion, anything would work 

Sorry for such a long post but any help would be appreciated.
IndexError: too many indices for array
Tags: python, programming, codenewbie, tutorial
Published: 2021-09-12 08:03:50

---
title: IndexError: too many indices for array
published: true
date: 2021-09-11 13:27:43 UTC
tags: #python #programming #codenewbie #tutorial

canonical_url: https://itsmycode.com/indexerror-too-many-indices-for-array/
---

ItsMyCode |

The **indexerror: too many indices for an array** means that you have a declared an array in a different dimension and trying to index it in another dimension.

For example, suppose you have declared a numpy array in a single dimension and try to access the elements of an array in 2 dimensional. In that case, you will get too many indices for array error, as shown below.

```python 
# Import the numpy library
import numpy as np

# Declaring and Initializing the one Dimension Array
numbers = np.array([10,20,30,40,50])

# Indexing and accessing array as 2D causes IndexError
print(numbers[0,2])
```

**Output**

```python 
Traceback (most recent call last):
  File "c:\Projects\Tryouts\Python Tutorial.py", line 8, in <module>
    print(numbers[0,2])
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
```

The above code is a classic example of indexerror: too many indices for an array. We have declared a single dimensional array in the code, but on the other hand, we are trying to print the array as a two-dimensional array.

### **How to fix indexerror: too many indices for array**

The resolution is pretty simple, where you need to make sure to re-check the dimension of an array you have declared and trying to index or access it in the same way. 

```python 
# Import the numpy library
import numpy as np

# Declaring and Initializing the one Dimension Array
numbers = np.array([10,20,30,40,50])

# Indexing and accessing array correctly
print("The array element is ",numbers[2])
```

**Output**

```python 
The array element is 30
```

## How to Check the dimension of a numpy array in Python?

If it’s a dynamic numpy array, you could also check the dimension of an array using the **`len() `**method, as shown below.

You can pass the numpy array shape to the **`len()`** function and return the array’s dimension. 

```python 
# Import the numpy library
import numpy as np

# Declaring and Initializing the one Dimension Array
numbers1d = np.array([10,20,30,40,50])

# Declaring and Initializing the one Dimension Array
numbers2d = np.array([[[10,1],[20,2],[30,3],[40.4],[50.5]]])

print("The array dimension is ", len(numbers1d.shape))
print("The array dimension is ", len(numbers2d.shape))
```

**Output**

```python 
The array dimension is 1
The array dimension is 2
```

The post [IndexError: too many indices for array](https://itsmycode.com/indexerror-too-many-indices-for-array/) appeared first on [ItsMyCode](https://itsmycode.com).