The title of this article little clears out the purpose of using the fgets function in C. The fgets() function in C is mainly designed to get the data input from a user or an input stream like file and display it within the output console. To get the input from a user to display on the console, we must have some buffer memory or array in which we can store that input. Using this function, we can restrict the number of characters to be displayed from an input stream and avoid displaying the excess data and display only the needed ones. This guide covers some C examples to explain the use of the fgets() function in detail.

The system update is a must before performing any sort of coding on it as it caters to all the memory-related issues and makes your system feature full. Thus, the “update” keyword with the “apt” utility and “sudo” privilege is a must. After adding this query to your Linux shell, it would require the passcode of a currently logged-in user.

If the Linux system already has a C compiler configured in it, you don’t need to add it again. If it’s not configured, you will face problems while executing the code. Thus, install it by utilizing the “apt” utility within the “install” instruction followed by the “gcc” utility name.

Before having a clear look at the C example for the fgets function, we have to create a “c” file. The “fgets.c” file that we create can be seen in the list of files and folders of the current “home” directory after using the “ls” query after creating it with the “touch” query.

After the file has been successfully created, we are going to open it in Linux’s “GNU Nano” editor. Therefore, we tried the displayed command in the shell.

Example 1:

We perform the first example of C to utilize the fgets function to get the input data from the user at run time and display a specific range of characters from it on the shell. Here is the C code that is used to get the data from a user. This code uses the standard input/output header for the use of the standard input and output streams like stdio.h. Before using the main() function, we define a MAX variable with the value 20 that is used as a range. The main() method is used here for the overall functionality.

The character type array “A” of size “MAX” is declared and the printf() function of C is used to display the “Input: ” string on the shell to ask the user for an input. The fgets() function of C is called here by passing it an “A” array, MAX variable, and “stdin” standard input output mutable as arguments to get the input from a user. This input is saved to the “A” array up to “MAX” length. A total of 20 characters is stored and the rest is discarded.

The printf() statement then uses the “A” array to display those 20 characters from the input. The return 0 statement ends the program smoothly after the execution. Save it before this code execution.

#include <stdio.h>

#define MAX 20

int main() {

  char A[MAX];

printf(«Input: «);

fgets(A, MAX, stdin);

printf(«Data: %sn«, A);

return 0;

}

After saving our C fgets() function code to its file, we exit the “nano” editor with the “Ctrl+X” and apply the “gcc” command to the “fgets.c” file to make it compiled. Nothing happened, so we tried the “./a.out” query to run the program. The “Input” string appeared along with the text area to get an input from us.

We add a single line of more than 30 characters and hard-press the “Enter” key. The inputted data is displayed up to the first 20 characters and the rest is discarded.

Example 2:

Within our new C illustration, we will demonstrate the use of the fgets() function to get the text data from the input file stream and display it on the console. Therefore, the main structure of this code is very similar to the previous example. The main() function starts with the declaration of a file descriptor “f” of pointer type by utilizing the built-in FILE object. The character type array “A” of size 30 is declared and the fopen() function of C is called to read the input stream “fgets.txt” from the system.

The returned value is saved to the file descriptor NULL. The “if” statement checks if the value of “f” is NULL or something else. If the value is “NULL”, it throws an error using the “perror” function of C. Otherwise, the “else-if” part of the statement is executed which is called the “fgets” function.

The purpose of using the fgets() method is to get 30 characters from an input stream “f”, save them to the “A” array, and check if the input is not NULL. When the whole input is not NULL, the puts() function of C is called here to display the whole input of 30 characters at the console while passing it the “A” array as an argument. The stream is closed using the fclose() function.

;
 f = fopen(«fgets.txt», «r»);
if(f == NULL) {
perror(«Error!»);
return(1); }
 else if(fgets(A, 30, f)!=NULL) {
    puts(A); }
fclose(f);
 return 0;
 }

Before compiling our code, we show you the text data within the fgets.txt file (that is used as an input stream) with the “cat” display query. It shows the 2 lines of the text data. Now, the compilation and execution take place. We get a single first line at the output area. This is because we choose to only get 30 characters from the input file stream.

Conclusion

While concluding this article, we are a hundred percent sure that you will not regret taking the help from our article when you want to learn some basics about the fgets() function of C. We discussed about how you can utilize this function to get the standard input from the user at runtime and how you can get the data from a file stream and display it in the output area.



Source link


“In UNIX/Linux ecosystem, the sed command is a dedicated tool for editing streams, hence the name (stream editor). It receives text inputs as “streams” and performs the specified operations on the stream.”

In this guide, we will explore performing in-place file editing with sed.

Prerequisites

To perform the steps demonstrated in this guide, you’ll need the following components:

Editing Stream Using sed

First, let’s have a brief look at how sed operates. The command structure of sed is as follows:

$ sed <options> <operations> <stream>

 
The following command showcases a simple workflow of sed:

$ echo «the quick brown fox» | sed -e ‘s/quick/fast/’

 

Here,

    • The echo command prints the string on STDOUT. Learn more about STDIN, STDOUT, and STDERR.
    • We’re piping the output to the sed Here, STDOUT is the stream sed that will perform the task specified.
    • The sed command, as specified, will search for any instance of the word quick and replace it with fast. The resultant stream will be printed on the console.

What if we wanted to modify the texts of a text file? The sed command can also work using text files as the stream. For demonstration, I’ve grabbed the following text file:

 

The following sed command will replace all the instances of the with da:

$ sed -e ‘s/the/da/g’ demo.txt

 

Check the content of demo.txt for changes:

 

From the last example, we can see that sed only printed the resultant stream on the console. The source file (demo.txt) wasn’t touched.

Editing Files In-place Using sed

As demonstrated from the previous example, the default action of sed is to print the changed content on the screen. It’s a great feature that can prevent accidental changes to files. However, if we wanted to save the changes to the file, we needed to provide some additional options.

A simple and common technique would be replacing the content of the file with the sed output. Have a look at the following command:

$ cat demo.txt | sed ‘s/the/da/g’ | tee demo.txt

 

Here, we’re overwriting the contents of demo.txt with the output from the sed command.

While the command functions as intended, it requires typing additional codes. We involved the cat and tee commands along with the sed command. Bash is also involved in redirecting the outputs. Thus, the command is more resource-intensive than it needs to be.

To solve this, we can use the in-place edit feature of sed. In this mode, sed will change the contents of the file directly. To invoke the in-place edit mode, we have to use the -i or –in-place flag. The following sed command implements it:

$ sed –in-place -e ‘s/the/da/g’ demo.txt

 

Check demo.txt for changes:

 

As you can see, the file contents are changed without adding any additional components.

Final Thoughts

In this guide, we successfully demonstrated performing in-place edits on text files using sed. While sed itself is a simple program, the main source of power lies within its ability to incorporate regular expressions. Regex allows describing very complex patterns that sed acts upon. Check out regex in sed to learn more in-depth.

Alternatively, you can use Bash scripts to filter and modify the contents of a file. In fact, you can incorporate sed in your scripts to fine-tune text content. Check out this guide on getting started with Bash scripting.

Happy computing!



Source link


It does not matter if you’re a system administrator or an media user, but keeping your computer infrastructure and network running smoothly is very important. Hence, you need a reliable system monitoring tool that will help you keep track of all the system activities like CPU performance, memory usage, network monitoring, and status of all the connected devices.

There are many choices available on the internet for system monitoring tools. Still, we have crafted a list of the best system monitoring tools for you by testing each tool in different circumstances. So, sit back and enjoy the ride to find the best system monitoring tool for Ubuntu that matches your requirements.

1. htop

htop is a cross-platform system educador, process viewer, and process manager and a reliable alternative to top, which is also a system monitoring tool for Linux and its distros. It is specially designed and developed for consoles and terminals; hence, it supports text mode.

It is a feature-rich system monitoring tool that can be used on Linux, FreeBSD, OpenBSD, and macOS. Talking about the features, it offers information based on various parameters, such as tasks, load media, and uptime. You can change color preferences on its UI to match your requirements.

For Linux and its distros, it provides a delay account matrix and offers support for custom scripts and real-time signals. Since it is open-source and free, it makes it one of the best system monitoring tools for Linux systems.

$ sudo apt-get install htop

2. Glances

Written in Python, Glances is another cross-platform system monitoring tool on our list. It uses a web-based interface to give you maximum system information in the minimum possible space. Depending on terminal size, it automatically adjusts itself and displays all the information in a single window.

It can also be used in client/server mode, and remote system monitoring could be done through the web interface or terminal. You getting all the important information in one place is one of the positives of this tool.

The thing I like most about this system monitoring tool is that you can keep track using its web interface, which allows remote monitoring. Linux running on low-end or older computers might find it tough to run this tool smoothly as it demands higher CPU resources.

Download Here

3. Stacer

Stacer is an open-source system educador and optimization tool, which helps system administrators manage system resources and tasks under one roof. It is a modern tool with an excellent user interface that makes you feel at home even on first use.

It has feature-rich tools that let you manage startup apps, clean unnecessary package caches, crash reports, application logs, application caches, and trash under the system cleaner tab, and start or stop services quickly. Sort processes based on process id (PID), CPU, and memory usage, find a particular process easily using its name in the search bar, and uninstall applications that are not required anymore.

The resource tab displays CPU, RAM, Disk, CPU load media, and network activity for the last 60 seconds. It also comes with an APT repository manager, which you can use to activate, disable or delete any repository. Ubuntu users can use this feature to edit the package repositories.

Sudo add-apt-repository ppa:oguzhaninan/stacer

sudo apt-get update

sudo apt-get install stacer

4. BashTOP

BashTOP is another cool and reliable system monitoring tool for Linux and its distros, such as Ubuntu. It displays the usage stats for processors, memory, disks, network, and other resources.

It is an excellent tool for desktop and computer users who are generally personal users. However, system administrators and server users won’t find this tool useful as their demands will be higher. Also, it is a little bit slower compared to other system monitoring tools, such as Htop.

It is an easy-to-use tool and sports a beautiful user interface with everything placed perfectly.

$ sudo add-apt-repository ppa:bashtop-monitor/bashtop

$ sudo apt update

$ sudo apt install bashtop

5. GNOME System Maestro

It is a simple system monitoring tool that comes pre-installed on various Linux distros running the GNOME desktop environment. This tool shows which programs are running, how much processor time, memory, and disk space are used.

As you can see in the screenshot, it has a clean and simple user interface. Every information and stats are placed perfectly in the user interface, which makes it easy to read and understand.

The CPU history tab shows how much processor capacity is used for each CPU, and the memory and history tabs show how much of your computer’s memory (RAM) is being used. Under the network tab, you see the download and upload speed of the network over the last 60 seconds.

6. vtop

vtop is a free and open-source system monitoring tool for Ubuntu and other Linux distros. Using vtop, not only can you educador system resources, but also you can manage them.

It is a command-line tool written in node.js. Hence, you must first install node.js and npm packages before installing vtop. Using this tool, you can easily educador CPU usage and memory usage, something you can do in other command-line tools like top.

$ sudo apt-get install node.js

$ sudo apt-get install npm

$ sudo npm install -g vtop

7. nmon

nmon is a simple-to-use system monitoring tool for Linux and its distros, such as Ubuntu. It gives you a quick overview of what’s going on with your server.

This monitoring tool displays the usage stats of CPU, memory, network, disks, file system, NFS, top processes, and resources. The best thing is you can select what the nmon displays, and what you have to do is simply press specific keys to toggle stats.

$ sudo apt-get install nomn

8. atop

atop is an advanced interactive system and process educador that displays the load on the Linux system. It shows the stats of the most critical hardware resources, such as CPU, memory, disk, and network.

You can log resource utilization permanently if you want it for long-term analysis.

$ sudo apt-get install atop

9. gotop

gotop is another command-line graphical system monitoring tool for Ubuntu and other Linux distros. Along with Linux, gotop is also available for macOS.

It is inspired by vtop and gtop. But unlike them, it does not use node.js. Instead, it is written in Go. You can educador CPU usage, disk usage, CPU temperature, memory usage, network usage, and process table.

$ sudo snap install gotop-brlin

Conclusion

These are the best system monitoring tools you can use on your computers running Linux and its distros. Some other tools are available for Ubuntu, but the ones listed above are tested and presented to you.



Source link


Git is the most popular version control system. Many developers and teams use Git for their activities. One common practice when working with Git is to create branches that help create a separate working environment. With branches, you can mess around with things without affecting the other sections of the code, and at long last, you can compare your branches and then merge them. The question is, “how do you compare two branches using Git?”

Comparing Branches in Git

Git offers the Git diff command, which lets you easily compare branches. You can compare the files in the branches and their commits. Let’s see the various ways of comparing branches.

1. Comparing Two Branches

Creating a new branch and working on it is safe when you’ve cloned a project. That way, you separate it from the main branch without messing up things. Before you merge the two branches, you should compare them to see the differences.

The syntax for comparing branches is:

$ git diff branch0..branch1

In the syntax above, you are trying to check what files or information are available in branch1 but not in branch0. Ideally, the double-dot will compare the branches’ tips or HEAD. If solving a conflict between the branch, the double-dot will give more details about the branches.

In the image above, we are comparing two branches: linuxhint e master. We can see all the commits in the master branch that are not in the linuxhint branch.

2. Comparing Files in Branches

It’s common to have specific files sharing the same name but in different branches. It could be some code or a file and you want to check the difference between the two versions of the files in different branches. In that case, use the syntax below.

$ git diff branch0..branch1 filename

With the above syntax, we are comparing the given file based on the HEAD of the two branches to outline the difference in the versions.

For instance, in the image below, we can see the difference in the file named one.txt in the file’s content. The words in the two files are not the same. This command could come in handy if you compare code that had a conflict or your version of the code with another.

3. Comparing Commits

Different branches have different commits, when working on the same version of a project in a separate branch, it makes sense that you would want to check the difference in the commit of two branches. Here, you will use the git log command with the syntax below.

$ git log branch0..branch1

In the example below, we can see the different commits for each branch, the date of the commit, the author, and the commit message. You can also note the commit ID. Comparing commits between branches is a great way of analyzing a merge conflict.

4. Using Triple-dots

Most comparisons involve the HEAD, which is why you will often use the double-dots. However, if you need to compare one branch with the ancestor of both branches, you use the triple-dots.

In the syntax below, we are comparing branch1 with the common ancestor of branch0 and branch1.

$ git diff branch0…branch1

Conclusion

Git is an excellent and easy-to-use version control system. It offers short commands that achieve great functionality, when working on a project, it’s recommended to create a branch to act as the safe zone for trying things without messing with the flamante code. This guide covered the various ways of comparing branches on Git to see their difference in commits, HEAD, and files.



Source link


JavaScript offers a variety of functionalities to create interactive interfaces. One can retrieve the value of any element using JavaScript methods. The input value can be printed somewhere on the web page or it can be obtained as an alert message. All this is possible with the help of JavaScript. Here, we will describe the JavaScript support to get the input value from any element. The following learning outcomes are expected:

How to Get Input Value in JavaScript

JavaScript provides two properties to get the input values by employing the getElementById, getElementsByClassName, and querySelector methods. These methods extract the string as well as the numerical value to display the user information. All the famous browsers support both of these properties. The value property returns the information of the user. Moreover, the property is useful for assigning any specific value for display in the browser window.

The syntax of these methods is stated below.

Syntax of getElementById

document.getElementById(«textId»).value = «text_message»;

Syntax of getElementsByClassName

document.getElementsByClassName(«clName»).value ;

Syntax of querySelector

document.querySelector(«id1»).value

The description of the above parameters is as below:

  • textId: denotes the id of an element.
  • text_message: represents the message to be displayed.
  • clName: specify the name of the class.
  • Id1: represents the id or class of an HTML element.

Example 1: Get the Input Value Using the getElementbyId() Method

Another example is considered for getting the input value in JavaScript.

HTML

<!DOCTYPE html>
<html>
<body>
<center>
<h2> An example to get the value of the text field</h2>
Favorite Message: <input type=«text» id=«mtxt» value=«Welcome to JavaScript»>
<p>Press button to display the text value.</p>
<button onclick=«Display_fn()»>Display Button</button>
<p id=«demo»></p>
</center>
</body>
</html>
<script src=«test.js»> </script>

The HTML code gets the input value “Welcome to JavaScript” by pressing the “Display Button”. The button is attached with the Display_fn() method.

JavaScript

function Display_fn() {
  var a = document.getElementById(«mtxt»).value;
  document.getElementById(«demo»).innerHTML = a;
}

A method Display_fn() is employed to retrieve the value of text in the HTML file by getElementById.

Example 2: Get the Input Value Using the getElementsbyClassName() Method

An example is considered to get the numeric value from the input field in JavaScript.

HTML file

<!DOCTYPE html>
<html>
<body>
<center>
    <h2> An example to get the numeric value of field</h2>
    <input type=«text» placeholder=«Type « id=«inp_id1» class=«inpCls»>
    <br> </br>
    <button type=«button» onclick=«getInpVal();»>Get Numeric Value</button>
</center>
</body>
</html>
<script src=«test.js»> </script>

In this code, the description is as below:

  • The class inpCls is used to input the numeric number.
  • After that, a button is attached that is associated with the getInpVal() method.
  • In the end, a JavaScript file test.js is linked by assigning the source src variable.

JavaScript

function getInpVal() {
  let inpVal = document.getElementsByClassName(«inpCls»)[0].value;
  alert(inpVal);}

In the JavaScript file:

  • A method getInpVal() is used to extract the value from the HTML file.
  • The extraction is performed by getElementByClassName(“inpCls”)[0].value.
  • In the end, an alert message is generated by passing the inpVal variable.

Output

The output shows that the user first inputs any number. After that, an alert box is generated by pressing the “Get Numerical Value” button.

Example 3: Get Input Value Using querySelector() Method

Another example is considered to get the value using the querySelector() method.

Code

<html>
<body>
   <h2>Get value using Query Selector <br></h2>
 <input type=«text» id=«id1» > <br><button type=«button»  onclick=«getValueInput()»>
    Display Button
  </button>
  <p id=«val»></p>
  <script>
    const getValueInput = () =>{
      let val1 = document.querySelector(«#id1»).value;
      document.querySelector(«#val»).innerHTML = `Message: ${val1}`;
    }
  </script>
</body></html>

In this code, the description is as follows:

  • Firstly, a text box and a button are attached with <input> e <button> tags respectively.
  • The button is associated with the getValueInput() method.
  • In this method, querySelector() is employed to extract the value of the text box and display it using val1.

Output

The output shows the message “JavaScript” by pressing the button in the browser.

Conclusion

The getElementById, getElementsByClassName, and querySelector() methods are utilized to get the input value in JavaScript. The first two methods retrieve the elements using the id and class name. While the third method can get the elements using an id as well as a class name. Here, you have learned to use all three of these methods to get input values in JavaScript.



Source link


Every device has a life, and so do the laptops; with time and the increasing advancements in technologies, the versions get older. When determining the software compatibility with your laptop or replacing any components of your laptop, knowing the age of your laptop is a mandatory thing to do. To get to know more about the version of your laptop or how old and compatible your laptop is, read this article.

Ways to Check Laptop’s Age

It can be difficult to get the exact date of manufacturing, but still, there are a variety of methods available to check how old your laptop is:

  1. From the serial number
  2. Through BIOS version
  3. Through PC release date
  4. From the model’s name of your laptop

1: Checking Laptop’s Age from Serial Number

If you have purchased a new laptop, then every laptop has a serial number sticker or a tag containing the serial number. This tag is mainly located at the bottom of the laptop and the back side of the desktops. You can copy that serial number and paste it into the Google search engine to check your laptop’s manufacturing date.

Write the below-mentioned command to find the serial number of your machine:

wmic bios get serialnumber

Copy the serial number and search on Google to find the manufacturing date of your laptop:

2: Checking Laptop’s Age Through BIOS Version

The visible command prompt has all the necessary system information. A Lot of information is there of your system in the command prompt. It will tell your innovador install date of Windows or BIOS version; this will give you a good idea of how old your system is:

Step 1: Right click on the Windows icon to open the Window PowerShell:

Step 2: Type the following command in Windows PowerShell:

If you have updated your BIOS since you purchased a computer, this date will not be accurate, but it will give you a rough estimate of your laptop’s manufacturing date.

The BIOS method will not tell you the exact date as it will give a rough estimate. Follow the other methods to figure out the manufacturing date of your laptop.

3: Checking Laptop’s Age Through CPU Release Date

The CPU will tell you the rough estimate of the release date of your system. Go through these steps to check the release date of your laptop:

Step 1: Open settings by pressing the Windows+I key and click on the System:

Step 2: Navigate to the About option:

Step 3: In the next step, copy the processor name:

Step 4: Paste your process name into the Google:

Step 5: Look for a Processor launch date of your laptop:

4: Checking Laptop’s Age from Model Name

You can perform a quick search on the internet to check the age of your laptop by following this step-by-step guide:

Step 1: Right-click on Windows to open Windows PowerShell:

Step 2: Type the command given below to get the information about the system:

Step 3: Copy the system model and manufacturer and search it on Google:

Step 4: Open the manufacturer’s website to check the release date of your laptop:

Conclusion

Checking your laptop manufacturing date is very important before upgrading because like desktops, components of laptops cannot be upgraded. There are many procedures through which you can make an estimate of your systems age. The above listed are some easiest steps to check your laptop’s version and how old it is.



Source link


“It’s crucial to manage storage capacity on a Linux system. Programs that act as package managers, for instance, alert you to the amount of disc space needed for setup. You need to be aware of the amount of free space on your machine for that knowledge to be useful. There are several utilities available in the Linux systems to discover what is using the disk space of our system. Discover how to examine the disc space in Ubuntu using the df utility as well as how to view the file system’s disc space consumption using the “du” tool throughout this lesson.”

Update System

Before checking the disk space usage, we need to update our system to make it fully updated so that the memory space can be displayed correctly. For this, try opening the console application of your Linux system with the use of the “Ctrl+Alt+T” shortcut. It will be launching the console quickly in a few seconds. We have tried the apt instruction with the sudo rights followed by the keyword “update”. The execution asks for the “password” of the currently active user at the moment. We have added the password, and the process continues.

Check Disk Space Usage With Df Utility

The main system part that uses the memory more than anything is the disk, usually in all operating systems. To find the amount of space used by the disk in the Ubuntu 20.04 system, we will be utilizing the “df” utility of our system. The df tool, which refers to disk free, displays how much space each drive is using. Values are shown by df by a standard in 1-kilobyte units. Within the “df” command output below, we have been shown the space used by the file system and the system’s related parts. It also displayed the percentage usage of space in the output.

Check Disk Space Usage in Mega & Gega Bytes

Within the above output, the disk space usage has been displayed in the 1-kilobyte format, while in the “used” and “available” column, we can only see disk space value in numbers, i.e., merely understandable. So, to display the disk space output in a more human-readable presentable format so that any computer user can understand it quickly and get any type of information required. For this, we need to use the “df” instruction with its “-h” option in the query area, as we have used this instruction in the attached photo. The output for the Size, Used, and Avail column has now displayed the result in Kilobytes, megabytes, and gigabytes after the conversion. While the “Use%”, and “Mounted on” columns have got no change in them.

You can also make use of the “df” instruction according to your needs. Let’s say you only want to look for the size of disk space, its available space, and its used space on your shell screen. For this, you need to use the “df” instruction with the “-H” option and the column names from the particular space table, i.e., Size, used, avail, as presented in the image below. The output below has displayed the data for these three columns and didn’t identify the program or disk.

Check Disk Space Usage for File System

The very same “df” instruction can be utilized in the console with its “-h” option to display the disk space used by the file system used in your Linux system. So, we have tried this instruction to check the space used by the “dev/sda2” device file system. The output shows that the disk “dev/sda” has a size of 2.4GB while 0 bytes are used, and the rest is available to be used.

The use of the “df” instruction with the “-h” option and the “/” character shows the amount of space used on the primary disk storage device. So, we have tried it and found that the primary disk “dev/sda5” has a size of 30GB while 14GB has been used and 15GB has been left unused and can be utilized shortly.

Check Disk Space Usage for File System by Type

You can try to find out the disk space usage for the file system according to the type of file system. For this, you need to use the “-ht” option within the “df” instruction along with the file system type, i.e., ext4 in our case. The output on our screens is showing quiebro similar output as above while the “mounted on” column has only a “/”.

Check Disk Space Usage With Du Utility

Disk use is seen via the du utility. You may see your disc performance in further detail with this utility by using Ubuntu 20.04 Console application to show the disk usage for certain folders. Use it to show how much storage your present directory is using, as we did in the below presentation. The left side numerical value shows the data size, and the right side shows all files and folders of our system.

The “du” instruction, along with the “-h” option, has been showing the space used by the folders in kilobytes at the console application screen of our system, as presented in the attached image.

If you want to find out the space used by your current working directory, you must utilize the “du” instruction with the combined option “-hs”. The result displays that it contains a total of 106MB of data within the system.

Conclusion

We have elaborated on the popular use of the disk space concept along with the different utilities of our Linux operating system. Firstly, we have tried to update our system to avoid any issues. After that, we discussed the use of “df” and “du” instructions separately to see how much space has been utilized by a particular disk drive. We have tried the “df” and “du” instructions with the “-H” or “-h” instructions for the view of disk space usage in the Kilobytes, Megabytes, and Giga bytes. Hence, we have tried to cover every minor detail in this article.



Source link


The Raspberry Pi remote access feature is a handy task that allows Raspberry Pi users to handle another operating system with ease. Accessing your favorite desktop environment like Windows right from your Raspberry Pi device will help you use Windows features and applications on your device.

This article will guide you on remotely connecting your Windows PC to your Raspberry Pi device.

How to Remote Connect to a Windows PC From Raspberry Pi

If you want to control Windows PC from your Raspberry Pi device, you must need to follow the below-given steps:

Step 1: First, enable the remote connect feature option from your PC or laptop and for that, you need to go to Windows Explorer and right click on “The PC” to select the “Properties” option.

Step 2: Select the “Advanced system settings” option.

Step 3: In the “System Properties”, make sure that you have a checkbox for the below-highlighted option in the Remote section.

Step 4: Next, you will need to find the IP address of your PC or laptop and you can do so by opening the command prompt and entering the following command:

Step 5: Now, head toward your Raspberry Pi terminal and execute the following command to install a remote desktop application called Remmina on your Raspberry Pi device.

$ sudo apt install remmina -y

Step 6: You will also need to enable the VNC feature as well as SSH on your Raspberry Pi, which you can do so by going straight into the Raspberry Pi configuration as shown below:

Ensures that both SSH and VNC options are enabled as these two features are important for Remote desktop connection.

Step 7: Now, open Remmina on Raspberry Pi by executing the following command:

In the Remmina app, there are three options to pick for a remote desktop connection, which are RDP, VNC and SSH.

Since the VNC feature is already enabled in the Raspberry Pi device, thus, we are selecting the VNC on Remmina.

Step 8: Now, enter the IP address of your PC or laptop, which is “192.168.100.45” in our case.

Step 9: Enter the password for your Raspberry Pi to join the connection.

There, you will see your Windows desktop on your Raspberry Pi, which confirms a successful remote connection of your Windows PC.

Conclusion

The remote connection is beneficial if someone needs to access the Windows desktop environment on his Raspberry Pi device. The above step-by-step guidelines are enough to help you get things done successfully. These steps require enabling the remote access feature from your laptop or PC and installing Remmina on Raspberry Pi. After enabling both VNC and SSH features on your device, you can access your Windows PC on your Raspberry Pi display using the IP address of your Windows PC.



Source link



There are multiple ways of writing a program that selects a random element from an Array, but the best-suited method is to use a combination of Math.random() and Math.floor() methods. Math.random() method provides the user with a random floating-point value between 0 and 1. While the Math.floor() method simply takes in a floating-point value and rounds down the value to make it an integer.

Method 1: Random element from an Array Using Math.random() & Math.floor()

First, create an array with the following line:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

This array represents a list of cities to choose from at random. After this, simply create a new function that takes in the array as a parameter like:

function elemenet_Selector(arr) {
 
}

Within this function, the very first thing is to get the length of the array passed to it inside a separate variable:

array_length = arr.length;

Then, simply call the Math.random() method to get a floating-point value and then multiply that number with the length of the array to get the range between 0 and array length:

value = Math.random() * array_length;

This line will return floating point values, but they are no good when it comes to being the index of an array. Confirm this by simply wrapping this line into the console log and observing the output:

The output on the terminal is as:

To change these values into an integer, simply pass the value variable into the Math.floor() method and remove the console.log(value) line:

indexValue = Math.floor(value)

At the end of the function, use a return statement and return the element at the indexValue of the array:

After that, come out of the function element_Selector, and make a call to this function and wrap that call inside a console log function to print out the randomly selected element:

console.log(elemenet_Selector(my_arr));

The complete code snippet is as:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

function elemenet_Selector(arr) {
  array_length = arr.length;
  value = Math.random() * array_length;
  indexValue = Math.floor(value);
  return arr[indexValue];
}

console.log(elemenet_Selector(my_arr));

Execute this program and observe the following result:

It is clear from the output that random elements are selected from the array.

Method 2: Using Double NOT Bitwise Operator

Start by creating an array just like in method 1 with the help of the following line:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];

Afterwards, call Math.random() and multiple it with the length of our array to get a range from 0 to the length:

value = Math.random() * my_arr.length;

This time around, to convert this value into an integer representing the index of the array, simply apply the double NOT Bitwise operator, which is the double tilde operator (~~), and fetch the value from the array as:

var item = my_arr[~~value];

Last, simply print out the randomly selected element onto the terminal with the help of console log function:

Complete code snippet for method 2 is as:

my_arr = [«Paris», «London», «Bangkok», «New York», «Los Angeles», «Dubai»];
value = Math.random() * my_arr.length;
var item = my_arr[~~value];
console.log(item);

Execute this program and observe the following result:

It is clear from the output that a random element is being selected from the array

Conclusion

In JavaScript, we can utilize the Math.random() function with either the Math.floor() function or the double NOT Bitwise operator to fetch a random item from an array. Math.random(), when multiplied by the length of the array, provides a range value of index between zero and the array’s length. However, this range value is in floating point, therefore, use Math.floor() or NOT Bitwise operators to convert it into an integer to be used as the array index. This article has explained both of these methods along with an example



Source link



There are multiple ways of storing key => value arrays in JavaScript. However, the tricky part is storing the keys and values from two different arrays into a single element. And to add to its trickiness, key and value are to be stored in such a scheme that fetching a key with its respective value is easy. This cuts down the number of methods to achieve the task at hand to only two. The two most promising methods include the use of Objects e Maps. This article will go through both of these methods one by one.

Note: This article will assume that keys and values are stored in different arrays, and the objective is to store them together and have them formatted as “key => value” while fetching.

Method 1: Using Objects to Store Key => Value Arrays

To demonstrate this method, first create a key array and a value array with the following lines:

var keysArray = [«China», «England», «Egypt», «Finland», «Greece»];
var valuesArray = [«Beijing», «London», «Cairo», «Helsinki», «Athens»];

After that, create an empty JavaScript object with the following line:

After that, simply copy the keys and values from their array and add them in the object using the following lines:

for (var i = 0; i < keysArray.length; i++) {
  resultObj[keysArray[i]] = valuesArray[i];
}

In this above code snippet:

  • A for loop is run and its iterations are equal to the number of elements inside the keys array.
  • In each iteration, a new attribute of property of the object is created, and it is given the name equal to the element inside the key array and its respective value from the value array by using the same index values.

After that, pass the resultObj to the console log function to print it out on the terminal:

Executing the code will provide the following output:

The keys and values are stored together, but they are still not in the “key => format
To display them in the correct format, use the following lines of code:

for (x of Object.keys(resultObj)) {
  console.log(x + » => « + resultObj[x]);
}

In this code snippet:

  • Object.keys() method returns the keys of the object in its argument one by one. The keys are getting stored inside the variable “x
  • String concatenation is used to format the output of the console log as “keys=> values”

Executing the program now produces the following result:

The output shows that the keys are not only stored together but also formatted in the correct way.

Method 2: Using Maps to Store Key => Value Arrays

To demonstrate the usage of maps for storing keys and their respective values, create two arrays with keys and values with the following lines of code:

var keysArray = [«China», «England», «Egypt», «Finland», «Greece»];
var valuesArray = [«Beijing», «London», «Cairo», «Helsinki», «Athens»];

The next step is to create a map, for this create a variable and set it equal to the new Map() constructor like:

To add values to a Map variable, there is this method mapVar.set(). Use this function to add keys and their respective values:

for (i = 0; i < keysArray.length; i++) {
  resultMap.set(keysArray[i], valuesArray[i]);
}

In the code snippet mentioned above:

  • A for loop is used to iterate through the keysArray and the valuesArray using the length of the keysArray.
  • In each iteration, resultMap.set() method is used to store the key and value pair in the map.

After this, simply pass the resultMap variable onto the terminal by using the console log function:

This code will produce the following output:

It is sort of in the right format, but it includes a little extra information. To correctly format it, use the following lines:

for (key of resultMap.keys()) {
  console.log(key + » => « + resultMap.get(key));
}

In this code snippet:

  • resultMap.keys() method returns the keys of the map one by one to the key variable.
  • resultMap.get() method is used to get the value of a specific key.
  • And in the console log function, string concatenation is used to correctly format the output.

Executing the code now produces the following output on the terminal:

The output shows that the keys are not only stored together but also formatted in the correct way.

Conclusion

In JavaScript, Objects and Maps are the two elements that are most suited to store keys and value pairs, even if the task at hand is to take keys and values from individual arrays and place them inside a single entity. Afterward, whenever the user is trying to get keys and their respective values, they can be easily formatted in “key => value” format by using simple string concatenation in JavaScript.



Source link