code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.pyplot.get_plot_commands() in Python - GeeksforGeeks

10 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The get_plot_commands() method in pyplot module of matplotlib library is used to get the sorted list of all of the plotting commands.
Syntax: matplotlib.pyplot.get_plot_commands()
Parameters: This method does not accept any parameters.
Returns: This method returns sorted list of all of the plotting commands.
Below examples illustrate the matplotlib.pyplot.get_plot_commands() function in matplotlib.pyplot:
Example:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt       w = plt.get_plot_commands()  print("List of all of the plotting commands : ")for i in w:    print(i)
Output:
List of all of the plotting commands : 
acorr
angle_spectrum
annotate
arrow
autoscale
axes
axhline
axhspan
axis
axvline
axvspan
bar
barbs
barh
box
boxplot
broken_barh
cla
clabel
clf
clim
close
cohere
colorbar
contour
contourf
csd
delaxes
draw
errorbar
eventplot
figimage
figlegend
fignum_exists
figtext
figure
fill
fill_between
fill_betweenx
findobj
gca
gcf
gci
get_figlabels
get_fignums
grid
hexbin
hist
hist2d
hlines
imread
imsave
imshow
install_repl_displayhook
ioff
ion
isinteractive
legend
locator_params
loglog
magnitude_spectrum
margins
matshow
minorticks_off
minorticks_on
pause
pcolor
pcolormesh
phase_spectrum
pie
plot
plot_date
plotfile
polar
psd
quiver
quiverkey
rc
rc_context
rcdefaults
rgrids
savefig
sca
scatter
sci
semilogx
semilogy
set_cmap
setp
show
specgram
spy
stackplot
stem
step
streamplot
subplot
subplot2grid
subplot_tool
subplots
subplots_adjust
suptitle
switch_backend
table
text
thetagrids
tick_params
ticklabel_format
tight_layout
title
tricontour
tricontourf
tripcolor
triplot
twinx
twiny
uninstall_repl_displayhook
violinplot
vlines
xcorr
xkcd
xlabel
xlim
xscale
xticks
ylabel
ylim
yscale
yticks
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How to Get the minimum value from the Pandas dataframe in Python? - GeeksforGeeks

14 Jan, 2022
In this article, we will discuss how to get the minimum value from the Pandas dataframe in Python.
We can get the minimum value by using the min() function
Syntax:
dataframe.min(axis)
where, 
axis=0 specifies column
axis=1 specifies row
To get the minimum value in a dataframe row simply call the min() function with axis set to 1.
Syntax:
dataframe.min(axis=1)
Example: Get minimum value in a dataframe row
Python3
# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({    'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'],    'subjects': ['java', 'php', 'html/css', 'python', 'R'],    'marks': [98, 90, 78, 91, 87],    'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in rowdata.min(axis=1)
Output:
To get the minimum value in a column simply call the min() function using axis set to 0.
Syntax:
dataframe.min(axis=0)
Example: Get minimum value in a column
Python3
# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({    'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'],    'subjects': ['java', 'php', 'html/css', 'python', 'R'],    'marks': [98, 90, 78, 91, 87],    'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in columndata.min(axis=0)
Output:
To get the minimum value in a particular column call the dataframe with the specific column name and min() function.
Syntax:
dataframe['column_name'].min()
Example: Get the minimum value in a particular column 
Python3
# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 4 columnsdata = pd.DataFrame({    'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'],    'subjects': ['java', 'php', 'html/css', 'python', 'R'],    'marks': [98, 90, 78, 91, 87],    'age': [11, 23, 23, 21, 21]}) # display dataframeprint(data) # get the minimum in name  columnprint(data['name'].min()) # get the minimum in subjects  columnprint(data['subjects'].min()) # get the minimum in age  columnprint(data['age'].min()) # get the minimum in marks  columnprint(data['marks'].min())
Output:
sumitgumber28
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
What is the Halting Problem in TOC?

Usually, programs consist of loops that are limited or unlimited in length.
The total work done by the program completely depends on the input given to the program.
The program may consist of several different numbers of loops that may be in linear or nested manner.
The Halting Problem is the problem of deciding or concluding based on a given arbitrary computer program and its input, whether that program will stop executing or run-in an infinite loop for the given input.
The Halting Problem tells that it is not easy to write a computer program that executes in the limited time that is capable of deciding whether a program halts for an input.
In addition to that the Halting Problem never says that it is not practicable to determine whether a given random program is going to halt (stop).
Generally, it asks the question like “Given a random program and an input, conclude whether the given random program is going to halt when that input is given”.
An example of writing the Halting Problem is as follows −
INPUT − Program P and a string S.
OUTPUT − if P stops on S, it returns 1.
Otherwise, if P enters into an endless loop on S, it returns 0.
Let us consider the Halting Problem called H having the solution.
Now H takes the following two inputs −
Program P
Program P
Input S.
Input S.
If P stops on S, then H results in “halt”, otherwise H gives the result “loop”.
The diagrammatic representation of H is as follows −
ATM = {(M,w) | M is a TM and M halts at input w }.
We can build a universal Turing machine which can simulate any Turing machine on any input.
Let’s consider TM which recognizing the Altering Turing Machine (ATM) −
Recognize-ATM (<M,w>)
   Simulate M using UTM till it halts
   If M halts and accept then
      Accept
   Else
      Reject
Suppose, if M goes into an infinite loop on input w, then the TM Recognize-ATM is going to run forever which means TM is only a recognizer, not a decider.
A decider for this problem would call a halt to simulations that loop forever.
Now the question is whether an ATM is TM decidable is equivalent to asking the question whether we can tell if a TM M will halt on input w.
Because of this, both versions of this question are generally called the halting problem.
How to set text font family in HTML?

To change the text font family in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-family. HTML5 do not support the <font> tag, so the CSS style is used to add font size.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to change the text font family in an HTML page
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Font Family</title>
   </head>

   <body>
      <h1>Our Products</h1>
      <p style="font-family:georgia,garamond,serif;">
         This is demo text
      </p>
   </body>
</html>
PyQt5 QSpinBox - Getting the sender signal index value - GeeksforGeeks

28 May, 2020
In this article we will see how we can get the spin box sender signal index value. Sender signal index is the meta-method index of the signal that called the currently executing slot, which is a member of the class returned by sender. If called outside of a slot activated by a signal, -1 is returned.
In order to do this we use senderSignalIndex method with the spin box object.
Syntax : spin_box.senderSignalIndex()
Argument : It takes no argument
Return : It returns integer value
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for widgets    def UiComponents(self):        # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 250, 40)          # setting range to the spin box        self.spin.setRange(1, 999999)          # setting prefix to spin        self.spin.setPrefix("PREFIX ")          # setting suffix to spin        self.spin.setSuffix(" SUFFIX")          # creating a label        self.label = QLabel(self)          # making label multi line        self.label.setWordWrap(True)          # setting label geometry        self.label.setGeometry(100, 200, 250, 60)          # getting sender signal index        value = self.spin.senderSignalIndex()          # setting text to the label        self.label.setText("Sender Signal Index : " + str(value))    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
How to use the wildcard character (*) in Get-ChildItem in PowerShell?

You can also search for files with a specific name or using the wildcard (*) character.
Below command will search for the files (including hidden files) starting with “Bac”.
Get-ChildItem D:\Temp -Recurse -Force -Include Bac*
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp -Recurse -Force -Include Bac*
    Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       24-11-2018     11:34           6215 Backup.xml
When you use the wildcard character (*) at both the ends, file name containing that string will be displayed. For example, the below command will display all the files which contain the word “tmp”.
Get-ChildItem D:\Temp\ -Recurse -Force -Include *tmp*

PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Recurse -Force -Include *tmp*
    Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\DomainSysvol\GPO\Machine\microsoft\windows
    nt\SecEdit
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       24-11-2018     11:34          16028 GptTmpl.inf
Powershell - Read XML File

Get-Content cmdlet is used to read content of a xml file.
In this example, we're reading content of test.xml.
Get-Content D:\temp\test\test.xml 

You can see following output in PowerShell console.
<title>Welcome to TutorialsPoint</title>


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
C# Program to Check a Specified Type is an Interface or not - GeeksforGeeks

23 Nov, 2021
The interface is just like a class, it can also have methods, properties, events, etc. as its members, but it only contains the declaration of the members and the implementation of these members will be given by the class that implements the interface implicitly or explicitly. We can check the specified type is an interface or not by using the IsInterface property of the Type class. It will return true if the given type is an interface. Otherwise, it will return false. It is a read-only property.
Syntax:
public bool IsInterface { get; }
Example 1:
C#
// C# program to check whether the // given type is interface or notusing System;using System.Reflection;  // Declare an interfaceinterface myinterface{          // Method in interface    void gfg();}  class GFG{      // Driver codestatic void Main(){          // Check the type is interface or not    // Using the IsInterface property    if (typeof(myinterface).IsInterface == true)     {        Console.WriteLine("Yes it is Interface");    }    else     {        Console.WriteLine("No it is not an Interface");    }}}
Output:
Yes it is Interface
Example 2:
C#
// C# program to check whether the // given type is interface or notusing System;using System.Reflection;  // Declare an interfaceinterface myinterface{          // Method in interface    void gfg();}  // Declare a classpublic class myclass{    public void myfunc(){}}  // Declare a structpublic struct mystruct{    int a;}  class GFG{      // Driver codestatic void Main(){          // Check the type is interface or not    // Using the IsInterface property    Console.WriteLine(typeof(myinterface).IsInterface);    Console.WriteLine(typeof(myclass).IsInterface);    Console.WriteLine(typeof(mystruct).IsInterface);}}
Output:
True
False
False
CSharp-Interfaces
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | List Class
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
How to rename the drive letter in Windows using PowerShell?

We can rename a drive letter of a disk using PowerShell with the Set-Partition command. An example is shown below.
In the Windows OS, we have E: and we need to rename its partition to the F: You can run the below command.
Set-Partition -DriveLetter 'E' -NewDriveLetter 'F'
You can also run the Get-Partition command and Pipeline the Set-Partition command. For example,
Get-Partition -DriveLetter 'E' | Set-Partition -NewDriveLetter 'F'
If you want to rename the drive on the remote computer, then you need to take the CIMSession of the system and run the command. For example,
$sess = New-CimSession -ComputerName 'Test1-Win2k12' Set-Partition -CimSession $sess -DriveLetter 'E' -NewDriveLetter 'F'
How to get the list of shared folders using PowerShell?

Get-SmbShare gives all the shared folders on the local system.
PS C:\Temp> Get-SmbShare
Name    ScopeName    Path       Description
----    ---------    ----       -----------
ADMIN$    *       C:\Windows    Remote Admin
C$        *       C:\ Default    share
DSC       *       E:\DSC
E$        *       E:\           Default share
IPC$      *                      Remote IPC
Shared1   *       E:\Extract
To get the shared folders on the remote computer we can use the CIM session. For example,
$sess = New-CimSession -ComputerName Labmachine2k16
Get-SmbShare -Session $sess
PS C:\Users\Administrator> Get-SmbShare -Session $sess
Name       ScopeName Path          Description    PSComputerName
----       --------- ----          -----------    --------------
ADMIN$       *       C:\Windows    Remote Admin    Labmachine2k16
C$           *       C:\ Default   share           Labmachine2k16
DSC          *       E:\DSC                        Labmachine2k16
E$           *       E:\           Default share   Labmachine2k16
IPC$         *                     Remote IPC      Labmachine2k16
Shared1      *       E:\Extract                    Labmachine2k16
What are the different operations on files in C language?

The operations that can be carried out on files in C language are as follows −
Naming the file.
Opening the file.
Reading from the file.
Writing into the file.
Closing the file.
The syntax for opening and naming file is as follows −
FILE *File pointer;
For example, FILE * fptr;
File pointer = fopen ("File name”, "mode”);
For example, fptr = fopen ("sample.txt”, "r”)
FILE *fp;
fp = fopen ("sample.txt”, "w”);
The modes of opening the file in C language are explained below −
Write mode of opening the file
The syntax is as follows −
FILE *fp;
fp =fopen ("sample.txt”, "w”);
If the file is not existing, then a new file is created.
If the file exists then, old content gets erased and current content will be stored.
Read mode of opening the file
The syntax is as follows −
FILE *fp
fp =fopen ("sample.txt”, "r”);
If the file is not existing, then fopen function returns NULL value.
If the file exists, then data is read successfully from file
Append mode of opening a file
The syntax is as follows −
FILE *fp;
fp =fopen ("sample.txt", "a");
If the file doesn’t exist, then a new file will be created.
If the file exists, the current content will be adding to the old content.
Following is the C program for operations on files −
 Live Demo
//Program for copying the contents of one file into another file
#include <stdio.h>
#include <stdlib.h> // For exit()
int main(){
   FILE *fptr1, *fptr2;
   char filename[100], c;
   printf("Enter the filename to open for reading \n");
   scanf("%s",filename);
   // Open one file for reading
   fptr1 = fopen(filename, "r");
   if (fptr1 == NULL){
      printf("Cannot open file %s \n", filename);
      exit(0);
   }
   printf("Enter the filename to open for writing \n");
   scanf("%s", filename);
   // Open another file for writing
   fptr2 = fopen(filename, "w");
   if (fptr2 == NULL){
      printf("Cannot open file %s \n", filename);
      exit(0);
   }
   // Read contents from file
   c = fgetc(fptr1);
   while (c != EOF){
      fputc(c, fptr2);
      c = fgetc(fptr1);
   }
   printf("\nContents copied to %s", filename);
   fclose(fptr1);
   fclose(fptr2);
   return 0;
}
When the above program is executed, it produces the following result −
Enter the filename to open for reading
file2.txt
Enter the filename to open for writing
file1.txt
Contents copied to file1.txt
How to set a cookie and get a cookie with JavaScript?

The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:
document.cookie = "key1=value1;key2=value2;expires=date";
Here the “expires” attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
Try the following. It sets a customer name in an input cookie.
Live Demo
<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("Enter some value!");
                  return;
               }
               cookievalue= escape(document.myform.customer.value) + ";";
               document.cookie="name=" + cookievalue;
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>
   </head>
   <body>
      <form name="myform" action="">
         Enter name: <input type="text" name="customer"/>
         <input type="button" value="Set Cookie" onclick="WriteCookie();"/>
      </form>
   </body>
</html>
Reading a cookie is just as simple as writing one because of the value of the document.cookie object is the cookie. So, you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where the name is the name of a cookie and value is its string value.
You can try to run the following code to read a cookie −
Live Demo
<html>
   <head>
      <script>
         <!--
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );
               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(';');
               // Now take key value pair out of this array
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split('=')[0];
                  value = cookiearray[i].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>
   </head>
   <body>
      <form name="myform" action="">
         <p> click the following button and see the result:</p>
         <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
      </form>
   </body>
</html>
How can I tell when a MySQL table was last updated?

We can know that with the help of the column name ‘UPDATED_TIME’ using information_schema.tables with WHERE clause.
Let us first create a table for our example.
mysql> create table MyISAMTableDemo
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.56 sec)
Inserting some records into table.
mysql> insert into MyISAMTableDemo values(1);
Query OK, 1 row affected (0.72 sec)

mysql> insert into MyISAMTableDemo values(2);
Query OK, 1 row affected (0.16 sec)
Syntax to know the last updated time.
SELECT UPDATE_TIME
FROM   information_schema.tables
WHERE  TABLE_SCHEMA = 'yourDatabaseName'
AND TABLE_NAME = 'yourTableName';
Let us implement the following query to get the last updated time.
mysql> SELECT UPDATE_TIME
   -> FROM   information_schema.tables
   -> WHERE  TABLE_SCHEMA = 'business'
   ->  AND TABLE_NAME = 'MyISAMTableDemo';
The following is the output.
+---------------------+
| UPDATE_TIME         |
+---------------------+
| 2018-11-01 19:00:02 |
+---------------------+
1 row in set (0.08 sec)
Differences between static and non-static variables in Java

A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
A static variable is also called a class variable and is common across the objects of the class and this variable can be accessed using class name as well.
Any variable of a class which is not static is called non-static variable or an instance variable.
Following are the important differences between static and non-static variable.
public class JavaTester {
   public int counter = 0;
   public static int staticCounter = 0;
   public JavaTester(){
      counter++;
      staticCounter++;
   }
   public static void main(String args[]) {
      JavaTester tester = new JavaTester();
      JavaTester tester1 = new JavaTester();
      JavaTester tester2 = new JavaTester();
      System.out.println("Counter: " + tester2.counter);
      System.out.println("Static Counter: " + tester2.staticCounter);
   }
}
Counter: 1
Static Counter: 3
How to alter a MySQL Column from varchar(30) to varchar(100)?

You need to use ALTER TABLE command along with MODIFY
The syntax is as follows
ALTER TABLE yourTableName MODIFY COLUMN yourColumnName varchar(100) NOT NULL;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table syntaxOfAlterCommandDemo
   -> (
   -> UserId int,
   -> UserName varchar(30),
   -> UserAge int,
   -> UserCityName varchar(50)
   -> );
Query OK, 0 rows affected (0.51 sec)
Let us check the description of the table.
The query is as follows
mysql> desc syntaxOfAlterCommandDemo;
The following is the output
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| UserId       | int(11)     | YES  |     | NULL    |       |
| UserName     | varchar(30) | YES  |     | NULL    |       |
| UserAge      | int(11)     | YES  |     | NULL    |       |
| UserCityName | varchar(50) | YES  |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.04 sec)
Now let us change UserName column from varchar(30) to varchar(100). Remember, right now we have set the UserName column to varchar(30). The query is as follows to change the column
mysql> alter table syntaxOfAlterCommandDemo modify column UserName varchar(100) NOT NULL;
Query OK, 0 rows affected (1.36 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the table description once again.
The query is as follows
mysql> desc syntaxOfAlterCommandDemo;
The following is the output
+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| UserId       | int(11)      | YES  |     | NULL    |       |
| UserName     | varchar(100) | NO   |     | NULL    |       |
| UserAge      | int(11)      | YES  |     | NULL    |       |
| UserCityName | varchar(50)  | YES  |     | NULL    |       |
+--------------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
Look at the sample output above, the column UserName is now varchar(100).
Tryit Editor v3.7

HTML Input types
Tryit: input type = range
How to count the total number of tables in a page in Selenium with python?

We can count the total number of tables in a page in Selenium with the
help of find_elements method. While working on any tables, we will always find
the tagname in the html code and its value should be table (<table>).
This characteristic is only applicable to tables on that particular page and to no
other types of UI elements like edit box, radio buttons and so on.
To retrieve all the elements with the tagname as a table we will use
find_elements_by_tag_name() method. This method returns a list of web elements
with the type of tagname specified in the method argument. In case there are no
matching elements, an empty list will be returned.
After the list of tables is fetched, in order to count its total numbers, we need to
get the size of that list. The size of the list can be obtained from the len() method
of the list data structure.
Finally this length is printed on the console.
driver.find_elements_by_tag_name("table")
Code Implementation for counting the number of tables.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to get the list of tables present on the web page
t = driver.find_elements_by_tag_name('table')
#print the count with the len method on console
print(len(t))
#to close the browser
driver.quit()
Minimum Moves to Equal Array Elements in C++

Suppose we have an array of size n, we have to find the minimum number of moves required to make all array elements the same, where a move means incrementing n - 1 elements by 1.
So, if the input is like [3,2,3,4], then the output will be 4.
To solve this, we will follow these steps −
n := size of nums
n := size of nums
if n is same as 0, then −return 0
if n is same as 0, then −
return 0
return 0
sort the array nums
sort the array nums
ans := 0
ans := 0
for initialize i := 0, when i < n, update (increase i by 1), do −ans := ans + nums[i] - nums[0]
for initialize i := 0, when i < n, update (increase i by 1), do −
ans := ans + nums[i] - nums[0]
ans := ans + nums[i] - nums[0]
return ans
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int minMoves(vector<int>& nums) {
      int n = nums.size();
      if (n == 0)
         return 0;
      sort(nums.begin(), nums.end());
      int ans = 0;
      for (int i = 0; i < n; i++) {
         ans += nums[i] - nums[0];
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {3,2,3,4};
   cout << (ob.minMoves(v));
}
{3,2,3,4}
4
Enum with Customized Value in Java

An enum in java represents a group of named constants. It can also have custom properties and methods.
Let us look at an example.
import java.lang.*;

// enum showing Mobile prices
enum Mobile {
   Samsung(400), Nokia(250),Motorola(325);

   int price;
   Mobile(int p) {
      price = p;
   }
   int showPrice() {
      return price;
   }
}

public class EnumDemo {
   public static void main(String args[]) {
      System.out.println("CellPhone List:");

      for(Mobile m : Mobile.values()) {
         System.out.println(m + " costs " + m.showPrice() + " dollars");
      }

      Mobile ret = Mobile.Motorola;
      System.out.println("MobileName = " + ret.name());
   }
}
This will produce the following result −
CellPhone List:
Samsung costs 400 dollars
Nokia costs 250 dollars
Motorola costs 325 dollars
MobileName = Motorola
Here we've added a price as field and showPrice() as method to Enum.
Here we've added a price as field and showPrice() as method to Enum.
We've assign custom values to enum using its constructor.
We've assign custom values to enum using its constructor.
How to Move an Image in Tkinter canvas with Arrow Keys?

Tkinter Canvas widget is one of the versatile widgets in the Tkinter library. It is used to create different shapes, images, and animating objects. We can provide a dynamic attribute to the image defined in a Canvas widget by using the move() method.
Define the image and the coordinates as a parameter in the move(Image, x,y) method to move the Image in the Canvas. We declare images globally in order to track the Image location in the Canvas.
We can follow these steps to make our image movable within the canvas,
First, define the Canvas widget and add images to it.
First, define the Canvas widget and add images to it.
Define the move() function to allow the image to be dynamic within the Canvas.
Define the move() function to allow the image to be dynamic within the Canvas.
Bind the Arrow Keys with the function that allows images to be moved within the Canvas.
Bind the Arrow Keys with the function that allows images to be moved within the Canvas.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a Canvas widget
canvas = Canvas(win, width=600, height=400, bg="white")
canvas.pack(pady=20)

# Add Images to Canvas widget
image = ImageTk.PhotoImage(Image.open('favicon.ico'))
img = canvas.create_image(250, 120, anchor=NW, image=image)

def left(e):
   x = -20
   y = 0
   canvas.move(img, x, y)

def right(e):
   x = 20
   y = 0
   canvas.move(img, x, y)

def up(e):
   x = 0
   y = -20
   canvas.move(img, x, y)

def down(e):
   x = 0
   y = 20
   canvas.move(img, x, y)

# Bind the move function
win.bind("<Left>", left)
win.bind("<Right>", right)
win.bind("<Up>", up)
win.bind("<Down>", down)

win.mainloop()
Running the above code will display a window that contains an image that can be moved across the window using the arrow keys.
You can move the object on the canvas around with the Arrow keys.
Whitespaces in Perl

A Perl program does not care about whitespaces. Following program works perfectly fine −
#!/usr/bin/perl
print    "Hello, world\n";
But if spaces are inside the quoted strings, then they would be printed as is. For example −
 Live Demo
#!/usr/bin/perl
# This would print with a line break in the middle
print "Hello
         world\n";
This will produce the following result −
Hello
      world
All types of whitespace like spaces, tabs, newlines, etc. are equivalent to the interpreter when they are used outside of the quotes. A line containing only whitespace, possibly with a comment, is known as a blank line, and Perl totally ignores it.
Trigger a button click and generate alert on form submission in JavaScript

Let’s say the following is our button −
<button id="submitForm">Submit</button>
On the basis of button id, on form submission, generate an alert −
$("#submitForm").click(function() {
   alert("The Form has been Submitted.");
});
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
CollegeId=<input id="collegeId" type="text"><br />
CollegeName= <input id="collegeName" type="text"><br />
<button id="submitForm">Submit</button>
<script>
   $("#submitForm").click(function() {
      alert("The Form has been Submitted.");
   });
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
After clicking the button, you can see the following output −
Finger command in Linux with Examples - GeeksforGeeks

10 May, 2020
Finger command is a user information lookup command which gives details of all the users logged in. This tool is generally used by system administrators. It provides details like login name, user name, idle time, login time, and in some cases their email address even. This tool is similar to the Pinky tool but the Pinky tool is just the lightweight version of this tool.
To install finger tool use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install finger
In case of CentOS/RedHat
$sudo yum install finger
In case of Fedora OS
$sudo dnf install finger
1. To finger or get details of a user.
$finger manav

Note: Here “manav” is the username.
As can be seen, it displays the login name, name, directory, shell, login time, email, and plan of the user.
2. To get idle status and login details of a user.
$finger -s manav

As can be seen, it displays the idle status along with the details of the user.
3. To avoid printing PGP key, plan and project details
$finger -p manav

As can be seen, it displays the login name, name, directory, shell, login time, email, but not the plan, PGP key, and project of the user.
4. To create a plan for a user.
$echo "Plan details" > ~/.plan

Now, after again using finger command it will display a plan for the user.
5. To create a project for a user.
$echo "Project details" > ~/.project

Now, after again using finger command it will display a project for the user.
6. To create a PGP key for a user.
$echo "pgpkey" > ~/.pgpkey

Now, after again using finger command it will display a PGP key for the user.
linux-command
Linux-Unix
Write From Home
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
SED command in Linux | Set 2
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Shell Script to Display the Digits which are in Odd Position

09 Feb, 2022
Here given a list of numbers, our task is to find the odd position from the given number.
Example:
Input: 123456
Output: 135
Explanation: 1, 2, 3 are at odd position.

Input: 34567
Output: 357
Explanation: 3, 5, 7 are at odd position.
We will have to input a number from the user for a dynamic script.  After the number input, we need to whether the input is a number or not. We may also accept numbers with signs as well.  We’ll have to input from the user until he/she inputs a pure number. Then we may exactly how many digits are there in the variable, we then need to loop through only the odd positioned digits and print the same. Usage of cut, read, and other basic Linux utility tools to make the task simpler and efficient.
Approach:
Take input from users.
Count of the digits.
Select the particular digits.
Handle + and – symbols (sign).
Get the result.
Below is the implementation:
#!/bin/bash
n=0
while ! [[ $n =~ "^[-+]?[0-9]+$" ]]
do
    read -p "Enter a number : " n
    l=${#n}
    if [[ $n =~ ^[+-]?[0-9]+$ ]];then
        if [[ $n =~ ^[+-] ]];then
            i=2
        if   
        if [[ $n =~ ^[0-9] ]];then
            i=1
        if
        while [ $i -le $l ]
        do
            d=$(echo $n | cut -c $i)
            echo $d    
            i=$(($i + 2)) 
        done
    break    
    if
done
Output:
anikaseth98
rkbhola5
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Python program to find Tuples with positive elements in List of tuples

31 Jan, 2022
Given a list of tuples. The task is to get all the tuples that have all positive elements.
Examples:
Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements.
Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple with all positive elements. 
Method #1 : Using list comprehension + all()
In this, all() is used to check for all the tuples, list comprehension helps in the iteration of tuples.
Python3
# Python3 code to demonstrate working of# Positive Tuples in List# Using list comprehension + all() # initializing listtest_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original listprint("The original list is : " + str(test_list)) # all() to check each elementres = [sub for sub in test_list if all(ele >= 0 for ele in sub)] # printing resultprint("Positive elements Tuples : " + str(res))
Method #2 : Using filter() + lambda + all()
In this, the task of filtration is performed using filter() and lambda function.
Python3
# Python3 code to demonstrate working of# Positive Tuples in List# Using filter() + lambda + all() # initializing listtest_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)] # printing original listprint("The original list is : " + str(test_list)) # all() to check each elementres = list(filter(lambda sub: all(ele >= 0 for ele in sub), test_list)) # printing resultprint("Positive elements Tuples : " + str(res))
adnanirshad158
Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Pandas Series.dt.month

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.month attribute return a numpy array containing the month of the datetime in the underlying data of the given series object.
Syntax: Series.dt.month
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',                '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object.
# return the monthresult = sr.dt.month  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.month attribute has successfully accessed and returned the month of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12',                       periods = 5, freq = 'H'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.month attribute to return the month of the datetime in the underlying data of the given Series object.
# return the monthresult = sr.dt.month  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.month attribute has successfully accessed and returned the month of the datetime in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
How to Print all Keys of the LinkedHashMap in Java?

17 Dec, 2020
LinkedHashMap is a predefined class in Java that is similar to HashMap, contains a key and its respective value. Unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to print all the Keys present in our LinkedHashMap in java. We have to iterate through each Key in our LinkedHashMap and print It.
Example :
Input : Key- 1  : Value-5
    Key- 29 : Value-13
    Key- 14 : Value-10
    Key- 34 : Value-2
    Key- 55 : Value-6

Output: 1, 29, 14, 34, 55
Method 1: Use for-each loop to iterate through LinkedHashMap. For each iteration, we print the respective key using getKey() method.
for(Map.Entry<Integer,Integer>ite : LHM.entrySet())
    System.out.print(ite.getKey()+", ");
Example 1:
Java
// Java program to print all keys of the LinkedHashMap  import java.util.*;import java.io.*;  class GFG {    public static void main(String[] args)    {          // create a linkedhashmap        LinkedHashMap<Integer, Integer> LHM            = new LinkedHashMap<>();            // Add mappings        LHM.put(1, 5);        LHM.put(29, 13);        LHM.put(14, 10);        LHM.put(34, 2);        LHM.put(55, 6);            // print keys using getKey() method        for (Map.Entry<Integer, Integer> ite :             LHM.entrySet())            System.out.print(ite.getKey() + ", ");    }}
1, 29, 14, 34, 55,
Example 2:
Java
// Java program to print all keys of the LinkedHashMap  import java.util.*;import java.io.*;  class GFG {    public static void main(String[] args)    {        // create a linkedhashmap        LinkedHashMap<String, String> LHM            = new LinkedHashMap<>();          // Add mappings        LHM.put("Geeks", "Geeks");        LHM.put("for", "for");        LHM.put("Geeks", "Geeks");          // print keys using getKey() method        for (Map.Entry<String, String> ite : LHM.entrySet())            System.out.print(ite.getKey() + ", ");    }}
Geeks, for,
Method 2: (Using keySet() method)
Syntax:
hash_map.keySet()
Parameters: The method does not take any parameters.
Return Value: The method returns a set having the keys of the hash map.
Java
import java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {        // create an instance of linked hashmap        LinkedHashMap<String, String> lhm            = new LinkedHashMap<String, String>();          lhm.put("One", "Geeks");        lhm.put("Two", "For");        lhm.put("Three", "Geeks");          // get all keys using the keySet method        Set<String> allKeys = lhm.keySet();          // print keys        System.out.println(allKeys);    }}
[One, Two, Three]
Java-LinkedHashMap
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Python | math.isqrt() method

04 Dec, 2020
Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.isqrt() method in Python is used to get the integer square root of the given non-negative integer value n. This method returns the floor value of the exact square root of n or equivalently the greatest integer a such that a2 <= n.
Note: This method is new in Python version 3.8. 
Syntax: math.isqrt(n) 
Parameter: n: A non-negative integer 
Returns: an integer value which represents the floor of exact square root of the given non-negative integer n.  
Code #1: Use of math.isqrt() method
Python3
# Python Program to explain# math.isqrt() method  import math n = 10 # Get the floor value of# exact square root of nsqrt = math.isqrt(n)print(n) n = 100 # Get the floor value of# exact square root of nsqrt = math.isqrt(n)print(n)
3
10
 
Code #2: Use of math.isqrt() method to check whether the given integer is a perfect square.
Python3
# Python Program to explain# math.isqrt() method  import math  def isPerfect(n):         # Get the floor value of    # exact square root of n    sqrt = math.isqrt(n)         if sqrt * sqrt == n:        print(f"{n} is perfect square")         else :        print(f"{n} is not a perfect square")   # Driver's codeisPerfect(100)isPerfect(10)
100 is perfect square
10 is not a perfect square
 
Code #3: Use of math.isqrt() method to find the next perfect square of n.
Python3
# Python Program to explain# math.isqrt() method  import math n = 11  def Next(n):         # Get the ceiling of    # exact square root of n    ceil = 1 + math.isqrt(n)         # print the next perfect square of n    print("Next perfect square of {} is {}".          format(n, ceil*ceil))  # Driver's codeNext(11)Next(37)
Next perfect square after 11 is 16
Next perfect square after 37 is 49
 
Akanksha_Rai
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.