Shubham Ankit

Shubham Ankit

1563259974

A beginner’s guide to Docker — how to create your first Docker application

After a short introduction on what Docker is and why to use it, you will be able to create your first application with Docker.

What is Docker?

Docker is a free software developed by Docker Inc. It was presented to the general public on March 13, 2013 and has become since that day a must in the world of IT development.

It allows users to create independent and isolated environments to launch and deploy its applications. These environments are then called containers.

This will let the developer run a container on any machine.

As you can see, with Docker, there are no more dependency or compilation problems. All you have to do is launch your container and your application will launch immediately.

But, is Docker a virtual machine?

Here is one of the most asked question about Docker. The answer is: actually, not quite.

It may look like a virtual machine at first but the functionality is not the same.

Unlike Docker, a virtual machine will include a complete operating system. It will be independent and act like a computer.

Docker will only share the resources of the host machine in order to run its environments.

Why use Docker as a developer?

This tool can really change a developer’s daily life. In order to best answer this question, I have written a non-exhaustive list of the benefits you will find:

  • Docker is fast. Unlike a virtual machine, your application can start in a few seconds and stop just as quickly.
  • Docker is multi-platform. You can launch your container on any system.
  • Containers can be built and destroyed faster than a virtual machine.
  • No more difficulties setting up your working environment. Once your Docker is configured, you will never have to reinstall your dependencies manually again. If you change computers or if an employee joins your company, you only have to give them your configuration.
  • You keep your work-space clean, as each of your environments will be isolated and you can delete them at any time without impacting the rest.
  • It will be easier to deploy your project on your server in order to put it online.

Now let’s create your first application

Now that you know what Docker is, it’s time to create your first application!

The purpose of this short tutorial is to create a Python program that displays a sentence. This program will have to be launched through a Dockerfile.

You will see, it’s not very complicated once you understand the process.

Note: You will not need to install Python on your computer. It will be up to the Docker environment to contain Python in order to execute your code.#### 1. Install Docker on your machine

For Ubuntu:

First, update your packages:

$ sudo apt update

Next, install docker with apt-get:

$ sudo apt-get install docker-ce

Finally, verify that Docker is installed correctly:

$ sudo docker run hello-world

2. Create your project

In order to create your first Docker application, I invite you to create a folder on your computer. It must contain the following two files:

  • A ‘main.py’ file (python file that will contain the code to be executed).
  • A ‘Dockerfile’ file (Docker file that will contain the necessary instructions to create the environment).

Normally you should have this folder architecture:

.
├── Dockerfile
└── main.py
0 directories, 2 files

3. Edit the Python file

You can add the following code to the ‘main.py’ file:

#!/usr/bin/env python3

print("Docker is magic!")

Nothing exceptional, but once you see “Docker is magic!” displayed in your terminal you will know that your Docker is working.

3. Edit the Docker file

Some theory: the first thing to do when you want to create your Dockerfile is to ask yourself what you want to do. Our goal here is to launch Python code.

To do this, our Docker must contain all the dependencies necessary to launch Python. A linux (Ubuntu) with Python installed on it should be enough.

The first step to take when you create a Docker file is to access the DockerHub website. This site contains many pre-designed images to save your time (for example: all images for linux or code languages).

In our case, we will type ‘Python’ in the search bar. The first result is the official image created to execute Python. Perfect, we’ll use it!

# A dockerfile must always start by importing the base image.
# We use the keyword 'FROM' to do that.
# In our example, we want import the python image.
# So we write 'python' for the image name and 'latest' for the version.
FROM python:latest

# In order to launch our python code, we must import it into our image.
# We use the keyword 'ADD' to do that.
# The first parameter 'main.py' is the name of the file on the host.
# The second parameter '/' is the path where to put the file on the image.
# Here we put the file at the image root folder.
ADD main.py /

# We need to define the command to launch when we are going to run the image.
# We use the keyword 'CMD' to do that.
# The following command will execute "python ./main.py".
CMD [ "python", "./main.py" ]

4. Create the Docker image

Once your code is ready and the Dockerfile is written, all you have to do is create your image to contain your application.

$ docker build -t python-test .

The ’-t’ option allows you to define the name of your image. In our case we have chosen ’python-test’ but you can put what you want.

5. Run the Docker image

Once the image is created, your code is ready to be launched.

$ docker run python-test

You need to put the name of your image after ‘docker run’.

There you go, that’s it. You should normally see “Docker is magic!” displayed in your terminal.

Useful commands for Docker

Before I leave you, I have prepared a list of commands that may be useful to you on Docker.

  • List your images.
$ docker image ls

  • Delete a specific image.
$ docker image rm [image name]

  • Delete all existing images.
$ docker image rm $(docker images -a -q)

  • List all existing containers (running and not running).
$ docker ps -a

  • Stop a specific container.
$ docker stop [container name]

  • Stop all running containers.
$ docker stop $(docker ps -a -q)

  • Delete a specific container (only if stopped).
$ docker rm [container name]

  • Delete all containers (only if stopped).
$ docker rm $(docker ps -a -q)

  • Display logs of a container.
$ docker logs [container name]

Before you go…

Thanks for reading! Do not hesitate to give me some feedback to improve my future articles in the comments below.

#docker #web-development

What is GEEK

Buddha Community

A beginner’s guide to Docker — how to create your first Docker application
Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Tamale  Moses

Tamale Moses

1669003576

Exploring Mutable and Immutable in Python

In this Python article, let's learn about Mutable and Immutable in Python. 

Mutable and Immutable in Python

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.

Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.

Mutable Definition

Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.

Immutable Definition

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

List of Mutable and Immutable objects

Objects of built-in type that are mutable are:

  • Lists
  • Sets
  • Dictionaries
  • User-Defined Classes (It purely depends upon the user to define the characteristics) 

Objects of built-in type that are immutable are:

  • Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)
  • Strings
  • Tuples
  • Frozen Sets
  • User-Defined Classes (It purely depends upon the user to define the characteristics)

Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.

Objects in Python

In Python, everything is treated as an object. Every object has these three attributes:

  • Identity – This refers to the address that the object refers to in the computer’s memory.
  • Type – This refers to the kind of object that is created. For example- integer, list, string etc. 
  • Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2 and 3

While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.

Check out this free python certificate course to get started with Python.

Mutable Objects in Python

I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:

#Creating a list which contains name of Indian cities  

cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]

# Printing the elements from the list cities, separated by a comma & space

for city in cities:
		print(city, end=’, ’)

Output [1]: Delhi, Mumbai, Kolkata

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [2]: 0x1691d7de8c8

#Adding a new city to the list cities

cities.append(‘Chennai’)

#Printing the elements from the list cities, separated by a comma & space 

for city in cities:
	print(city, end=’, ’)

Output [3]: Delhi, Mumbai, Kolkata, Chennai

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(cities)))

Output [4]: 0x1691d7de8c8

The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.

Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.

Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0. 

#Creating a Tuple with variable name ‘foo’

foo = (1, 2)

#Changing the index[0] value from 1 to 3

foo[0] = 3
	
TypeError: 'tuple' object does not support item assignment 

Immutable Objects in Python

Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:

#Creating a Tuple which contains English name of weekdays

weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’

# Printing the elements of tuple weekdays

print(weekdays)

Output [1]:  (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [2]: 0x1691cc35090

#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’

weekdays  +=  ‘Pythonday’,

#Printing the elements of tuple weekdays

print(weekdays)

Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(weekdays)))

Output [4]: 0x1691cc8ad68

This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it.  Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.

Also Read: Understanding the Exploratory Data Analysis (EDA) in Python

Where can you use mutable and immutable objects:

Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.

Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.

Watch outs:  Non transitive nature of Immutability:

OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–

#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements

#The elements (lists) contains the name, age & gender 

person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the tuple

print(person)

Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [2]: 0x1691ef47f88

#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4

person[0][1] = 4

#printing the updated tuple

print(person)

Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(person)))

Output [4]: 0x1691ef47f88

In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.

Also Read: Real-Time Object Detection Using TensorFlow

Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–

#creating a list (mutable object) which contains tuples(immutable) as it’s elements

list1 = [(1, 2, 3), (4, 5, 6)]

#printing the list

print(list1)

Output [1]: [(1, 2, 3), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [2]: 0x1691d5b13c8	

#changing object reference at index 0

list1[0] = (7, 8, 9)

#printing the list

Output [3]: [(7, 8, 9), (4, 5, 6)]

#printing the location of the object created in the memory address in hexadecimal format

print(hex(id(list1)))

Output [4]: 0x1691d5b13c8

As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.

Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’ 

x = 10
 

#printing the value of ‘x’

print(x)

Output [1]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(x)))

Output [2]: 0x538fb560

#creating an object of integer type with value 10 and reference variable name ‘y’

y = 10

#printing the value of ‘y’

print(y)

Output [3]: 10

#Printing the location of the object created in the memory address in hexadecimal format

print(hex(id(y)))

Output [4]: 0x538fb560

As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.

Quick checkPython Data Structures

Immutability of Tuple

Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.

Exceptions in immutability

Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.

Consider a tuple ‘tup’.

Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;

We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.

FAQs

1. Difference between mutable vs immutable in Python?

Mutable ObjectImmutable Object
State of the object can be modified after it is created.State of the object can’t be modified once it is created.
They are not thread safe.They are thread safe
Mutable classes are not final.It is important to make the class final before creating an immutable object.

2. What are the mutable and immutable data types in Python?

  • Some mutable data types in Python are:

list, dictionary, set, user-defined classes.

  • Some immutable data types are: 

int, float, decimal, bool, string, tuple, range.

3. Are lists mutable in Python?

Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)

4. Why are tuples called immutable types?

Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.

A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.

5. Are sets mutable in Python?

A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.

6. Are strings mutable in Python?

Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.

Join Great Learning Academy’s free online courses and upgrade your skills today.


Original article source at: https://www.mygreatlearning.com

#python 

Mike  Kozey

Mike Kozey

1656151740

Test_cov_console: Flutter Console Coverage Test

Flutter Console Coverage Test

This small dart tools is used to generate Flutter Coverage Test report to console

How to install

Add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dev_dependencies:
  test_cov_console: ^0.2.2

How to run

run the following command to make sure all flutter library is up-to-date

flutter pub get
Running "flutter pub get" in coverage...                            0.5s

run the following command to generate lcov.info on coverage directory

flutter test --coverage
00:02 +1: All tests passed!

run the tool to generate report from lcov.info

flutter pub run test_cov_console
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
 print_cov_constants.dart                    |    0.00 |    0.00 |    0.00 |    no unit testing|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

Optional parameter

If not given a FILE, "coverage/lcov.info" will be used.
-f, --file=<FILE>                      The target lcov.info file to be reported
-e, --exclude=<STRING1,STRING2,...>    A list of contains string for files without unit testing
                                       to be excluded from report
-l, --line                             It will print Lines & Uncovered Lines only
                                       Branch & Functions coverage percentage will not be printed
-i, --ignore                           It will not print any file without unit testing
-m, --multi                            Report from multiple lcov.info files
-c, --csv                              Output to CSV file
-o, --output=<CSV-FILE>                Full path of output CSV file
                                       If not given, "coverage/test_cov_console.csv" will be used
-t, --total                            Print only the total coverage
                                       Note: it will ignore all other option (if any), except -m
-p, --pass=<MINIMUM>                   Print only the whether total coverage is passed MINIMUM value or not
                                       If the value >= MINIMUM, it will print PASSED, otherwise FAILED
                                       Note: it will ignore all other option (if any), except -m
-h, --help                             Show this help

example run the tool with parameters

flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

report for multiple lcov.info files (-m, --multi)

It support to run for multiple lcov.info files with the followings directory structures:
1. No root module
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
2. With root module
<root>/coverage/lcov.info
<root>/lib/src
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
You must run test_cov_console on <root> dir, and the report would be grouped by module, here is
the sample output for directory structure 'with root module':
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock --multi
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_a -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_b -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

Output to CSV file (-c, --csv, -o, --output)

flutter pub run test_cov_console -c --output=coverage/test_coverage.csv

#### sample CSV output file:
File,% Branch,% Funcs,% Lines,Uncovered Line #s
lib/,,,,
test_cov_console.dart,0.00,0.00,0.00,no unit testing
lib/src/,,,,
parser.dart,100.00,100.00,97.22,"97"
parser_constants.dart,100.00,100.00,100.00,""
print_cov.dart,100.00,100.00,82.91,"29,49,51,52,171,174,177,180,183,184,185,186,187,188,279,324,325,387,388,389,390,391,392,393,394,395,398"
print_cov_constants.dart,0.00,0.00,0.00,no unit testing
All files with unit testing,100.00,100.00,86.07,""

Installing

Use this package as an executable

Install it

You can install the package from the command line:

dart pub global activate test_cov_console

Use it

The package has the following executables:

$ test_cov_console

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add test_cov_console

With Flutter:

 $ flutter pub add test_cov_console

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  test_cov_console: ^0.2.2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:test_cov_console/test_cov_console.dart';

example/lib/main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Author: DigitalKatalis
Source Code: https://github.com/DigitalKatalis/test_cov_console 
License: BSD-3-Clause license

#flutter #dart #test 

Abigail betty

Abigail betty

1624226400

What is Bitcoin Cash? - A Beginner’s Guide

Bitcoin Cash was created as a result of a hard fork in the Bitcoin network. The Bitcoin Cash network supports a larger block size than Bitcoin (currently 32mb as opposed to Bitcoin’s 1mb).

Later on, Bitcoin Cash forked into Bitcoin SV due to differences in how to carry on its developments.

That’s Bitcoin Cash in a nutshell. If you want a more detailed review watch the complete video. Here’s what I’ll cover:

0:50 - Bitcoin forks
2:06 - Bitcoin’s block size debate
3:35 - Big blocks camp
4:26 - Small blocks camp
5:16 - Small blocks vs. big blocks arguments
7:05 - How decisions are made in the Bitcoin network
10:14 - Block size debate resolution
11:06 - Bitcoin cash intro
11:28 - BTC vs. BCH
12:13 - Bitcoin Cash (ABC) vs. Bitcoin SV
13:09 - Conclusion
📺 The video in this post was made by 99Bitcoins
The origin of the article: https://www.youtube.com/watch?v=ONhbb4YVRLM
🔺 DISCLAIMER: The article is for information sharing. The content of this video is solely the opinions of the speaker who is not a licensed financial advisor or registered investment advisor. Not investment advice or legal advice.
Cryptocurrency trading is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#bitcoin #blockchain #bitcoin cash #what is bitcoin cash? - a beginner’s guide #what is bitcoin cash #a beginner’s guide

Felix Kling

Felix Kling

1683553906

Everything You Need to Know About CSS Variables

I'll be covering all you need to know about CSS variables. A complete guide To CSS Variables with examples. In this tutorial, we will explore what CSS variables are and how to use variables in CSS for creating beautiful responsive websites. 

Learn CSS Variables in 15 Minutes

In today's tutorial, I'll be covering all you need to know about CSS variables in 15 minutes. These include it's basic usage, combining it with the calc() function, fallback values and inheritence + psuedo classes.


A Complete Guide To CSS Variables [With Examples]

Variables are the basic building block of any software application. They reduce the redundant tasks for the developers in a program and hold values that have to be used in the entire program. Websites are a bit different. A novice in web programming may not be aware that variables exist at the front-end of web development as well as in CSS. Variables serve the same purpose as they serve when implementation is done using C++, Python, etc. Their work and complexities motivated us to come up with a dedicated blog on CSS variables.

CSS variables (also known as Custom Properties) is a modern CSS specification that is gaining prominence due to widespread browser support. It reduces coding and maintenance time and lets you develop cross browser compatible websites. It also helps in declaring values for reuse across a CSS file, which was previously possible only with preprocessors such as Sass and LESS.

In this blog, we will explore what CSS variables are and how to use variables in CSS for creating beautiful responsive websites. Finally, we will back it up with practical examples. So let’s begin!

What Are CSS Variables?

CSS variables are custom properties in which you can store a value and use it anywhere in the HTML code. They were introduced in Chrome 49 and have been extremely popular ever since. However, unlike programming languages that support simple initialization and substitution syntax, CSS variables need to be specifically defined whether they are being initialized or substituted. Hence, both of these things have their separate syntaxes.

CSS (4)

The initialization of the CSS variable is done by prefixing “–” to the variable name. For example, the following syntax initializes the variable “my_font” to 20px.

--my_font: 20px;

The “my_font” variable can now be used anywhere inside the code with a value of “20px”. Next comes the substitution part. The substitution of a property to the variable can be done only by the “var()” CSS property. Inside the “var(),” we spell the variable name as shown below:

selector {
    font-size : var(--my_font);
}

In the above syntax, the font size of the selector will become 20px due to the my_font variable. The “var()” takes another argument apart from the variable name – the fallback value. The fallback value works as a safety net in the variable substitution. In scenarios where the variable value is found to be inaccessible, the fallback value will be used in its place. The fallback value can be declared as shown below:

font-size: var(--my_font, 20px);

Fallback values work differently in different aspects. We will discuss this later in this post with some interesting illustrations related to web browsers.

Life Before CSS Variables – The SASS Preprocessor

Before understanding how to use variables in CSS and their importance in the website styling sheet, we need to understand what we used to do before variables in CSS. Before we had this awesome custom property to use, the web developers would use the SASS variables, which had similar intentions but were not smooth and flexible.

SASS variables work similarly to the backend languages where we copy-paste the variable name whenever substitution is required. The initialization, however, is done by prefixing the “$” to the variable name.

$my_font: 20px;

The substitution can be done as shown below:

font-size: $my_font;

The problem with SASS is that it is a preprocessor and not a custom property as a CSS variable. Therefore, any variable declared in SASS needs to be compiled before it can be executed. This makes the variable static and irresistible to change at runtime. A very common problem, therefore, arises when the developer tries to reinitialize the variable as follows.


$my_font: 20px;
 
selector1 {
 
   font-size: $my_font;
}
 
selector2 {
  
   $my_font : $my_font + 1;
   font-size: $my_font; 
  
}

This will now change the value of my_font to 21px. To reset the value back to 20px, we have to subtract one from it. This does not happen in CSS variables, as we get the advantage of the “calc” function, which we will cover later in this blog.

SASS Variables vs. CSS Variables

The following table will help you out to draw a clear picture between the two variables:

SASS VariableCSS Variable
Static allocationDynamic allocation
Media queries not supportedSupport for media queries
Requires preprocessorPreprocessor not required
An added layer of calculation and complexitySingle-layer and direct variable management

The SASS variables were commonly used before CSS variables. But the differences between them cannot be ignored. CSS variables are more useful as compared to SASS variables but also differ in many other aspects. Let’s see them in the next section.

Importance Of CSS Variables

Before we go ahead and understand how to use variables in CSS, let’s explore some of the benefits of using variables in CSS. As a web developer, you will be able to relate to it and retrospect on how your life would have been easier with them.

1. Remove Redundancy In Code

Variables remove the redundancy in the code. For example, let’s say we have a very small web page requirement with all the headings (the h tags) of the same “color: red.”

<html lang="en" dir="ltr">
    <head>
      <meta charset="utf-8">
      <title>CSS Variables</title>
      <style>
           h2 {
             color: red;
           }

           h3 {
             color: red;
           }

           h4 {
             color: red;
           }
      </style>
    </head>

    <body>
      <center>
      <h2>I am heading 2</h2>
      <h3>I am heading 3</h3>
      <h4>I am heading 4</h4>
    </center>
    </body>
  </html>

Up to this point, everything looks good, and we get the correct output on our webpage.

pasted image 0 (17)

Now let’s say the team decides to change the color to green for every heading. To do this, we have to go through “find and replace” three times on the page, which is acceptable. But what about constructing a real website where this would be done 100 times or more for just a single change

Variables in CSS eliminate this redundancy from the system where we would just need to change the color once – in the variable’s value.

--heading_color: red;
   h2 {
             color: var(--heading_color, black);
           }

           h3 {
             color: var(--heading_color, black);
           }

           h4 {
             color: var(--heading_color, black);
           }

In the above code, whenever a change arises, I just need to change the variable “heading__color” value from “red” to “green.”

2. No need For Preprocessors

Preprocessors are used for the compilation of variables. Now that we have variables in CSS, we can bid adieu to the processors and perform dynamic activities on the variables. So, in the above example, when I change the color from Red to Green or Cyan (or anything else), I don’t need to compile my page again. Instead, I just press F5, and the changes will be reflected on the web browser.

3. Super Flexible – Declare Anywhere

CSS variables are custom properties of CSS. Similar to other custom properties, you can use the variables in CSS wherever you want. Here is how you can use it with the style tag:

<style>
       h2 {
             color: var(--heading_color, black);
           }
      </style>

Using it inline can be another option:

< h2 style = "color: var(--heading_color, black)">I am heading 2</h2 >

4. Improved code readability

For developers, code readability is perhaps one of the most troubling pain points. Consider the following code where we apply color to the various elements on the web page:

h2 {
             color: rgb(194, 70, 48);
           }

           h3 {
             color: #c40808;
           }

           h4 {
             color: #8c1c06;
           }

Consider a case where 100 lines later, I choose the same h1 color for another paragraph because that was the team plan.

p {
             color: rgb(194, 70, 48);
           }

But is it predictable that the color used in this paragraph is the same as used in the heading? If color consistency is a point in your website development plan, you might have to look at both the values carefully and verify their similarities. This becomes a lot harder when we talk about maybe 10 or 20 such scenarios. Here is how you can improve the code readability and make it more predictable with variables in CSS:

:root {
        --heading_color: red;
        --other_color: rgb(194, 70, 48);
      }
           h2 {
             color: var(--heading_color, black);
           }

           h3 {
             color: var(--other_color, black);
           }

           p {
             color: var(--heading_color, black)
           }

Since the variable of “p” is similar to “h2”, they both have the same color. An add-on advantage of a readable code is that it becomes a lot easier to find typos. For example, let’s say later on you find out that “H2” and “p” were not supposed to be the same color?

To make them similar, you might have to go through the grilling task of finding and replacing the instances where you have read every value digit by digit. Instead, you can define CSS variables! In the above code, the class “root” defines the variables, which is one of the methods for defining variables in CSS.

CSS Variables and JavaScript

CSS variables can access the DOM of the web page, which is very helpful when dealing with JavaScript. This is a big advantage knowing that JavaScript can help us create awesome code by fetching the variable value and setting it to different values based on predefined conditions.

The end result (i.e., web page) is more dynamic, user-friendly, and gives a lot more control to the developer. The process and code for manipulating the variables with the help of JavaScript are defined in a separate section at the end of this blog.

Calc And CSS Variables

In the SASS variable section, I mentioned the calc function and how it gives the edge to variables in CSS. The calc function is a vital function for people who love to set things relative to each other. For example, if you are interested in fluid typography in web design, calc function would probably focus on your typography designs.

In addition, the calc function is a basic CSS function that lets us do calculations. For example, Calc functions are generally used to apply relative properties in HTML.

This is how I would make the heading to be 2.5 times larger than the paragraph’s font size.

font-size: calc(20 * 2.5)px;

But the problem here is that even though I have my requirements set properly, I still have to look at my paragraph size. This leads to redundancy in the source code. Variables in CSS can be used with the calc function just like any other property to minimize redundancy.

The approach described above can be replaced with the CSS variables as shown below:

:root {
        --paragraph_size: 20px;
      }
           h2 {
             font-size: calc(var(--paragraph_size) * 2.5);

Output:

pasted image 0 (16)

The second line is the original default font size of the “h2” tag. This code will be further discussed in the exceptions section to point out some of the common mistakes in CSS variables.

Scope In CSS Variables

In the implementation shown earlier, the root pseudo class (in which the variable is declared) and its significance in the CSS sheet look a bit questionable. However, this class is a part of “scopes,” and this section will highlight its importance in variables in CSS.

Global Scope – One declaration For All

The scope property is akin to a variable’s scope in the programming languages. The CSS variable’s scope is no different. This is how you can define a CSS variable under two scopes:

  • Global Scope – Accepted from the start till the end of the document
  • Local Scope – Accepted only within the selector

When a variable is defined with a global scope, its existence is defined in the complete document from the time of its declaration. But other programming languages like Python or C++ have an open field between functions where you have the option to define the global scope.

Unfortunately, CSS has no such area due to the lack of a preprocessor. Therefore, in CSS, we use the root pseudo class, which means that the variable is under the document’s root (i.e. global).

:root {
--my_variable: <value>
}

This variable can now be called in any of the selectors in the same document.


:root {
        --my_variable: <value>;
      }

div {

   <property>: var(--my_variable, fallback)

}

The root selector works because variables in CSS can access the DOM of the web app code. The root here represents the root of the DOM tree which passes the data to its branches (i.e., complete document).

Local Scope – Bounded By Selector Walls

The local scope of the variables in CSS is restricted by the boundaries of the selectors inside which it has been defined. For instance, in the below code, I have defined the background colour for a div box with id “first_div”:

div {
        width: 300px;
        height: 200px;
        color: white;
        font-weight: bold;
        font-size: 30px;
      }
      #first_div {
        --my_bg: #692a3c;
        background-color: var(--my_bg, black);
      }

  <body>
      <center>
      <div id = "first_div">I am a div</div>
    </center>
    </body>

Output:

pasted image 0 (14)

Let’s make another div and set the same background color as done with the above div.

#first_div {
        --my_bg: #692a3c;
        background-color: var(--my_bg, black);
      }
      #second_div {
        background-color: var(--my_bg, white);
      }
  <div id = "first_div">I am a div</div>
   <br><br>
   <div id = "second_div">I am a div too!!</div>

Output:

unnamed (1)

The fallback value is applied (i.e., black background color) to the second div. This happened because the scope of the variable “my_bg” is only within the #first_div tag. Thus, “my_bg” will not be accessible outside those brackets. Try rendering the same web page with “my_bg” defined in the root section and see how it looks!

Precedence And Inheritance

Now we know that when a variable is defined in the document’s root, it has a global scope and when defined inside any selector, it has a local scope. But, what if the same variable is declared at both places? Who takes the precedence, local or global CSS variable?

The following implementation demonstrates two different techniques to initialize the same CSS variable and its effect on the web page:

<style>
      :root {
        --my_bg : #692a3c;
      }
      div {
        width: 300px;
        height: 200px;
        color: white;
        font-weight: bold;
        font-size: 30px;
      }
      #first_div {
        --my_bg: #f42a3c;
        background-color: var(--my_bg, black);
      }

      #second_div {
        background-color: var(--my_bg, black);
      }

Output:

pasted image 0 (13)

None of the divs here has a black background color. This means none of the variables failed and fallback values were never used. Furthermore, if you read the code, the second div has used the global instance of the variable while the first div chose the local variable. Therefore, we can confirm that the local scope has precedence over the global scope in CSS variables.

As far as inheritance is concerned. CSS is infamous for inheritance, which confuses many web developers when things take values that were never defined within their scope. So, what does inheritance mean in CSS?

Inheritance is the relationship between elements that are nested in each other. For example, the following code shows a parent-child relationship:

<div>Hello, I am a parent
<div> Hello, I am a child</div>
</div>

Similarly, we can define other sibling relationships. But these relationships affect each other’s property (down the line from the top) when the value is either set to “inherit” or cannot be found. The following implementation demonstrates the parent-child relationship where the child does not have the CSS variable setting for its background color:

CSS:

#first_div {
        --my_bg: blue;
        background-color: var(--my_bg, black);
      }

      #second_div {
             background-color: var(--my_bg, black);
      }

      #third_div {
        --my_bg: green;
        background-color: var(--my_bg, black);
      }

      #fourth_div {
        background-color: var(--my_bg, black);
      }

HTML:

<div id = "first_div">
    <div id = "second_div">
      <div id = "third_div"></div>
      <div id = "fourth_div"></div>
    </div>
  </div>

If a variable is not found for the element, it inherits the variable value from its parent! Therefore, the above code will see the following background colors for all the div:

  • first_div: blue
  • second_div: blue – inherited from the parent.
  • third_div: green
  • fourth_div: blue – inherited from the parent that inherited from its parent.

All four values are predictable considering the inheritance logic in the above diagram.

Fallback Values In CSS Variables

Fallback values are the second argument used in the “var()” function, which denotes the substitution of a CSS variable. Fallback values take their name from the job they do – they are used when you fall back with the original variable values.

There are four possibilities through which a CSS variable goes during the substitution.

  • Browser does not support CSS variable property.
  • The browser supports the property, and the variable is set to correct values with scope.
  • The browser supports the property, but the variable is not set to any value.
  • The browser supports the property, and the variable is set to an invalid value.

What If The Browser Does Not Support CSS Variables?

If the browser does not support variables in CSS, the CSS line of code with “/var()” is ignored completely as the browser does not understand it. In such cases, the browser takes on the default values, i.e., transparent.

Let’s check the code on Google Chrome 46 that does not support the CSS variables.

<style>
      :root {
        --my_bg : #9e2e50;
      }
      div {
        width: 300px;
        height: 200px;
        color: black;
        font-weight: bold;
        font-size: 30px;
        background-color: var(--my_bg, black);
      }

      </style>
    </head>

    <body>
      <center>
  <div>
      I am a div box!!
  </div>
    </center>
    </body>
pasted image 0 (12)

The color I applied to the variable “my_bg” is not rendered on the div box. At the same time, the div box does exist here but only transparently.

pasted image 0 (11)

To demonstrate my web app, I have used an online cross browser testing platform LambdaTest. It provides 3000+ browsers and operating systems to test websites and web apps for cross browser compatibility issues.

Variable Is Set And Is In Scope!

If the variable is set to a valid value and is being called within its scope, it will be implemented correctly. So, for example, executing the above code on Google 47 and above will show correct results.

Variable Is Never Initialized

The next scenario comes when the variable is never initialized but is substituted in the code somewhere.

<style>
      div {
           background-color: var(--my_bg, black);
      }
   </style>

Output:

pasted image 0 (10)

The div box takes the fallback value in this case. The same thing happens when the variable is initialized but is called outside of its scope.

Variable Is Set To An Invalid Value

If the variable is set to an invalid value based on its usages, such as px or deg for color, the background becomes transparent.

 <style>
      :root {
        --my_bg : 20px;
      }
      div {
        background-color: var(--my_bg, black);
      }
      </style>

Output:/p>
pasted image 0 (9)

So the variable line is ignored by the browser.

Fallback values do not work every time the variable throws an error. Furthermore, it only works with a few of the scenarios that are described above. So, as a web developer, what can we do to manage the cross browser compatibility issues?

Implementing Two Fallbacks

The best method is to lay a safety net in the selector CSS code that can still place the value to the property in cases that the CSS variable fails.

<style>
      :root {
        --my_bg : #9e2e50;
      }
      div {
        background-color: #9e2e50;
        background-color: var(--my_bg, black);
      }

      </style>

If the variable is not initialized in the above code, the value will be taken from the first “background-color” initialization. However, if it is initialized, the value will be taken from the variable.

Although not necessarily a strict “fallback,” the variables in CSS can also perform fallback values for various exceptions using the cascading CSS variable methods.

background-color: var(variable_name, var(variable_name, fallback));

However, it has multiple layers of calculation and takes time to execute. This approach is therefore never recommended for a web developer.

Exceptions In CSS Variables

Once you know how to use variables in CSS, you will see it is flexible and easy to use. However, they do have a few exceptions that one should remember before declaring and substituting the variables.

Watch Cyclic Dependencies

Cyclic dependencies are explicit with their names. When dependencies are created with each other, the web developer should verify that the cycle is not created among the variables. If a cycle is created, the code execution could result in an infinite loop that can timeout the web page as it would never load completely.

--variable_name_1 : var(variable_name_2, fallback);
--variable_name_2 : var(variable_name_1, fallback);

A similar process will be seen when a variable will depend on itself during the time of initialization.

--variable_1 = var(variable_1, fallback);

Web developers should always take note of cyclic dependencies while initializing the variables.

CSS Variables Are Case-Sensitive

The CSS variables are case-sensitive. Therefore, the variables my_var and My_var are both different.

CSS Variable Cannot Be A Property Name

The CSS variable name cannot have a value as an existing property in CSS. So, for example, you cannot initialize a variable with the value “font-size.”

CSS Variables With JavaScript

One of the most attractive points for developers who love JavaScript is that variables in CSS can be handled and manipulated with the help of JavaScript easily. To use variables in CSS with JavaScript, you can fetch their current value similar to how JS handles other properties.

The following code fetches the CSS variable (used for the font size) and increases its font size to 40px as we press the button.

<html lang="en" dir="ltr">
    <head>
      <meta charset="utf-8">
      <title>CSS Variables</title>
      <style>
      :root {
      --fontSize: 20px;
      }

      div {
        width: 300px;
        height: 200px;
        color: white;
        font-weight: bold;
        font-size: var(--fontSize, 12px);
        background-color: #9e2e50;
      }
      </style>
      <script>
function changeFontSize() {
  var r = document.querySelector(':root');
  var rs = getComputedStyle(r);
  r.style.setProperty('--fontSize', '40px');
}
      </script>
    </head>

    <body>
      <center>
  <div>
      I am a div box!!
  </div>
  <br><br>
  <button onclick="changeFontSize()">Change Font Size</button>
    </center>
    </body>
  </html>

Output:

CSS_variables_with_Javascript

Browser Compatibility Of CSS Variables

CSS variables enjoy great support from every major browser. If you know how to use variables in CSS, you can ensure that exceptions and fallbacks are correctly working as per the code.

After implementing, you can use LambdaTest to perform browser compatibility testing to make sure it renders correctly on different browser versions and operating systems.

pasted image 0 (7)

How To Use LT Browser For Responsiveness Test Of CSS Variables

The most buzzed word of the web development world currently is responsiveness. With Google specifying the responsiveness wherever possible and multiple devices flooding the market, responsive web design has become a priority in itself.

Variables in CSS are not visual elements that can be tested with window resize functionality for responsiveness. But they do affect the components that are visual such as div, images, or anything else. Therefore, responsiveness test are important with the CSS media queries whether variables in CSS support them or not.

The following code implements the CSS media queries along with the CSS variables.

<html lang="en" dir="ltr">
    <head>
      <meta charset="utf-8">
      <title>CSS Variables</title>
      <style>
      :root {
        --my_color: red;
        --my_second_color: green;
      }


      @media only screen and (min-width: 641px) {
          #heading {
            color: var(--my_color);
          }
      }

      @media only screen and (max-width: 640px){
        #heading {
          color: var(--my_second_color);
        }
      }
      </style>
    </head>

    <body>
      <center>
      <h2 id = "heading">Wait for it!!!!</h2>
    </center>
    </body>
  </html>

Output:

media_queries_CSS_variables

The text is original of red color in the above code until the window size is greater than 640px. Else, the text color becomes green.

Performing a responsiveness test is not an easy job. You need various devices and owning or leasing every device is not a feasible approach. Instead, we need to choose smart solutions when dealing with responsiveness.

Conclusion

As a web developer, variables have always been a part of my styling sheet. I am sure after befriending them today, and you will start using them regularly too. Variables in CSS remove redundancy from the code, and the best thing is that they are just another property in CSS. However, after implementing CSS variables, you must perform a responsiveness test of your web design. You can follow the responsive web design checklist to ease up the entire responsiveness test process.

giphy

In this guide, we learned how to use variables in CSS from its implementation to responsiveness test. I hope variables in CSS are something that you enjoy and share with your fellow developers. If you have come across any interesting experiences with variables in CSS, please share them in the comment section below.

For your reference, check this out:
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties 

#css #webdevelopment