code-rag-bench/online-tutorials huggingface dataset:
Mongoose | findByIdAndDelete() Function

28 Jun, 2021
The findByIdAndDelete() function is used to find a matching document, removes it, and passing the found document (if any) to the callback.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose');  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {    name: { type: String },    age: { type: Number }});  // Find a document whose // id=5ebadc45a99bde77b2efb20e and remove itvar id = '5ebadc45a99bde77b2efb20e';User.findByIdAndDelete(id, function (err, docs) {    if (err){        console.log(err)    }    else{        console.log("Deleted : ", docs);    }});
Steps to run the program:
The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see in the database that the particular user is deleted as shown below:
The project structure will look like this:
Make sure you have installed mongoose module using following command:npm install mongoose
npm install mongoose
Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:node index.js
node index.js
After the function is executed, You can see in the database that the particular user is deleted as shown below:
So this is how you can use the mongoose findByIdAndDelete() function which finds a matching document, removes it, and passing the found document (if any) to the callback.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Character indices Mapping in String List

14 Oct, 2020
Given a String list, map each character in strings, to indices it occurs.
Input : test_list = [‘g f g’, ‘b e s t’, ‘f o r’, ‘g e e k s’]Output : {‘g’: [1, 4], ‘f’: [1, 3], ‘s’: [2, 4], ‘b’: [2], ‘e’: [2, 4], ‘t’: [2], ‘o’: [3], ‘r’: [3], ‘k’: [4]}Explanation : Characters mapped with their occurring elements indices.
Input : test_list = [‘g f g’, ‘i s’, ‘b e s t’, ‘f o r’, ‘g e e k s’]Output : {‘g’: [1, 5], ‘f’: [1, 4], ‘i’: [2], ‘s’: [2, 3, 5], ‘b’: [3], ‘e’: [3, 5], ‘t’: [3], ‘o’: [4], ‘r’: [4], ‘k’: [5]}Explanation : Characters mapped with their occurring elements indices.
Method #1 : Using defaultdict() + enumerate() + split()
The combination of above functions can be used to solve this problem. In this, we use defaultdict() to get empty list to store indices, enumerate() is used to check for indices and split() can be used for splitting characters. 
Python3
# Python3 code to demonstrate working of # Charatacter indices Mapping in String List# Using defaultdict() + enumerate() + split()from collections import defaultdict  # initializing listtest_list = ['g f g', 'i s', 'b e s t', 'f o r', 'g e e k s']   # printing original listprint("The original list is : " + str(test_list))  res = defaultdict(set)  # loop for assigning indicesfor idx, ele in enumerate(test_list):    for sub in ele.split():        res[sub].add(idx + 1)  # dictionary comprehension to remake result res = {key: list(val) for key, val in res.items()}  # printing result print("The mapped dictionary : " + str(res))
The original list is : ['g f g', 'i s', 'b e s t', 'f o r', 'g e e k s']
The mapped dictionary : {'g': [1, 5], 'f': [1, 4], 'i': [2], 's': [2, 3, 5], 'b': [3], 'e': [3, 5], 't': [3], 'o': [4], 'r': [4], 'k': [5]}

Method #2 : Using enumerate() + dictionary comprehension
This is another way in which this task can be performed. This performs task in similar way, just in one liner way in dictionary comprehension.
Python3
# Python3 code to demonstrate working of # Charatacter indices Mapping in String List# Using enumerate() + dictionary comprehension  # initializing listtest_list = ['g f g', 'i s', 'b e s t', 'f o r', 'g e e k s']   # printing original listprint("The original list is : " + str(test_list))  # using dictionary comprehension to bind resultres = {sub : [key + 1 for key, val in enumerate(test_list) if sub in val]        for ele in test_list for sub in ele.split()}  # printing result print("The mapped dictionary : " + str(res))
The original list is : ['g f g', 'i s', 'b e s t', 'f o r', 'g e e k s']
The mapped dictionary : {'g': [1, 5], 'f': [1, 4], 'i': [2], 's': [2, 3, 5], 'b': [3], 'e': [3, 5], 't': [3], 'o': [4], 'r': [4], 'k': [5]}

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Draw tree using Turtle module in Python

01 Oct, 2020
Prerequisite: Turtle module, Drawing Triangle, Drawing Rectangle
There are many modules in python which depicts graphical illustrations, one of them is turtle, it is an in-built module in Python, which lets the user control a pen(turtle) to draw on screen(drawing board). It is mostly used to illustrate figures, shapes, designs etc. In this article, we will learn how to draw a simple tree using the turtle module. Illustrating a Tree consists of creating a single rectangle and then three triangles of same sizes sequentially from the bottom.
Below are the steps to create a tree:
Import turtle and math module.Set screen with dimensions and color.Create a turtle object.Create tree by illustrating stacked triangles and a rectangle.
Import turtle and math module.
Set screen with dimensions and color.
Create a turtle object.
Create tree by illustrating stacked triangles and a rectangle.
Below is the program of the above approach:
Python3
# Python program to draw a tree using turtle # Importing required modulesimport turtleimport math    # Function to draw rectangledef drawRectangle(t, width, height, color):    t.fillcolor(color)    t.begin_fill()    t.forward(width)    t.left(90)    t.forward(height)    t.left(90)    t.forward(width)    t.left(90)    t.forward(height)    t.left(90)    t.end_fill()        # Function to draw triangle    def drawTriangle(t, length, color):    t.fillcolor(color)    t.begin_fill()    t.forward(length)    t.left(135)    t.forward(length / math.sqrt(2))    t.left(90)    t.forward(length / math.sqrt(2))    t.left(135)    t.end_fill()        # Set the background colorscreen = turtle.Screen ( )screen.bgcolor("skyblue")    # Creating turtle objecttip = turtle.Turtle()tip.color ("black")tip.shape ("turtle")tip.speed (2)    # Tree basetip.penup()tip.goto(100, -130)tip.pendown()drawRectangle(tip, 20, 40, "brown")    # Tree toptip.penup()tip.goto(65, -90)tip.pendown()drawTriangle(tip, 90, "lightgreen")tip.penup()tip.goto(70, -45)tip.pendown()drawTriangle(tip, 80, "lightgreen")tip.penup()tip.goto(75, -5)tip.pendown()drawTriangle(tip, 70, "lightgreen")
Output:-
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Numbers | choice() function

10 Jan, 2018
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string.
Syntax:
random.choice(sequence)
Parameters: 
sequence is a mandatory parameter that
can be a list, tuple, or string.
Returns:  
The choice() returns a random item. 
Note:We have to import random to use choice() method.
Below is the Python3 implementation of the above approach:
# Python3 program to demonstrate the use of# choice() method   # import random import random  # prints a random value from the listlist1 = [1, 2, 3, 4, 5, 6] print(random.choice(list1))  # prints a random item from the string string = "striver" print(random.choice(string))  
The output every-time will be different as the system returns a random item.Output:
5
s

Practical application:Print any random number 5 times from a given list.
# Python3 program to demonstrate the practical application# choice()   # import random module import random   list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   for x in range(5):    print(random.choice(list1))
The output changes every time as choice() function is used.Output:
1
4
1
5
7

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Taking input in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
How to disable input type text area ?

23 Apr, 2020
In this article, we get to know how to disable an input type=text by using the input disabled attribute. A disabled input is un-clickable and unusable. It is a boolean attribute. The disabled elements are not submitted in the form.
Syntax:
<input type="text" disabled>
Example:
<!DOCTYPE html><html>  <head>    <title>HTML input disabled Attribute</title></head>  <body style="text-align:center">    <h1 style="color: green;">GeeksforGeeks</h1>    <h2>HTML input disabled Attribute</h2>      <label>Input:          <!--A disabled input-->        <input type="text" name="value"                 value="This input field                 is disabled" disabled>    </label></body>  </html>
Output:
Supported Browsers: The browsers supported by <input> disabled attribute are listed below:
Apple Safari 1.0
Google Chrome 1.0
Firefox 1.0
Opera 1.0
Internet Explorer 6.0
HTML-Misc
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Index.astype()

16 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.astype() function create an Index with values cast to dtypes. The class of a new Index is determined by dtype. When conversion is impossible, a ValueError exception is raised.
Syntax: Index.astype(dtype, copy=True)
Parameters :dtype : numpy dtype or pandas typecopy : By default, astype always returns a newly allocated object. If copy is set to False and internal requirements on dtype are satisfied, the original data is used to create a new Index or the original Index is returned.
Example #1: Use Index.astype() function to change the data type of index from float to integer type.
# importing pandas as pdimport pandas as pd   # Creating the Indexdf=pd.Index([17.3, 69.221, 33.1, 15.5, 19.3, 74.8, 10, 5.5])  print("Dtype before applying function: \n", df)  print("\nAfter applying astype function:")# Convert df datatype to 'int64'df.astype('int64')
Output :
 
Example #2: Use Index.astype() function to change the datatype of the given Index to string form.
# importing pandas as pdimport pandas as pd   # Creating the Indexdf=pd.Index([17.3, 69.221, 33.1, 15.5, 19.3, 74.8, 10, 5.5])  print("Dtype before applying function: \n", df)  print("\nAfter applying astype function:")# Convert df datatype to 'int64'df.astype('str')
Output :
 Example #3: Let’s do something interesting with index.astype() method.
Observe this DataFrame.
Setting ‘Number’ column as index.
# importing pandas module  import pandas as pd     # reading csv file from url  data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")      # dropping null value columns to avoid errors data.dropna(inplace = True)   # Setting Number column as indexdata = data.set_index('Number')  # Setting index as Nonedata.index.names = [None]data.head(5)
Output:
Now, let’s convert the index to integer.
# applying astype on indexdata.index.astype('int64')
Output:
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between textContent and innerText - GeeksforGeeks

14 Dec, 2020
1. textContent :This property is used to set or return the text value of the selected node and all its descendants. While setting the textContent property, any child nodes are removed. It is replaced by a single Text node containing the specified string.
Syntax :
To set the text of node –node.textContent = text
node.textContent = text
To return the text of node –node.textContent
node.textContent
2. innerText :This property also sets or returns the text value of the selected node and all its descendants. However, there are some differences shown using the following example.
<!DOCTYPE html><html><head>  <title>    Differences between innerText and textContent.  </title></head><body>  <h3>Differences between innerText & textContent.</h3>  <p id="demo"> This element has extra       spacing and contains <span>a span element</span>.</p>    <button onclick="getInnerText()">Get innerText</button>  <button onclick="getTextContent()">Get textContent</button>    <p id="demo"></p>  <script>    function getInnerText() {      alert(document.getElementById("demo").innerText)    }      function getTextContent() {      alert(document.getElementById("demo").textContent)    }  </script></body></html>
[/tabbyending]
Output :Before clicking any buttons :
After clicking on innerText button :
After clicking on textContent button :
The innerText property returns the text, without spacing and the textContent property returns the text along with spacing.
Other differences between innerText :
Sl No.
innerText
textContent
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Basics
Difference Between
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Informed and Uninformed Search in AI
Difference between Internal and External fragmentation
Difference between HashMap and HashSet
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Create array with MongoDB query?

You can use the concept of toArray() to create array. Following is the syntax −
db.yourCollectonName.find({}, {yourFieldName:1}).toArray();
Let us create a collection with documents −
> db.createArrayDemo.insertOne({"UserName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6461de8cc557214c0e00")
}
> db.createArrayDemo.insertOne({"UserName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6467de8cc557214c0e01")
}
> db.createArrayDemo.insertOne({"UserName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd646cde8cc557214c0e02")
}
> db.createArrayDemo.insertOne({"UserName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6470de8cc557214c0e03")
}
Display all documents from a collection with the help of find() method −
> db.createArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbd6461de8cc557214c0e00"), "UserName" : "Chris" }
{ "_id" : ObjectId("5cbd6467de8cc557214c0e01"), "UserName" : "David" }
{ "_id" : ObjectId("5cbd646cde8cc557214c0e02"), "UserName" : "Robert" }
{ "_id" : ObjectId("5cbd6470de8cc557214c0e03"), "UserName" : "Sam" }
Case 1 − Create array with MongoDB.
If you want to create an array of field UserName and do not want the field _id, use the below query.
> db.createArrayDemo.find({},{_id:0}, {UserName:1}).toArray();
This will produce the following output −
[
   {
      "UserName" : "Chris"
   },
   {
      "UserName" : "David"
   },
   {
      "UserName" : "Robert"
   },
   {
      "UserName" : "Sam"
   }
]
Case 2 − Create array with MongoDB with field name_id only
If you want to create an array with field name _id only, use the below query.
> db.createArrayDemo.find({}, {_id:1}).toArray();
This will produce the following output −
[
   {
      "_id" : ObjectId("5cbd6461de8cc557214c0e00")
   },
   {
      "_id" : ObjectId("5cbd6467de8cc557214c0e01")
   },
   {
      "_id" : ObjectId("5cbd646cde8cc557214c0e02")
   },
   {
      "_id" : ObjectId("5cbd6470de8cc557214c0e03")
   }
]
HTML <link> disabled attribute - GeeksforGeeks

08 Jun, 2021
The Disabled attribute for <link> element in HTML is used to specify that the linked document is disabled. A disabled link is un-clickable and unusable. It is a boolean attribute.
Syntax:
<link disabled> ----- </link>
Example:
html
<!DOCTYPE html><html> <head>    <link id="linkid"        rel="stylesheet"        type="text/css"        href="styles.css"        sizes="16*16"        hreflang="en-us" disabled></head> <body style="text-align:center;">    <h1>GeeksForGeeks</h1>    <h2><link> disabled Attribute</h2> </body> </html>   
Output:
Supported Browsers:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Java Examples - Display Thread status

How to display thread status?
Following example demonstrates how to display different status of thread using isAlive() & getStatus() methods of Thread.
class MyThread extends Thread {
   boolean waiting = true;
   boolean ready = false;
   MyThread() {
   }
   public void run() {
      String thrdName = Thread.currentThread().getName();
      System.out.println(thrdName + " starting.");
      
      while(waiting) System.out.println("waiting:"+waiting);
      System.out.println("waiting...");
      startWait();
      try {
         Thread.sleep(1000);
      } catch(Exception exc) {
         System.out.println(thrdName + " interrupted.");
      }
      System.out.println(thrdName + " terminating.");
   }
   synchronized void startWait() {
      try {
         while(!ready) wait();
      } catch(InterruptedException exc) {
         System.out.println("wait() interrupted");
      }
   }
   synchronized void notice() {
      ready = true;
      notify();
   }
}
public class Main {
   public static void main(String args[]) throws Exception {
      MyThread thrd = new MyThread();
      thrd.setName("MyThread #1");
      showThreadStatus(thrd);
      
      thrd.start();
      Thread.sleep(50);
      showThreadStatus(thrd);
      
      thrd.waiting = false;
      Thread.sleep(50);
      showThreadStatus(thrd);
      
      thrd.notice();
      Thread.sleep(50);
      showThreadStatus(thrd);
      
      while(thrd.isAlive())
      System.out.println("alive");
      showThreadStatus(thrd);
   }
   static void showThreadStatus(Thread thrd) {
      System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );
   }
}
The above code sample will produce the following result.
MyThread #1 Alive:false State:NEW
MyThread #1 starting.
waiting:true
waiting:true
alive
alive
MyThread #1 terminating.
alive
MyThread #1 Alive:false State:TERMINATED

 Print
 Add Notes
 Bookmark this page
find_element_by_css_selector() driver method – Selenium Python

24 Nov, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. 
This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_css_selector() is discussed in this article. With this strategy, the first element with the matching CSS selector will be returned. If no element has a matching CSS selector, a NoSuchElementException will be raised.
Syntax – 
driver.find_element_by_css_selector("CSS Selectors")
Example – 
For instance, consider this page source: 
HTML
<html> <body>  <p class="content">Site content goes here.</p> </body><html>
Now after you have created a driver, you can grab an element using – 
content = driver.find_element_by_css_selector('p.content') 
Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its id “GSC-i-id2”. 
Create a file called run.py to demonstrate find_element_by_css_selector method –  
Python3
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_css_selector("input.gsc-i-id2") # print complete elementprint(element)
Now run using – 
Python run.py
First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. 
Browser Output – 
Terminal Output – 
 
NaveenArora
kumaripunam984122
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to write N as sum of two or more positive integers in C++

In this problem, we are given an integer n. Our task is to find the total number of ways in can be expressed as sum of two or more positive integers.
Let’s take an example to understand the problem,
N = 4
5
4 can be written as the sum in these ways,
4, 3+1, 2+2, 2+1+1, 1+1+1+1
To solve this problem, we will use Euler’s recurrence formula. For a number n the total number of ways it can be generated p(n) by,
Σ∞n=0 p(n)xn = Π∞k=1 (1/(1-xk ))
Using this formula, we will derive formula for p(n),p(n) = p(n-1) + p(n-2) - p(n-5) - p(n-7) + ... + (-1)(k-1)((k(3k-1))/2)
Program to illustrate the implementation of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
long long postiveSum(int n){
   vector<long long> p(n + 1, 0);
   p[0] = 1;
   for (int i = 1; i <= n; ++i) {
      int k = 1;
      while ((k * (3 * k - 1)) / 2 <= i) {
         p[i] += (k % 2 ? 1 : -1) * p[i - (k * (3 * k - 1)) / 2];
         if (k > 0)
            k *= -1;
         else
            k = 1 - k;
      }
   }
   return p[n];
}
int main(){
   int N = 12;
   cout<<"The number of ways "<<N<<" can be written as sum of two or more positive numbers is "      <<postiveSum(N);
   return 0;
}
The number of ways 12 can be written as sum of two or more positive numbers is 77
How to add a user to the group on linux

The concept of “group” may be confusing to many Linux users. Linux operating system is designed to allow more than one user to have access to the Linux system at a time. Linux/Unix operating systems provides multitasking abilities to its multi-users. In order to do this task, we need to assign a group to each Linux user. This article gives step by step process on – how to add a user to the group in Linux system.
To create a new user using Linux command line, use the following command –
$ sudo useradd tutorialspoint
The above command is used to create a tutorialspoint user to the Linux system.To see the user list, use the following command –
$ awk -F':' '{ print $1}' /etc/passwd
A sample output will be as below –
.......
syslog
messagebus
usbmux
dnsmasq
avahi-autoipd
kernoops
rtkit
saned
whoopsie
speech-dispatcher
avahi
lightdm
colord
hplip
pulse
linux
gitlog
gitdaemon
tutorialspoint
For example, in the above result, you can see that tutorialspoint user is created.
To add a new group in Linux, use the following command –
$ sudo groupadd editors
In the above command ,It is creates a group called editors.
For adding tutorialspoint user to the editors group, use the following command –
$ sudo usermod -a -G editors tutorialspoint
To change the user’s primary group, use the following command –
$ sudo usermod -g linux tutorialspoint
In the above command, assign tutorialspoint user to linux group.
If you’re trying to figure out permissions assigned to a user, then you have to use the id command to see a group which is linked with the particular user. The following is the command line –
$ id tutorialspoint
The sample output will be like this –
uid=1001(tutorialspoint) gid=1000(linux) groups=1000(linux),1002(editors)

Sometimes, you may need to create a user which should have specific accessible rights or directories, then in these cases, use the following command to create a new user and assign a group as below –
$ sudo useradd -g linux john
The above command creates a user called john and which will be added to the linux group. Use the following command to assign a password to john user –
$ sudo passwd john
The sample output should be like this –
linux@linux:~$ sudo passwd john
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
For example, you might be required to add a user to multiple groups. To do this, use the following command –
$ sudo usermod -a -G linux,editors tutorialspoint
The above command turialspoint user is added to the linux and editors  groups.
Congratulations! Now, you know “How to add a User to the Group on Linux”. We’ll learn more about these type of commands in our next Linux post. Keep reading!
Controlling the main thread in Java

A thread can be created by implementing the Runnable interface and overriding the run() method.
The Main thread in Java is the one that begins executing when the program starts. All the child threads are spawned from the Main thread. Also, it is the last thread to finish execution as various shut-down actions are performed by it.
A program that demonstrates this is given as follows:
 Live Demo
public class Demo {
   public static void main(String args[]) {
      Thread t = Thread.currentThread();
      System.out.println("Main thread: " + t);
      t.setName("current");
      System.out.println("Current thread: " + t);
      try {
         for (int i = 1; i <= 5; i++) {
            System.out.println(i);
            Thread.sleep(10);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread is interrupted");
      }
      System.out.println("Exiting the Main thread");
   }
}
Main thread: Thread[main,5,main]
Current thread: Thread[current,5,main]
1
2
3
4
5
Exiting the Main thread
How to make a call-able link using HTML ?

11 Oct, 2019
With the rise of mobile web surfing the benefits of calling directly from a web page have become more realistic. Making a call-able link is easy with the use of HTML. HTML provides browsers with protocols such as tel which are used to add clickable phone numbers. Every browser responds differently to these protocols. Some launch the phone app with the number on the display, waiting for you to call while others directly make the call.
Approach:
Add tel:(a number) inside href attribute of the anchor tag.
You can even add country code for international calls as a part of the number.
Some phone numbers have an extension. You can add p before the extension that will cause a one second delay before dialling the next phone.
Syntax:
<a href="tel:(countrycode)(NUMBER)p(extension)"> Text </a>
Example 1: This example create a call-able link using HTML.
<!DOCTYPE html><html>  <head>    <title>        How to make a call-able        link using HTML ?    </title>          <style>        body {            text-align:center;        }        h1 {            color:green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>          <h3>        Make a call-able link using HTML    </h3>          <a href="tel:9876765678">        Call to GeeksforGeeks support    </a></body>  </html>
Output:
Before click on the link:
After click on the link:
Example 2: This example create a call-able link using HTML.
<!DOCTYPE html><html>  <head>    <title>        How to make a call-able        link using HTML ?    </title>          <style>        body {            text-align:center;        }        h1 {            color:green;        }        a {            text-decoration:none;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>          <h3>        Make a call-able link using HTML    </h3>          <a href="tel:9876765678p107">         Help    </a></body>  </html>
Output:
Before click on the link:
After click on the link:
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rename multiple files using Python

05 Apr, 2022
Prerequisite: OS module in PythonIn Python3, rename() method is used to rename a file or directory. This method is a part of the os module and comes in extremely handy.  
Syntax for os.rename() :
os.rename(src, dst) : src is source address of file to be renamed and dst is destination with the new name.
Now say given n images in a folder having random names. For example, consider the image below:
Now the requirement is to rename them in ordered fashion like hostel1, hostel2, ...and so on. Doing this manually would be a tedious task but this target can be achieved using the rename() and listdir() methods in the os module. 
The listdir method lists out all the content of a given directory.
Syntax for listdir() : 
list = os.listdir(‘src’) : where src is the source folder to be listed out.
The following code will do the job for us. It traverses through the lists of all the images in xyz folder, defines the destination (dst) and source (src) addresses, and renames using rename module. 
The accepted format for destination (dst) and source (src) addresses to be given as arguments in os.rename(src,dst) is “folder_name/file_name”.  Below is the implementation : 
Python3
# Python 3 code to rename multiple# files in a directory or folder # importing os moduleimport os # Function to rename multiple filesdef main():       folder = "xyz"    for count, filename in enumerate(os.listdir(folder)):        dst = f"Hostel {str(count)}.jpg"        src =f"{folder}/{filename}"  # foldername/filename, if .py file is outside folder        dst =f"{folder}/{dst}"                 # rename() function will        # rename all the files        os.rename(src, dst) # Driver Codeif __name__ == '__main__':         # Calling main() function    main()
Output :The output of this code will look something like this –  
Note : This code may not run in online IDE, since it use external image file directory. 
ChristopherGarland
gurmeharsinghkhalsa1005
simmytarika5
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Check String is Empty or Not in Dart (Null Safety)?

09 Aug, 2021
We can check a string is empty or not by the String Property isEmpty. If the string is empty then it returns True if the string is not empty then it returns False.
Syntax: String.isEmpty 
Return : True or False.
Example 1:
Dart
// main function startvoid main() {       // initialise a string st    String? st = "";       // print string is empty or not    print(st.isEmpty);}
Output:
true
Example 2:
Dart
// main function startvoid main() {       // initialise a string st    String? st = "Geeksforgeeks";       // print string is empty or not    print(st.isEmpty);}
 Output:
false
rk220217
Dart-String
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ListView Class in Flutter
Flutter - Search Bar
Flutter - Dialogs
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
Flutter - Pop Up Menu
Android Studio Setup for Flutter Development
What is widgets in Flutter?
Flutter - RichText Widget
Flutter - CircleAvatar Widget
How to find critical value for one-sided and two-sided t test in R?

To find the critical value for t test in R, we need to use qt function. This function requires level of significance and the sample size and returns the tabulated or critical value of t distribution. Below examples shows the calculation of critical value for different situations such as left-side test, right-side test or two-sided test.
Left side critical value with sample size 30 and 95% confidence level −
 Live Demo
qt(0.05,30)
[1] -1.697261
Right side critical value with sample size 30 and 95% confidence level −
 Live Demo
abs(qt(0.05,30))
[1] 1.697261

 Live Demo
qt(0.05,50)
[1] -1.675905
 Live Demo
abs(qt(0.05,50))
[1] 1.675905

 Live Demo
qt(0.01,50)
[1] -2.403272
 Live Demo
abs(qt(0.01,50))
[1] 2.403272

 Live Demo
qt(0.01,51)
[1] -2.401718
 Live Demo
abs(qt(0.01,51))
[1] 2.401718

 Live Demo
qt(0.01,100)
[1] -2.364217
 Live Demo
abs(qt(0.01,100))
[1] 2.364217

 Live Demo
qt(0.01,20)
[1] -2.527977
 Live Demo
abs(qt(0.01,20))
[1] 2.527977

 Live Demo
qt(0.10,36)
[1] -1.305514
 Live Demo
abs(qt(0.10,36))
[1] 1.305514

Two-sided critical value for 90% confidence level with sample size of 36 −
 Live Demo
abs(qt(0.10/2,36))
[1] 1.688298
 Live Demo
abs(qt(0.01/2,101))
[1] 2.625386

 Live Demo
abs(qt(0.05/2,89))
[1] 1.986979
Call by value and Call by reference in Java

Call by Value means calling a method with a parameter as value. Through this, the argument value is passed to the parameter.
While Call by Reference means calling a method with a parameter as a reference. Through this, the argument reference is passed to the parameter.
In call by value, the modification done to the parameter passed does not reflect in the caller's scope while in the call by reference, the modification done to the parameter passed are persistent and changes are reflected in the caller's scope.
Following is the example of the call by value −
The following program shows an example of passing a parameter by value. The values of the arguments remain the same even after the method invocation.
 Live Demo
public class Tester{
   public static void main(String[] args){
      int a = 30;
      int b = 45;
      System.out.println("Before swapping, a = " + a + " and b = " + b);
      // Invoke the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping values will be same here**:");
      System.out.println("After swapping, a = " + a + " and b is " + b);
   }
   public static void swapFunction(int a, int b) {
      System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
      // Swap n1 with n2
      int c = a;
      a = b;
      b = c;
      System.out.println("After swapping(Inside), a = " + a + " b = " + b);
   }
}
This will produce the following result −
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45
Java uses only call by value while passing reference variables as well. It creates a copy of references and passes them as valuable to the methods. As reference points to same address of object, creating a copy of reference is of no harm. But if new object is assigned to reference it will not be reflected.
 Live Demo
public class JavaTester {
   public static void main(String[] args) {
      IntWrapper a = new IntWrapper(30);
      IntWrapper b = new IntWrapper(45);
      System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);
      // Invoke the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping values will be different here**:");
      System.out.println("After swapping, a = " + a.a + " and b is " + b.a);
   }
   public static void swapFunction(IntWrapper a, IntWrapper b) {
      System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);
      // Swap n1 with n2
      IntWrapper c = new IntWrapper(a.a);
      a.a = b.a;
      b.a = c.a;
      System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);
   }
}
class IntWrapper {
   public int a;
   public IntWrapper(int a){ this.a = a;}
}
This will produce the following result −
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be different here**:
After swapping, a = 45 and b is 30
How to reset the root password of RedHat/CentOS Linux - GeeksforGeeks

30 Jan, 2020
RedHat Linux is a worldwide used OS in servers and networking devices. Red Hat lists Adobe, Ampersand and many among the top 500 fortune companies. They list Cisco, Dell, HP, and IBM as partners. Resetting the root password of RHEL is not a difficult task but rather you need to know 4 commands and you are into the root account!Root account in Linux is that user which has unlimited power in Linux without any restrictions. This article revolves about how one can reset the root password of RedHat/CentOS Linux. We are working here with the latest version of RHEL which is RHEL 8.
STEP 1: Start your OS and you will see this screen as soon you start your OS.Press e, a new screen will come as shown below.The place where green arrow is there, type
rd.break enforcing=0
.Press Ctrl+X to continue that process.When BIOS loads up your OS, in between that rd.break will stop that process there and enforcing will stop the security of RHEL which is SELINUX from any intervention.
STEP 2: you will get this screen like shown belowYou are in Emergency mode now. This is the main screen and most of the work will be done here.command 1:
mount -o remount, rw /sysroot/
command 2:
chroot /sysroot/
Type
passwd root
and enter the desired password twice.>you will get a bash shell from where you can change the root password as per your own choice.The command for changing password in Linux is passwd username. now type
exit
twice.Congrats, you have successfully changed the root password of RHEL without any intervention of SELinux(Security-Enhanced Linux) and you can login into root account with that password.But wait, after logging in the SElinux becomes active again and encrypts your /etc/passwd file which is a highly secured file where all users and link to their passwords are kept.
STEP 3:So, a last command to decrypt that filecommand 3:
restorecon /etc/shadow
.Follow all the steps in order explained and you will be easily able to reset root account password.
Technical Scripter 2019
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
What is dot operator in Java?

The (.) operator is also known as member operator it is used to access the member of a package or a class.
public class Sample {
   void display() {
      double d = 20.3;
      int i = (int)d;
      System.out.println(i);
   }

   public static void main(String args[]) {
      Sample s = new Sample();
      s.display();
   }
}
20
Fletcher’s Checksum

Fletcher checksum is an error – detection technique that uses two checksums to determine single-bit errors in a message transmitted over network channels. It is a block code technique that was devised by John G. Fletcher in 1970s at Lawrence Livermore Labs, USA.
The checksums are created based on the data values in the data blocks to be transmitted and appended to the data. When the receiver gets this data, the checksums are re-calculated and compared with the existing checksums. A non-match indicates an error.
The error-detection capabilities of this method is nearly same as that of Cyclic Redundancy Check (CRC) but requires much less computational effort.
There are three popular algorithms of Fletcher’s checksum −
Fletcher – 16 − The data word is divided into 8-bit blocks. Then, two 8-bit checksums are computed and are appended to form a 16-bit Fletcher checksum.
Fletcher – 16 − The data word is divided into 8-bit blocks. Then, two 8-bit checksums are computed and are appended to form a 16-bit Fletcher checksum.
Fletcher – 32 − The data word is divided into 16-bit blocks. Two 16-bit checksums are computed and are appended to form a 32-bit Fletcher checksum.
Fletcher – 32 − The data word is divided into 16-bit blocks. Two 16-bit checksums are computed and are appended to form a 32-bit Fletcher checksum.
Fletcher – 64 − The data word is divided into 32-bit blocks. Two 32-bit checksums are computed and are appended to form a 32-bit Fletcher checksum.
Fletcher – 64 − The data word is divided into 32-bit blocks. Two 32-bit checksums are computed and are appended to form a 32-bit Fletcher checksum.
INPUT : data blocks of equal sizes, b1,b2............ bn
OUTPUT : two checksums, checksum1 and checksum2, of 1 byte each
Step 1) Initialize partial sums, and sums, c1=0 and c2=0
Step 2) For each data block, bi
i. Add bi to c1
ii. Add updates value of c1 to c2
Step 3) Compute checksums,
checksum1= c1 MOD 256 and checksum2= c2 MOD 256
Step 4) Append checksums, checksum1 and checksum2, to the data blocks, b1,b2............ bn
Let there be five data blocks, 163, 200, 19, 74 and 88. The computations are −
Block Number    Data Block   c1    c2
     -              -        0     0
     1             163      163   163
     2             200      363   526
     3              19      382 908
4 74 456 1364
5 88 544 1908
checksum1 = 544 MOD 256 = 34 
checksum2 = 1908 MOD 256 = 123
Assign an SQL result to variable from prepared statement in MySQL?

For this, use stored procedure. Let us first create a table −
mysql> create table DemoTable(Id int, Name varchar(100));
Query OK, 0 rows affected (1.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10,'John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(11,'Chris');
Query OK, 1 row affected (0.41 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+-------+
| Id | Name    |
+------+-------+
| 10 | John    |
| 11 | Chris   |
+------+-------+
2 rows in set (0.00 sec)
Following is the query to assign SQL result to variable from prepared statement in MySQL −
mysql> DELIMITER //
mysql> CREATE PROCEDURE Prepared_Statement_Demo( nameOfTable VARCHAR(20), IN nameOfColumn VARCHAR(20), IN idColumnName INT)
BEGIN
   SET @holdResult=CONCAT('SELECT ', nameOfColumn, ' INTO @value FROM ', nameOfTable, ' WHERE id = ', idColumnName);
      PREPARE st FROM @holdResult;
      EXECUTE st;
      DEALLOCATE PREPARE st;
   END //
Query OK, 0 rows affected (0.20 sec)
mysql> DELIMITER ;
Call the stored procedure using call command −
mysql> call Prepared_Statement_Demo('DemoTable','Name',10);
Query OK, 0 rows affected, 2 warnings (0.00 sec)
Now check the value of variable @value −
mysql> select @value;
This will produce the following output −
+--------+
| @value |
+--------+
| John   |
+--------+
1 row in set (0.00 sec)
Design Pattern - Factory Pattern

Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.
Create an interface.
Shape.java
public interface Shape {
   void draw();
}
Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
Square.java
public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
Circle.java
public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}
Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
public class ShapeFactory {
	
   //use getShape method to get object of type shape 
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }		
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
         
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
         
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      
      return null;
   }
}
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of square
      shape3.draw();
   }
}
Verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.


    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page