code-rag-bench/online-tutorials huggingface dataset:
LocalDate get() method in Java with Examples

28 Nov, 2018
The get() method of LocalDate class in Java method gets the value of the specified field from this Date as an int.
Syntax:
public int get(TemporalField field)

Parameter: This method accepts a parameter field which is the field to get and not necessary null.
Return Value: It returns the value for the field.
Exceptions: The function throws three exceptions as described below:
DateTimeException: this exception is thrown if a value for the field cannot be obtained or the value is outside the range of valid values for the field.
UnsupportedTemporalTypeException: this exception is thrown if the field is not supported or the range of values exceeds an int
ArithmeticException: this exception is thrown if numeric overflow occurs
Below programs illustrate the get() method of LocalDate in Java:Program 1:
// Program to illustrate the get() method  import java.util.*;import java.time.*;import java.time.temporal.ChronoField;  public class GfG {    public static void main(String[] args)    {          LocalDate dt = LocalDate.parse("2017-02-16");        System.out.println(dt.get(ChronoField.MONTH_OF_YEAR));    }}
2

Program 2:
// Program to illustrate the get() method// Exception Program  import java.util.*;import java.time.*;import java.time.temporal.ChronoField;  public class GfG {    public static void main(String[] args)    {        try {            LocalDate dt = LocalDate.parse("2017-02-30");            System.out.println(dt.get(ChronoField.MONTH_OF_YEAR));        }        catch (Exception e) {            System.out.println(e);        }    }}
java.time.format.DateTimeParseException: 
Text '2017-02-30' could not be parsed: Invalid date 'FEBRUARY 30'

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/temporal/TemporalField.htmlhttps://docs.oracle.com/javase/10/docs/api/java/time/temporal/TemporalField.html
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Sorting string using order defined by another string

11 May, 2020
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once.
Examples:
Input : pat = "asbcklfdmegnot", str = "eksge" 
Output : str = "geeks"
(after sorting, str becomes "skeeg" and return its reverse)

Input : pat = "mgewqnasibkldjxruohypzcftv", str = "niocgd"
Output : str = "coding"

The idea is to first maintain a dictionary according to the index provided in Pattern and then passing the lambda function(which uses utility of dictionary) into the sort function.Below is the implementation of above idea.
# Python program to sort a string and return# its reverse string according to pattern string  # This function will return the reverse of sorted string# according to the pattern  def sortbyPattern(pat, str):      priority = list(pat)      # Create a dictionary to store priority of each character    myDict = { priority[i] : i for i in range(len(priority))}      str = list(str)      # Pass lambda function as key in sort function    str.sort( key = lambda ele : myDict[ele])      # Reverse the string using reverse()    str.reverse()      new_str = ''.join(str)    return new_str    if __name__=='__main__':    pat = "asbcklfdmegnot"    str =  "eksge"    new_str = sortbyPattern(pat, str)    print(new_str)
Output:
geeks
Time Complexity: n*log(n) where n is the length of the string
Python string-programs
python-lambda
Python-sort
Sorting Quiz
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove last K elements of list

08 Jun, 2022
We often come to situations in which we need to decrease the size of the list by truncating the k last elements of the list. This particular problem occurs when we need to optimize memory. This has its application in the day-day programming when sometimes we require to get all the lists of similar size. Let’s discuss certain ways in which this task can be performed. 
Method #1: Using len() + list slicing List slicing can perform this particular task in which we just slice the first len(list) – K elements to be in the list and hence remove the last K elements. 
Python3
# Python code to demonstrate# remove last K elements# using len() + list slicing # initializing list test_list = [1, 4, 6, 3, 5, 8] # printing original listprint ("The original list is : " + str(test_list)) # initializing KK = 3 # using len() + list slicing# remove last K elementsres = test_list[: len(test_list) - K] # printing resultprint ("The list after removing last K elements : " +  str(res))
The original list is : [1, 4, 6, 3, 5, 8]
The list after removing last K elements : [1, 4, 6]

Method #2: Using Negative list slicing We can perform this particular task using the negative list slicing in which we start removing the elements from the last index of the list and hence remove all the K elements from the last. We remove None if 0 elements are asked to be removed. 
Example
Python3
# Python code to demonstrate# remove last K elements# using negative list slicing # initializing list test_list = [1, 4, 6, 3, 5, 8] # printing original listprint ("The original list is : " + str(test_list)) # initializing KK = 3 # using negative list slicing# remove last K elementsres = test_list[: -K or None] # printing resultprint ("The list after removing last K elements : " +  str(res))
The original list is : [1, 4, 6, 3, 5, 8]
The list after removing last K elements : [1, 4, 6]
Method 3: Using pop() method: the pop() method will remove the last element from the list, So to remove last k elements from the python list, we need to perform the pop() operation k times.
Example
Python3
# Python code to demonstrate# remove last K elements# using negative list slicing # initializing list test_list = [1, 7, 6, 3, 5, 8] # printing original listprint ("The original list is : " + str(test_list)) # initializing KK = 3 # using pop()# remove last K elementsfor i in range(K):  test_list.pop() # printing resultprint ("The list after removing last K elements : " +  str(test_list))
The original list is : [1, 7, 6, 3, 5, 8]
The list after removing last K elements : [1, 7, 6]

pulamolusaimohan
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a table with auto-increment column in MySQL using JDBC?

While creating a table, in certain scenarios, we need values to column such as ID, to be generated/incremented automatically. Various databases support this feature in different ways.
In MySQL database you can declare a column auto increment using the following syntax.
CREATE TABLE table_name(
   ID INT PRIMARY KEY AUTO_INCREMENT,
   column_name1 data_type1,
   column_name2 data_type2,
   column_name3 data_type3,
   column_name4 data_type4,
   ............ ...........
);
MySQL query to create a table with auto-incremented column.
CREATE TABLE Sales(
   ID INT PRIMARY KEY AUTO_INCREMENT,
   ProductName VARCHAR (20) NOT NULL,
   CustomerName VARCHAR (20) NOT NULL,
   DispatchDate date,
   DeliveryTime timestamp,
   Price INT,
   Location varchar(20)
);
Following JDBC program establishes a connection with MYSQL database and creates a query with an auto-incremented column.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class AutoIncrementedColumns_Oracle {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Creating the sales table with auto-incremented values
      String createQuery = "CREATE TABLE Sales("
         + "ID INT PRIMARY KEY AUTO_INCREMENT, "
         + "ProductName VARCHAR (20) NOT NULL, "
         + "CustomerName VARCHAR (20) NOT NULL, "
         + "DispatchDate date, "
         + "DeliveryTime timestamp, "
         + "Price INT, "
         + "Location varchar(20))";
      //Executing the query
      stmt.execute(createQuery);
      System.out.println("Table created......");
   }
}
Connection established......
Table created......
The DESCRIBE command in MYSQL gives the description of a table, you can verify the creation of the table with auto-incremented column using it, as shown below −
mysql> describe sales;
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| ID           | int(11)     | NO   | PRI | NULL    | auto_increment |
| ProductName  | varchar(20) | NO   |     | NULL    |                |
| CustomerName | varchar(20) | NO   |     | NULL    |                |
| DispatchDate | date        | YES  |     | NULL    |                |
| DeliveryTime | time        | YES  |     | NULL    |                |
| Price        | int(11)     | YES  |     | NULL    |                |
| Location     | varchar(20) | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
How to change file permissions in Python?

To change the permission of a file, you can use the os.chmod(file, mode) call. Note that the mode should be specified in octal representation and therefore must begin with a 0o. For example, to make a file readonly, you can set the permission to 0o777, you can use:
>>> import os
>>> os.chmod('my_file', 0o777)
You can also use flags from the stat module. You can read more about these flags here: http://docs.python.org/2/library/stat.html
Another way to acheive it is using a subprocess call:
>>> import subprocess
>>> subprocess.call(['chmod', '0444', 'my_file'])
How to handle popup windows in Selenium?

Selenium has getWindowHandles() method , which returns all the window handle ids for all the open windows. This is stored in Set data structure in String data types.
In order to navigate to a specific window, we need to traverse to the window we want to access with the iterator() method then switch to that window.
getWindowHandle() method gives the window handle id of the current window Id.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
import org.testng.annotations.Test;
public class WindowHandles{
   @Test
   public void windowHandle() throws Exception {
      System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // getting the current window handle id
      String currentwindow = driver.getWindowHandle();
      // getting all the window handles in Set data structure
      Set<String> allWindows = driver.getWindowHandles();
      // traversing each ids with the help of iterator()
      Iterator<String> i = allWindows.iterator();
      //Iterating through the window handle ids
      while(i.hasNext()){
         String childwindow = i.next();
         if(!childwindow.equalsIgnoreCase(currentWindow)){
            driver.switchTo().window(childwindow);
            System.out.println("The child window is "+childwindow);
         } else {
            System.out.println("There are no children");
         }
      }
      driver.quit();
   }
}
SQL Tryit Editor v1.6

TRUNCATE TABLE Categories;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to detect vowels vs consonants in Python?

First you should check if the character is an alphabet or not. Then you can create a list of vowels and check if the character is a vowel using this. If not then it must be a consonant. For example,
def vowel_or_consonant(c):
    if not c.isalpha():
        return 'Neither'
    vowels = 'aeiou'
    if c.lower() in vowels:
        return 'Vowel'
    else:
        return 'Consonant'
for c in "hello people":
    print c, vowel_or_consonant(c)
This will give the output:
h Consonant
e Vowel
l Consonant
l Consonant
o Vowel
  Neither
p Consonant
e Vowel
o Vowel
p Consonant
l Consonant
e Vowel
How to Install PIL on Windows? - GeeksforGeeks

09 Sep, 2021
In this article, we will look into the various methods of installing the PIL package on a Windows machine.
Python 
PIP or Ananconda (Depending upon your preference)
Open up the command prompt and use the below command to install the PIL package:
pip install Pillow
The following message will be displayed once the installation is completed:
To verify the installation run the below code in a Python IDE of your choice:
Python3
import PIL  IL.__version__
Output:
Conda users can open up the Anaconda Power Shell and use the below command to install PIL:
conda install -c anaconda Pillow
The following message will be displayed once the installation is completed:
To verify the installation run the below code in a Python IDE of your choice:
Python3
import PILIL.__version__
Output:
Blogathon-2021
how-to-install
Picked
Python-pil
Blogathon
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
Python NOT EQUAL operator
SQL Query to Insert Multiple Rows
Difference Between Local Storage, Session Storage And Cookies
Banking Transaction System using Java
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
list emplace() function in C++ STL - GeeksforGeeks

19 Jul, 2018
The list::emplace() is a built-in function in C++ STL which extends list by inserting new element at a given position.
Syntax:
list_name.emplace(position, element)
Parameters: The function accepts two mandatory parameters which are described below:
position – it specifies the iterator which points to the position in the list where the new element is to be inserted.
args – it specifies the elements to be inserted in the list container.
Return value: It returns a random access iterator which points to the newly inserted element.
Below programs illustrate the above function:
Program 1:
// C++ program to illustrate the// list::emplace() function#include <bits/stdc++.h>using namespace std;  int main(){    // declaration of list    list<int> lis = { 5, 6, 7, 8, 9, 10 };      auto it = lis.emplace(lis.begin(), 2);      // inserts at the beginning of the list    lis.emplace(it, 1);      cout << "List: ";    for (auto it = lis.begin(); it != lis.end(); ++it)        cout << *it << " ";      return 0;}
List: 1 2 5 6 7 8 9 10

Program 2:
// C++ program to illustrate the// list::emplace() function#include <bits/stdc++.h>using namespace std;  int main(){    // declaration of list    list<pair<int, char> > lis;      // inserts at the beginning of the list    auto it = lis.emplace(lis.begin(), 4, 'a');      // inserts at the beginning of the list    lis.emplace(it, 3, 'b');      cout << "List: ";      for (auto it : lis)        cout << "(" << it.first << ", " << it.second << ") ";      return 0;}
List: (3, b) (4, a)

CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Polymorphism in C++
Copy Constructor in C++
Python - max() function - GeeksforGeeks

07 Mar, 2022
Python max() function returns the largest item in an iterable or the largest of two or more arguments.
It has two forms.
max() function with objects
max() function with iterable
Unlike the max() function of C/C++, the max() function in Python can take any type of object and returns the largest among them. In the case of strings, it returns the lexicographically largest value.
Syntax : max(arg1, arg2, *args[, key]) 
Parameters : 
arg1, arg2 : objects of the same datatype
*args : multiple objects
key : function where comparison of iterable is performed based on its return value
Returns : The maximum value 
Python3
var1 = 4var2 = 8var3 = 2 max_val = max(var1, var2, var3)print(max_val)
Output : 
8
 By default, it will return the string with the maximum lexicographic value. 
Python3
var1 = "geeks"var2 = "for"var3 = "geek" max_val = max(var1, var2, var3)print(max_val)
Output : 
for
We will be passing a key function in the max() method. 
Python3
var1 = "geeks"var2 = "for"var3 = "geek" max_val = max(var1, var2, var3,              key=len)print(max_val)
Output : 
geeks
If we pass parameters of different datatypes, then an exception will be raised.
Python3
integer = 5string = "geek" max_val = max(integer, string)print(max_val)
Output : 
TypeError: '>' not supported between instances of 'str' and 'int'
Python3
list = [1.2, 1.3, 0.1]max_value = max(list)print(max_value)
Output:
1.3
Python3
# function to find minimum and maximum position in listdef minimum(a, n):     # inbuilt function to find the position of maximum    maxpos = a.index(max(a))     # printing the position    print ("The maximum is at position", maxpos + 1) # driver codea = [3, 4, 1, 3, 4, 5]minimum(a, len(a))
Output:
The maximum is at position 6
When an iterable is passed to the max() function it returns the largest item of the iterable. 
Syntax : max(iterable, *iterables[, key, default]) Parameters : 
iterable : iterable object like list or string.
*iterables : multiple iterables
key : function where comparison of iterable is performed based on its return value
default : value if the iterable is empty
Returns : The maximum value. 
Python3
string = "GeeksforGeeks" max_val = max(string)print(max_val)
Output : 
s
Python3
string_list = ["Geeks", "for", "Geeks"] max_val = max(string_list)print(max_val)
Output : 
for
Python3
string_list = ["Geeks", "for", "Geek"] max_val = max(string_list, key=len)print(max_val)
Output : 
Geeks
Python3
dictionary = {} max_val = max(dictionary,              default={1: "Geek"})print(max_val)
Output : 
{1: 'Geek'}
kumar_satyam
simranarora5sos
python-basics
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
map rbegin() function in C++ STL - GeeksforGeeks

23 Oct, 2018
The rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map.
SYNTAX:
r_i rbegin();
const_r_i rbegin() const;

Parameters:It does not except any parameters.
Return Value: This method throws a reverse iterator to the reverse beginning of the sequence container.
Time Complexity:
O(1)
Example:
#include <iostream>#include <map>using namespace std;  int main(){      map<char, int> mp = {        { 'a', 1 },        { 'b', 2 },        { 'c', 3 },        { 'd', 4 },        { 'e', 5 },    };      cout << "Map contains "         << "following elements in"         << " reverse order"         << endl;      for (auto i = mp.rbegin(); i != mp.rend(); ++i) {          cout << i->first             << " = "             << i->second             << endl;    }      return 0;}
Map contains following elements in reverse order
e = 5
d = 4
c = 3
b = 2
a = 1

cpp-containers-library
CPP-Library
cpp-map
STL
Technical Scripter 2018
C++
Technical Scripter
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Queue in C++ Standard Template Library (STL)
Convert string to char array in C++
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

30 Sep, 2021
Consider the following processors (ns stands for nanoseconds). Assume that the pipeline registers have zero latency.
P1: Four-stage pipeline with stage 
    latencies 1 ns, 2 ns, 2 ns, 1 ns.
P2: Four-stage pipeline with stage 
    latencies 1 ns, 1.5 ns, 1.5 ns, 1.5 ns.
P3: Five-stage pipeline with stage 
    latencies 0.5 ns, 1 ns, 1 ns, 0.6 ns, 1 ns.
P4: Five-stage pipeline with stage 
    latencies 0.5 ns, 0.5 ns, 1 ns, 1 ns, 1.1 ns. 
Which processor has the highest peak clock frequency?
(A) P1(B) P2(C) P3(D) P4Answer: (C)Explanation:
Peak clock frequency = 1 / Maximum latency

Maximum of latencies is minimum in P3

i.e. 

P1 : f= 1/2 = 0.5 GHz

P2: f=1/1.5 = 0.67 GHz

P4: f=1/1.1 GHz

P3 : f=1/1 GHz =1

Thus P3 is be the right answer


This explanation has been contributed by Abhishek Kumar.
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersPipelining: Previous Year Question part-II | COA | GeeksforGeeks GATE | Harshit NigamWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0031:28 / 40:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=h-14CfDEprU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
How to delete cookies with JSP?

To delete cookies is very simple. If you want to delete a cookie, then you simply need to follow these three steps −
Read an already existing cookie and store it in Cookie object.
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using the setMaxAge() method to delete an existing cookie.
Set cookie age as zero using the setMaxAge() method to delete an existing cookie.
Add this cookie back into the response header.
Add this cookie back into the response header.
Following example will show you how to delete an existing cookie named "first_name" and when you run main.jsp JSP next time, it will return null value for first_name.
 Live Demo
<html>
   <head>
      <title>Reading Cookies</title>
   </head>
   <body>
      <center>
         <h1>Reading Cookies</h1>
      </center>
      <%
         Cookie cookie = null;
         Cookie[] cookies = null;

         // Get an array of Cookies associated with the this domain
         cookies = request.getCookies();

         if( cookies != null ) {
            out.println("<h2> Found Cookies Name and Value</h2>");
            for (int i = 0; i < cookies.length; i++) {
               cookie = cookies[i];
               if((cookie.getName( )).compareTo("first_name") == 0 ) {
                  cookie.setMaxAge(0);
                  response.addCookie(cookie);
                  out.print("Deleted cookie: " +
                  cookie.getName( ) + "<br/>");
               }
               out.print("Name : " + cookie.getName( ) + ", ");
               out.print("Value: " + cookie.getValue( )+" <br/>");
            }
         } else {
            out.println(
            "<h2>No cookies founds</h2>");
         }
      %>
   </body>
</html>
Let us now put the above code in the main.jsp file and try to access it. It will display the following result −
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
Now run  http://localhost:8080/main.jsp  once again and it should display only one cookie as follows −
Found Cookies Name and Value
Name : last_name, Value: Player
You can delete your cookies in the Internet Explorer manually. Start at the Tools menu and select the Internet Options. To delete all cookies, click the Delete Cookies button.
Tryit Editor v3.7

Web Safe Fonts
Tryit: The arial font
How to sort an R data frame column without losing row names?

When we sort a data frame column in R, the row names are lost but we might need them. Therefore, sorting without losing row names is required and it can be done with the help of order function. For example, if we have a data frame called df that has a column x then sorting of x without losing row names can be done by using the below command −
df[order(df$x),,drop=FALSE]
Consider the below data frame −
 Live Demo
x1<-rnorm(20)
x2<-rnorm(20,525,23.2)
df1<-data.frame(x1,x2)
row.names(df1)<-LETTERS[1:20]
df1
      x1       x2
A   1.7337922  534.3863
B  -0.6754809  534.8879
C   0.1106191  520.2269
D   0.2270701  513.5676
E  -0.5678853  558.2216
F  -0.1885840  534.2416
G   0.2192299  552.8982
H   1.5135296  488.6875
I   0.9043322  529.6242
J   0.7014559  552.5001
K   0.2591020  514.1494
L  -1.1273898  580.5344
M  -0.1771963  516.4953
N   0.2317244  503.3607
O   0.6529487  501.4557
P  -0.9165830  496.4222
Q  -2.2928809  490.9002
R   0.7511574  519.3586
S   1.5003125  504.2702
T   1.3791592  496.9542
Sorting df1 based on x2 without losing row names −
df1[order(df1$x2),,drop=FALSE]
       x1        x2
H   1.5135296   488.6875
Q  -2.2928809   490.9002
P  -0.9165830   496.4222
T   1.3791592   496.9542
O   0.6529487   501.4557
N   0.2317244   503.3607
S   1.5003125   504.2702
D   0.2270701   513.5676
K   0.2591020   514.1494
M  -0.1771963   516.4953
R   0.7511574   519.3586
C   0.1106191   520.2269
I   0.9043322   529.6242
F  -0.1885840   534.2416
A   1.7337922   534.3863
B  -0.6754809   534.8879
J   0.7014559   552.5001
G   0.2192299   552.8982
E  -0.5678853   558.2216
L  -1.1273898   580.5344
 Live Demo
y1<-rpois(20,5)
y2<-rpois(20,8)
df2<-data.frame(y1,y2)
row.names(df2)<-letters[1:20]
df2
  y1  y2
a  5   7
b  5   5
c  4   6
d  7   1
e  3   8
f  7   9
g  5   9
h  2   7
i  3  14
j  12  6
k  6   9
l  12  7
m  2   11
n  5   6
o  5   11
p  3   3
q  6   10
r  3   9
s  7   8
t  6   8
Sorting df2 based on y1 without losing row names −
df2[order(df2$y1),,drop=FALSE]
   y1  y2
h  2   7
m  2   11
e  3   8
i  3   14
p  3   3
r  3   9
c  4   6
a  5   7
b  5   5
g  5   9
n  5   6
o  5   11
k  6   9
q  6   10
t  6   8
d  7   1
f  7   9
s  7   8
j  12  6
l  12  7
Box plot and Histogram exploration on Iris data - GeeksforGeeks

20 May, 2019
Attribute Information about data set:
Attribute Information:
   -> sepal length in cm
   -> sepal width in cm
   -> petal length in cm
   -> petal width in cm
   -> class: 
              Iris Setosa
              Iris Versicolour
              Iris Virginica

Number of Instances: 150 

Summary Statistics:
             Min  Max   Mean    SD   Class Correlation
   sepal length: 4.3  7.9   5.84  0.83    0.7826   
    sepal width: 2.0  4.4   3.05  0.43   -0.4194
   petal length: 1.0  6.9   3.76  1.76    0.9490  (high!)
    petal width: 0.1  2.5   1.20  0.76    0.9565  (high!)

Class Distribution: 33.3% for each of 3 classes.

To get the Iris Data click here.
Loading Libraries
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt
Loading Data
data = pd.read_csv("Iris.csv")  print (data.head(10))
Output:
Description
data.describe()
Output:
Info
data.info()
Output: Code #1: Histogram for Sepal Length
plt.figure(figsize = (10, 7))x = data["SepalLengthCm"]  plt.hist(x, bins = 20, color = "green")plt.title("Sepal Length in cm")plt.xlabel("Sepal_Length_cm")plt.ylabel("Count")
Output:
Code #2: Histogram for Sepal Width
plt.figure(figsize = (10, 7))x = data.SepalWidthCm  plt.hist(x, bins = 20, color = "green")plt.title("Sepal Width in cm")plt.xlabel("Sepal_Width_cm")plt.ylabel("Count")  plt.show()
Output:
Code #3: Histogram for Petal Length
plt.figure(figsize = (10, 7))x = data.PetalLengthCm  plt.hist(x, bins = 20, color = "green")plt.title("Petal Length in cm")plt.xlabel("Petal_Length_cm")plt.ylabel("Count")  plt.show()
Output:
Code #4: Histogram for Petal Width
plt.figure(figsize = (10, 7))x = data.PetalWidthCm  plt.hist(x, bins = 20, color = "green")plt.title("Petal Width in cm")plt.xlabel("Petal_Width_cm")plt.ylabel("Count")  plt.show()
Output:
Code #5: Data preparation for Box Plot
# removing Id columnnew_data = data[["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm"]]print(new_data.head())
Output :
Code #6: Box Plot for Iris Data
plt.figure(figsize = (10, 7))new_data.boxplot()
Output :
ManasChhabra2
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Reinforcement learning
Decision Tree Introduction with example
Activation functions in Neural Networks
Read JSON file using Python
Python map() function
Python Dictionary
Taking input in Python
Read a file line by line in Python
Java Program to convert an integer into binary

To convert an integer to binary, use the Integer.toBinaryString() method in Java.
Let’s say the following is the integer we want to convert.
int val = 999;
Converting the above integer to binary.
Integer.toBinaryString(val)
 Live Demo
public class Demo {
    public static void main(String[] args) {
       int val = 999;
       // integer
       System.out.println("Integer: "+val);
       // binary
       System.out.println("Binary = " + Integer.toBinaryString(val));
    }
}
Integer: 999
Binary = 1111100111
Case-insensitive string comparison in C++

In C++ we have strings in standard library. In this program we will see how to check whether two strings are identical or not. In this case we will ignore the case.
Here the logic is simple. We will convert the whole string into lowercase or uppercase strings, then compare them, and return the result.
We have used the algorithm library to get the transform function to convert the string into lowercase string.
Input: Two strings “Hello WORLD” and “heLLO worLD”
Output: Strings are same
Step 1: Take two strings str1, and str2
Step 2: Convert str1, and str2 into lowercase form
Step 3: Compare str1 and str2
Step 4: End
 Live Demo
#include<iostream>
#include <algorithm>
using namespace std;
int case_insensitive_match(string s1, string s2) {
   //convert s1 and s2 into lower case strings
   transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
   transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
   if(s1.compare(s2) == 0)
      return 1; //The strings are same
   return 0; //not matched
}
main() {
   string s1, s2;
   s1 = "Hello WORLD";
   s2 = "heLLO worLD";
   if(case_insensitive_match(s1, s2)) {
      cout << "Strings are same";
   }else{
      cout << "Strings are not same";
   }
}
Strings are same
Check if string begins with punctuation in JavaScript

Let’s say we have the following strings. One of them is beginning with a question mark i.e.
punctuation −
var sentence1 = 'My Name is John Smith.'
var sentence2 = '? My Name is John Smith.'
We need to check whether any of the above two sentences begin with punctuation. To check if
string begins with punctuation, the code is as follows −
var punctuationDetailsRegularExpression=/^[.,:!?]/
var sentence1 = 'My Name is John Smith.'
var output1 = !!sentence1.match(punctuationDetailsRegularExpression)
if(output1==true)
   console.log("This ("+sentence1+") starts with a punctuation");
else
   console.log("This ("+sentence1+") does not starts with a punctuation");
var sentence2 = '? My Name is John Smith.'
var output2 = !!sentence2.match(punctuationDetailsRegularExpression)
if(output2==true)
   console.log("This ( "+sentence2+") starts with a punctuation");
else
   console.log("This ( "+sentence2+" ) does not starts with apunctuation");
To run the above program, you need to use the following command −
node fileName.js.
Here my file name is demo209.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo209.js
This (My Name is John Smith.) does not starts with a punctuation
This ( ? My Name is John Smith.) starts with a punctuation
How to get the absolute value of a number in JavaScript?

To get the absolute value of a number in JavaScript, use the Math.abs() function. It returns the absolute value. The following is the parameter supported by the abs() method −
x − A number
You can try to run the following code to learn how to get the absolute value of a number −
Live Demo
<html>
   <head>
      <title>JavaScript Math abs() Method</title>
   </head>
   
   <body>
      <script>
         var value = Math.abs(-10);
         document.write("First Test Value : " + value );
         var value = Math.abs(null);
         document.write("<br />Second Test Value : " + value );
         var value = Math.abs(20);
         document.write("<br />Third Test Value : " + value );
      </script>
   </body>
</html>
Switch case in R

21 Apr, 2020
Switch case statements are a substitute for long if statements that compare a variable to several integral values. Switch case in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values.
Switch statement follows the approach of mapping and searching over a list of values. If there is more than one match for a specific value, then the switch statement will return the first match found of the value matched with the expression.
Syntax:
switch(expression, case1, case2, case3....)
Here, the expression is matched with the list of values and the corresponding value is returned.
Important Points about Switch Case Statements:
An expression type with character string always matched to the listed cases.
An expression which is not a character string then this exp is coerced to integer.
For multiple matches, the first match element will be used.
No default argument case is available there in R switch case.
An unnamed case can be used, if there is no matched case.
Flowchart:
Example 1:
# Following is a simple R program  # to demonstrate syntax of switch.val <- switch(   4,   "Geeks1",   "Geeks2",   "Geeks3",   "Geeks4",   "Geeks5",   "Geeks6")print(val)
Output:
[1] "Geeks4"
Example 2:
# Following is val1 simple R program  # to demonstrate syntax of switch.  # Mathematical calculation  val1 = 6  val2 = 7val3 = "s"  result = switch(      val3,      "a"= cat("Addition =", val1 + val2),      "d"= cat("Subtraction =", val1 - val2),      "r"= cat("Division = ", val1 / val2),      "s"= cat("Multiplication =", val1 * val2),    "m"= cat("Modulus =", val1 %% val2),    "p"= cat("Power =", val1 ^ val2))      print(result)  
Output:
multiplication = 42NULL
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Return Rows Matching a Certain Condition

14 Nov, 2021
In SQL, sometimes we need to select matching a certain condition from the table. We will use the SELECT command along with the WHERE clause to apply a condition to achieve this in SQL. For this article. We will be using the Microsoft SQL Server as our database.
Syntax:
SELECT COLUMN_NAME_1, COLUMN_NAME_2, ....
 FROM TABLE_NAME WHERE CONDITION;
Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks.
Query:
CREATE DATABASE GeeksForGeeks
Output:
Step 2: Use the GeeksForGeeks database. For this use the below command.
Query:
USE GeeksForGeeks
Output:
Step 3: Create a table EMPLOYEE inside the database GeeksForGeeks. This table has 6 columns namely E_ID, E_NAME,  E_SALARY, E_AGE, E_GENDER, and E_DEPT containing id, name, salary, age, gender, and department of various employees.
Query:
CREATE TABLE EMPLOYEE(
E_ID INT,
E_NAME VARCHAR(6),
E_SALARY INT,
E_AGE INT,
E_GENDER VARCHAR(6),
E_DEPT VARCHAR(5));
Output:
Step 4: Display the structure of the EMPLOYEE table.
Query:
EXEC SP_COLUMNS 'EMPLOYEE';
Output:
Step 5: Insert six rows into the EMPLOYEE table.
Query:
INSERT INTO EMPLOYEE VALUES(1,'KHUSHI',10000,17,'FEMALE','CSE');
INSERT INTO EMPLOYEE VALUES(2,'KAMLA',20000,37,'FEMALE','EE');
INSERT INTO EMPLOYEE VALUES(3,'GAUTAM',25000,27,'MALE','ME');
INSERT INTO EMPLOYEE VALUES(4,'VIJAY',75000,42,'MALE','CIVIL');
INSERT INTO EMPLOYEE VALUES(5,'ANITA',50000,32,'FEMALE','CSE');
INSERT INTO EMPLOYEE VALUES(6,'MAYURI',42000,49,'FEMALE','CIVIL');
Output:
Step 6: Display all the rows of the EMPLOYEE table.
Query:
SELECT * FROM EMPLOYEE;
Output:
Step 7: If we want to display all the details of the employees who are older than 20 years but younger than 40 years from the EMPLOYEE table. Use the BETWEEN clause to compare the age attribute of the employees.
Syntax of BETWEEN:
ATTRIBUTE LOWER_LIMIT BETWEEN UPPER_LIMIT;
Query:
SELECT * FROM EMPLOYEE WHERE E_AGE BETWEEN 20 AND 40;
Output:
Step 8: Display all the details of the employees who are female from the EMPLOYEE table. Use the =(equal to), relational operator, to compare the gender attribute of the employees to FEMALE.
Query:
SELECT * FROM EMPLOYEE WHERE E_GENDER='FEMALE';
Output:
Step 9: Display all the details of the employees who have a salary greater than 40000 and belong to the civil department from the EMPLOYEE table. We will use >(greater than) relational operator for comparing the salary and =(equal to) relational operator to check the department. We will also use the AND(logical operator) so that both the conditions hold true simultaneously.
Query:
SELECT * FROM EMPLOYEE WHERE E_SALARY>40000 AND E_DEPT='CIVIL';
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector contains() Method in Java

17 Aug, 2018
The java.util.vector.contains() method is used to check whether a specific element is present in the Vector or not. So basically it is used to check if a vector contains any particular element or not.
Syntax:
Vector.contains(Object element)
Parameters: This method takes a mandatory parameter element which is of the type of vector. This is the element that needs to be tested if it is present in the vector or not.
Return Value: This method returns True if the element is present in the vector otherwise it returns False.
Below programs illustrate the Java.util.Vector.contains() method:
Program 1:
// Java code to illustrate contains()import java.util.*;  public class VectorDemo {    public static void main(String args[])    {        // Creating an empty Vector        Vector<String> vec_tor = new Vector<String>();          // Use add() method to add elements into the Vector        vec_tor.add("Welcome");        vec_tor.add("To");        vec_tor.add("Geeks");        vec_tor.add("4");        vec_tor.add("Geeks");          // Displaying the Vector        System.out.println("Vector: " + vec_tor);          // Check for "Geeks" in the Vector        System.out.println("Does the vector contains 'Geeks'? "                           + vec_tor.contains("Geeks"));          // Check for "4" in the Vector        System.out.println("Does the Vector contains '4'? "                           + vec_tor.contains("4"));          // Check if the Queue contains "No"        System.out.println("Does the Queue contains 'No'? "                           + vec_tor.contains("No"));    }}
Vector: [Welcome, To, Geeks, 4, Geeks]
Does the vector contains 'Geeks'? true
Does the Vector contains '4'? true
Does the Queue contains 'No'? false

Program 2:
// Java code to illustrate contains()import java.util.*;  public class VectorDemo {    public static void main(String args[])    {        // Creating an empty Vector        Vector<Integer> vec_tor = new Vector<Integer>();          // Use add() method to add elements into the Vector        vec_tor.add(10);        vec_tor.add(15);        vec_tor.add(30);        vec_tor.add(20);        vec_tor.add(5);          // Displaying the Vector        System.out.println("Vector: " + vec_tor);          // Check for "Geeks" in the Vector        System.out.println("Does the vector contains 'Geeks'? "                           + vec_tor.contains("Geeks"));          // Check for "4" in the Vector        System.out.println("Does the Vector contains '4'? "                           + vec_tor.contains("4"));          // Check if the vector contains "No"        System.out.println("Does the Vector contains 'No'? "                           + vec_tor.contains("No"));    }}
Vector: [10, 15, 30, 20, 5]
Does the vector contains 'Geeks'? false
Does the Vector contains '4'? false
Does the Vector contains 'No'? false

Java - util package
Java-Collections
Java-Functions
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rect element method – Selenium Python

30 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use rect method in Selenium. rect method is used to get a dictionary with the size and location of the element.
element.rect
Example –
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
Now one can get data of this element with –
element.rect
Let’s try to get element and its rect on geeksforgeeks using rect method.Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_id("gsc-i-id2")  # get rectprint(element.rect)
Output-
Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Pattern split(CharSequence) method in Java with Examples

21 Feb, 2019
split(CharSequence) method of a Pattern class used to splits the given char sequence passed as parameter to method around matches of this pattern.This method can split charSequence into an array of String’s, using the regular expression used to compile the pattern as a delimiter.so we can say that the method returns the array of strings computed by splitting the input around matches of this pattern.
Syntax:
public String[] split(CharSequence input)

Parameters: This method accepts a single parameter input which represents character sequence to be split.
Return value: This method returns the array of strings computed by splitting the input around matches of this pattern.
Below programs illustrate the split(CharSequence) method:Program 1:
// Java program to demonstrate// Pattern.split(CharSequence) method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {        // create a REGEX String        String REGEX = "ee";          // create the string        // in which you want to search        String actualString            = "geeksforgeeks";          // create a Pattern using REGEX        Pattern pattern = Pattern.compile(REGEX);          // split the text        String[] array = pattern.split(actualString);          // print array        for (int i = 0; i < array.length; i++) {            System.out.println("array[" + i                               + "]=" + array[i]);        }    }}
array[0]=g
array[1]=ksforg
array[2]=ks

Program 2:
// Java program to demonstrate// Pattern.split(CharSequence) method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {        // create a REGEX String        String REGEX = "ke";          // create the string        // in which you want to search        String actualString            = "Bharat ke Veer Portal";          // create a Pattern using REGEX        Pattern pattern = Pattern.compile(REGEX);          // split the text        String[] array = pattern.split(actualString);          // print array        for (int i = 0; i < array.length; i++) {            System.out.println("array[" + i                               + "]=" + array[i]);        }    }}
array[0]=Bharat 
array[1]= Veer Portal

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#split(java.lang.CharSequence)
Java - util package
Java-Functions
Java-Pattern
java-regular-expression
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.