code-rag-bench/online-tutorials huggingface dataset:
Difference between PreparedStatement and CallableStatement - GeeksforGeeks

22 Jul, 2020
1. CallableStatement :It is used when you want to use the database stored procedures. CallableStatement can accept runtime input parameters.
Example –
//Creating CallableStatement object 
CallableStatement GFG = con.prepareCall("{call anyProcedure(?, ?, ?)}");
 
//Use GFG.setter() methods to pass IN parameters
 
//Use GFG.registerOutParameter() method to register OUT parameters
 
//Executing the CallableStatement
 GFG.execute();
 
//Use GFG.getter() methods to retrieve the result 
2. PreparedStatement :It is used when you want to use SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.
Example –
//Creating the PreparedStatement object 
PreparedStatement GFG = con.prepareStatement("update STUDENT set NAME = ? where ID = ?");
  
//Setting values to place holders  
GFG.setString(1, "RAM");   //Assigns "RAM" to first place holder
          
GFG.setInt(2, 512);     //Assigns "512" to second place holder
 
//Executing PreparedStatement
GFG.executeUpdate(); 
Difference between CallableStatement and PreparedStatement :
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Difference between SQL and NoSQL
Difference between DDL and DML in DBMS
Logical and Physical Address in Operating System
Difference between Prim's and Kruskal's algorithm for MST
Difference between Primary Key and Foreign Key
Stack get() method in Java with Example - GeeksforGeeks

24 Dec, 2018
The Java.util.Stack.get() method is used to fetch or retrieve an element at a specific index from a Stack.
Syntax:
Stack.get(int index)
Parameters: This method accepts a mandatory parameter index which is of integer data type. It specifies the position or index of the element to be fetched from the Stack.
Return Value: The method returns the element present at the position specified by the parameter index.
Below programs illustrate the Java.util.Stack.get() method:
Program 1:
// Java code to illustrate get() methodimport java.util.*;  public class StackDemo {    public static void main(String args[])    {          // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Use add() method to add elements in the Stack        stack.add("Geeks");        stack.add("for");        stack.add("Geeks");        stack.add("10");        stack.add("20");          // Displaying the Stack        System.out.println("Stack: " + stack);          // Fetching the specific element from the Stack        System.out.println("The element is: "                           + stack.get(2));    }}
Stack: [Geeks, for, Geeks, 10, 20]
The element is: Geeks

Program 2:
// Java code to illustrate get() methodimport java.util.Stack;  public class StackDemo {    public static void main(String args[])    {          // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Use add() method to add elements in the Stack        stack.add("1");        stack.add("2");        stack.add("3");        stack.add("10");        stack.add("20");          // Displaying the Stack        System.out.println("Stack: "                           + stack);          // Fetching the specific element from the Stack        System.out.println("The element is: "                           + stack.get(4));    }}
Stack: [1, 2, 3, 10, 20]
The element is: 20

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
HashMap in Java with Examples
Arrays.sort() in Java with examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Python Program to Count Vowels, Lines, Characters in Text File - GeeksforGeeks

17 Oct, 2021
In this article, we are going to create a python program that counts vowels, lines, and a number of characters present in a particular text file.
We have to open the file using open() function in python.
Then make three variables, vowel, line and character to count the number of vowels, lines, and characters respectively.
Make a list of vowels so that we can check whether the character is a vowel or not.
When the count hits the  ‘\n’ character we have to increase our line variable means a new line in the file.
After that iterate over the characters of the file and count the vowels, lines, and characters.
Python3
# Python program to count number of vowels,# newlines and character in textfile  def counting(filename):        # Opening the file in read mode    txt_file = open(filename, "r")      # Initialize three variables to count number of vowels,    # lines and characters respectively    vowel = 0    line = 0    character = 0      # Make a vowels list so that we can    # check whether the character is vowel or not    vowels_list = ['a', 'e', 'i', 'o', 'u',                   'A', 'E', 'I', 'O', 'U']      # Iterate over the characters present in file    for alpha in txt_file.read():                # Checking if the current character is vowel or not        if alpha in vowels_list:            vowel += 1                      # Checking if the current character is        # not vowel or new line character        elif alpha not in vowels_list and alpha != "\n":            character += 1                      # Checking if the current character        # is new line character or not        elif alpha == "\n":            line += 1      # Print the desired output on the console.    print("Number of vowels in ", filename, " = ", vowel)    print("New Lines in ", filename, " = ", line)    print("Number of characters in ", filename, " = ", character)    # Calling the function counting which gives the desired outputcounting('Myfile.txt')
Output:
Number of vowels in  MyFile.txt  =  23    
New Lines in  MyFile.txt  =  2
Number of characters in  MyFile.txt  =  54
Text File:
Picked
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()
Convert Series of lists to one Series in Pandas - GeeksforGeeks

18 Aug, 2020
In this program, we will see how to convert a series of lists of into one series, in other words, we are just merging the different lists into one single list, in Pandas. We will be using the stack() method to perform this task. The line will be Series.apply(Pandas.Series).stack().reset_index(drop = True). The reset_index() method will reset the index of the DataFrame/Series.
Example 1 : Merging multiple series lists of integers.
# importing the moduleimport pandas as pd  # creating a Pandas series of listss = pd.Series([[2, 4, 6, 8],               [1, 3, 5, 7],               [2, 3, 5, 7]])print("Printing the Original Series of list")print(s)  # converting series of list into one seriess = s.apply(pd.Series).stack().reset_index(drop = True)  print("\nPrinting the converted series")print(s)
Output :
Example 2 : Merging multiple series lists of characters.
# importing the moduleimport pandas as pd  # creating a Pandas series of listss = pd.Series([['g', 'e', 'e', 'k', 's'],               ['f', 'o', 'r'],               ['g', 'e', 'e', 'k', 's']])print("Printing the Original Series of list")print(s)  # converting series of list into one seriess = s.apply(pd.Series).stack().reset_index(drop = True)  print("\nPrinting the converted series")print(s)
Output :
Python Pandas-exercise
Python pandas-series
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Playit

#myDIV {  background-color:lightblue;  transform:skewX(10deg));}
JSTL - SQL <sql:setDataSource> Tag

The <sql:setDataSource> tag sets the data source configuration variable or saves the data-source information in a scoped variable that can be used as input to the other JSTL database actions.
The <sql:setDataSource> tag has the following attributes −
Consider the following information about your MySQL database setup −
We are using JDBC MySQL driver.
We are using JDBC MySQL driver.
We are going to connect to TEST database on local machine.
We are going to connect to TEST database on local machine.
We would use user_id and mypassword to access TEST database.
We would use user_id and mypassword to access TEST database.
All the above parameters will vary based on your MySQL or any other database setup. Considering the above parameters, following example uses the setDataSource tag −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>

<html>
   <head>
      <title>JSTL sql:setDataSource Tag</title>
   </head>

   <body>
      <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
         url = "jdbc:mysql://localhost/TEST"
         user = "user_id"  password = "mypassword"/>
      <sql:query dataSource = "${snapshot}" sql = "..." var = "result" />
      
   </body>
</html>
We will use <sql:setDataSource> in subsequent SQL tags.

    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to count total number of occurrences of an object in a Python list?

You can use the list class count function to count the occurrences of an object in a Python list. Use this only if you want the count of one object only. It finds the total number of the object you pass it in the list it is called on. 
>>> ["red", "blue", "red", "red", "blue"].count("red")
3
If you want to get the count for all the objects in the list, you'd be better off using Counter from collections. It counts the frequency of all objects in the given list and returns them as a dictionary with the keys as the objects and values as their count in the list. 
from collections import Counter
my_list = ["red", "blue", "red", "red", "blue"]
print(Counter(my_list))
This will give the output −
Counter({'blue': 2, 'red': 3})
HTML Text Formatting

The HTML Text Formatting refers to the HTML elements that are designed specially for formatting content in an HTML document.
Following is the syntax −
<tagname>content</tagname>
Following are the text formatting tags in HTML:
Let us see an example of HTML Text Formatting:
Live Demo
<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background-color: #8BC6EC;
      background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%);
      text-align: center;
   }
</style>
<body>
<h1>HTML Text Formatting Demo</h1>
<b>I'm Bold Tag</b>
<br>
<em>I'm Em Tag</em>
<br>
<i>I'm I Tag</i>
<br>
<small>I'm Small Tag</small>
<br>
<strong>I'm Strong Tag</strong>
<br>
<sub>I'm Sub Tag</sub>
<br>
<sup>I'm Sup Tag</sup>
<br>
<ins>I'm Ins Tag</ins>
<br>
<del>I'm Del Tag</del>
<br>
<mark>I'm Mark Tag</mark>
<br>
</body>
</html>
How to create a profile card with CSS?

To create a profile card with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .profileCard {
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
      max-width: 300px;
      margin: auto;
      text-align: center;
      font-family: arial;
      background-color: rgb(190, 224, 224);
   }
   .Designation {
      color: rgb(26, 0, 51);
      font-weight: bold;
      font-size: 18px;
   }
   button {
      border: none;
      outline: 0;
      display: inline-block;
      padding: 8px;
      color: white;
      background-color: rgb(23, 31, 102);
      text-align: center;
      cursor: pointer;
      width: 100%;
      font-size: 18px;
   }
   button:hover, a:hover {
      opacity: 0.7;
   }
</style>
</head>
<body>
<h2 style="text-align:center">User Profile profileCard Example</h2>
<div class="profileCard">
<img src="https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="John" style="width:100%" />
<h1>John Doe</h1>
<p class="Designation">WebDeveloper</p>
<p>Michigan</p>
<p><button>Contact</button></p>
</div>
</body>
</html>
The above code will produce the following output −
Python math library | isnan() method - GeeksforGeeks

06 Jan, 2019
Python has math library and has many functions regarding it. One such function is isnan(). This method is used to check whether a given parameter is a valid number or not.
Syntax : math.isnan(x)
Parameters :x [Required] : It is any valid python data type or any number.
Returns: Return type is boolean.-> Returns False if the given parameter is any number(positive or negative)-> Returns True if given parameter is NaN (Not a Number).
Code #1:
# Python3 code to demonstrate # the working of isnan() import math   # initializing the value test_int = 4test_neg_int = -3test_float = 0.00  # checking isnan() values # with different numbersprint (math.isnan(test_int))print (math.isnan(test_neg_int))print (math.isnan(test_float))
False
False
False

 Code #2:
# Python3 code to demonstrate # the working of isnan() import math   # checking isnan() values # with inbuilt numbersprint (math.isnan(math.pi))print (math.isnan(math.e))    # checking for NaN valueprint (math.isnan(float('nan')))
False
False
True

Python math-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
How to open a browser window in full screen using Selenium WebDriver with C#?

We can open a browser window in full screen using Selenium webdriver in C# by using the method Maximize. This method has to be applied on the webdriver object.
driver.Manage().Window.Maximize();
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
namespace NUnitTestProject1{
   public class Tests{
      String url = "https://www.google.com/";
      IWebDriver driver;
      [SetUp]
      public void Setup(){
         //object of FirefoxDriver
         driver = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         //URL launch
         driver.Navigate().GoToUrl(url);
         //browser maximize
         driver.Manage().Window.Maximize();
         Console.WriteLine("Browser Maximized");
      }
      [TearDown]
      public void closeBrowser(){
         driver.Quit();
      }
   }
}
Aptitude - Progression

A succession of numbers formed and arranged in a definite order according to a certain definite rule is called a sequence.
It is a sequence in which each term, except the first one differs the preceding term by a constant. This constant is called the common difference. We denote the first term by a, common difference by d, nth term by Tṇ and the sum of first n terms by Sṇ.
5, 8,11,14,17...is an A.P. in which a=5 and d = (8-5) =3.
8, 5, 2,-1,-4,-7.... is an A.P. in which a = 8 and d = (5-8) = -3.

In a given A.P., let first term =a, common difference =d. Then,
Tn= a + (n-1) d.
Sum of n terms of an A.P.
Sn = n/2[2a+ (n-1) d]
Sn = n/2 (a + L), where L is the last term.

A sequence in which each term, except the first one bears a constant ratio with its preceding term, is called a geometrical progression, written as G.P. The constant ratio is called the common ratio of the G.P. We denote its first term by a and common ratio by r.
2, 6, 18, 54, is a G.P.in which a=2 and r=6/2=3.
24, 12, 6, 3... Is a G.P. in which a = 24 and r = 12/24=1/2.

General Term of a G.P.: In a G.P. we have 
Tn= arn-1
Sum of n terms of a G.P.
Sn = a (1-rn)/ (1-r), When r < 1
a (r - 1n)/(r-1), When r > 1

A.M. of a and b = 1/2(a+b).

G.M. of a and b =√ab

(i) 1+2+3+4+.......+n=1/2n (n+1).
(ii) 12+22+32+42+......+n2 = n(n+1)(2n+1)/6 
(iii)  13+23+33+43+.....+n3= {1/2 n(n+1)}2


    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
TypeScript - String valueOf()

This method returns the primitive value of a String object.
string.valueOf( )

Returns the primitive value of a String object.
var str = new String("Hello world"); 
console.log(str.valueOf( ));

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Hello world


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Python | Average of Float Numbers

10 Feb, 2020
While working with Python, we can have a problem in which we need to find mean of a list cumulative with float elements. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding mean and perform using loop shorthands. This is the most basic approach to solve this problem.
# Python3 code to demonstrate working of # Average of Float Numbers # using loop + formula import math  # initialize list test_list = [6.1, 7.2, 3.3, 9.4, 10.6, 15.7]   # printing original list print("The original list is : " + str(test_list))   # Average of Float Numbers# using loop + formula sum = 0for ele in test_list:  sum += eleres = sum / len(test_list)  # printing result print("The mean of float list elements is : " + str(res)) 
The original list is : [6.1, 7.2, 3.3, 9.4, 10.6, 15.7]
The mean of float list elements is : 8.716666666666667

 
Method #2 : Using statistics.fmean()This task can also be performed using inbuilt function of fmean(). This is new in Python versions >= 3.8.
# Python3 code to demonstrate working of # Average of Float Numbers# using statistics.fmean() import statistics   # initialize list test_list = [6.1, 7.2, 3.3, 9.4, 10.6, 15.7]   # printing original list print("The original list is : " + str(test_list))   # Average of Float Numbers# using statistics.fmean() res = statistics.fmean(test_list)   # printing result print("The mean of float list elements is : " + str(res)) 
The original list is : [6.1, 7.2, 3.3, 9.4, 10.6, 15.7]
The mean of float list elements is : 8.716666666666667

Python list-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 | Convert string dictionary to dictionary
Python | Prefix sum list

13 Jun, 2022
Nowadays, especially in the field of competitive programming, the utility of computing prefix sum is quite popular and features in many problems. Hence, having a one-liner solution to it would possess a great help. Let’s discuss certain way in which this problem can be solved. 
Method #1: Using list comprehension + sum() + list slicing This problem can be solved using the combination of above two functions in which we use list comprehension to extend logic to each element, sum function to get the sum along, slicing is used to get sum till the particular index. 
Python3
# Python3 code to demonstrate# prefix sum list# using list comprehension + sum() + list slicing # initializing listtest_list = [3, 4, 1, 7, 9, 1] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + sum() + list slicing# prefix sum listres = [sum(test_list[ : i + 1]) for i in range(len(test_list))] # print resultprint("The prefix sum list is : " + str(res))
  Method #2: Using accumulate(iterable) method.
Python3
# function to find cumulative sum of listfrom itertools import accumulate def cumulativeSum(lst):    print (list(accumulate(lst))) # Driver programif __name__ == "__main__":    lst = [3, 4, 1, 7, 9, 1]    cumulativeSum(lst)
Output: 
[3, 7, 8, 15, 24, 25]
Method#3: Using For loop and list indexing The above problem can be solve using two mention techniques. For loop is used for iterating in list and list indexing is used to access current element and previous element. 
Python3
# Python3 code to demonstrate# prefix sum list# using For loop + list indexing # initializing listtest_list = [3, 4, 1, 7, 9, 1] # printing original listprint("The original list : " + str(test_list)) # using For loop and list indexing# prefix sum listres = [0]*len(test_list)res[0] = test_list[0]for i in range(1, len(test_list)):    res[i] = res[i-1] + test_list[i] # print resultprint("The prefix sum list is : " + str(res))
The original list : [3, 4, 1, 7, 9, 1]
The prefix sum list is : [3, 7, 8, 15, 24, 25]

satyam00so
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding the Prototype Chain in JavaScript

22 Jul, 2020
When you started learning to program, you would have encountered the term object-oriented programming. Here we discover what it meant and you acknowledged that it is for grouping data into “objects” with attributes.The keyword that creates these objects in many programming languages is the class. You define a category with a constructor and a number of other public and personal functions. If you would like one class to inherit from another, you write simple inheritance syntax. You have created a sequence of inheritance. Until ES2015, the language didn’t implement a category. Instead, they used the prototype chain. The new ES6 “class” hides the inner workings of the prototype chain. Understanding how the prototype chain works is crucial if you would like to develop the performant code while using JavaScript’s OOP paradigm. For those familiar (or not so familiar) with computing, the prototype chain may be a linked list. It’s a gross oversimplification.
How do we initialize our chain?All objects in JavaScript have a prototype. An object’s prototype is also considered to be an object.
function Dog(name) {  this.name = name;}
Because a prototype is an object, a prototype has its own prototype. In that case, the prototype of Dog.prototype is Object.prototype
// Returns trueObject.prototype.isPrototypeOf(Dog.prototype);
Output:
 true

Recall the hasOwnProperty() method.
javascript
let duck = new Dog("Donald");duck.hasOwnProperty("name"); // yields true
Output:
  true

The hasOwnProperty() method is defined in Object.prototype, that can be accessed by Dog.prototype, which can then be accessed by variable “duck”. It clearly explains the prototype chain. In this prototype chain, “Dog” is the supertype for “duck”, while “duck” is the subtype. The object is a supertype for both “Dog” and “duck”. We take an Object is a supertype for all objects in JavaScript. Any object can use the hasOwnProperty() JavaScript method.
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | askopenfile() function in Tkinter

29 Nov, 2021
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code.With the help of GUI, you may not require to specify the path of any file but you can directly open a file and read it’s content.
In order to use askopenfile() function you may require to follow these steps:
-> import tkinter-> from tkinter.filedialog import askopenfile ## Now you can use this function-> file = askopeenfile(mode=’r’, filetypes=[(‘any name you want to display’, ‘extension of file type’)])
We have to specify the mode in which you want to open the file like in above snippet, this will open a file in reading mode.
# importing tkinter and tkinter.ttk# and all their functions and classesfrom tkinter import * from tkinter.ttk import *  # importing askopenfile function# from class filedialogfrom tkinter.filedialog import askopenfile  root = Tk()root.geometry('200x100')  # This function will be used to open# file in read mode and only Python files# will be openeddef open_file():    file = askopenfile(mode ='r', filetypes =[('Python Files', '*.py')])    if file is not None:        content = file.read()        print(content)  btn = Button(root, text ='Open', command = lambda:open_file())btn.pack(side = TOP, pady = 10)  mainloop()
Output:
Printed content of selected file –
Comparison of content of original file and printed content –
Note: In above code only .py (python files) types files will be open. To open specified type of files, one has to mention it in the filetypes option along with it’s extension as done in above code.
nidhi_biet
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
TreeSet toArray() method in Java with Example

27 Dec, 2018
The toArray() method of Java TreeSet is used to form an array of the same elements as that of the TreeSet. Basically, it copies all the element from a TreeSet to a new array.
Syntax:
Object[] arr = TreeSet.toArray()
Parameters: The method does not take any parameters.
Return Value: The method returns an array containing the elements similar to the TreeSet.
Below programs illustrate the TreeSet.toArray() method:
Program 1:
// Java code to illustrate toArray()  import java.util.*;  public class TreeSetDemo {    public static void main(String args[])    {        // Creating an empty TreeSet        TreeSet<String>            set = new TreeSet<String>();          // Use add() method to add        // elements into the TreeSet        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("For");        set.add("Geeks");          // Displaying the TreeSet        System.out.println("The TreeSet: "                           + set);          // Creating the array and using toArray()        Object[] arr = set.toArray();          System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The TreeSet: [For, Geeks, To, Welcome]
The array is:
For
Geeks
To
Welcome

Program 2:
// Java code to illustrate toArray()  import java.util.*;  public class TreeSetDemo {    public static void main(String args[])    {        // Creating an empty TreeSet        TreeSet<Integer>            set = new TreeSet<Integer>();          // Use add() method to add        // elements into the TreeSet        set.add(10);        set.add(15);        set.add(30);        set.add(20);        set.add(5);        set.add(25);          // Displaying the TreeSet        System.out.println("The TreeSet: "                           + set);          // Creating the array and using toArray()        Object[] arr = set.toArray();          System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The TreeSet: [5, 10, 15, 20, 25, 30]
The array is:
5
10
15
20
25
30

Java - util package
Java-Collections
Java-Functions
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Introduction to Java
Constructors in Java
Initialize an ArrayList in Java
Select a single column of data as a Series in Pandas

01 Oct, 2020
In this article, we will discuss how to select a single column of data as a Series in Pandas.
For example, Suppose we have a data frame :
Name Age  MotherTongue
Akash 21   Hindi
Ashish 23  Marathi
Diksha 21  Bhojpuri
Radhika 20 Nepali
Ayush   21 Punjabi

Now when we select column Mother Tongue as a Series we get the following output:
Hindi Marathi Bhojpuri Nepali Punjabi

Now let us try to implement this using Python:
Step1: Creating data frame:
# importing pandas as libraryimport pandas as pd  # creating data frame:df = pd.DataFrame({'name': ['Akash', 'Ayush', 'Ashish',                            'Diksha', 'Shivani'],                                        'Age': [21, 25, 23, 22, 18],                                        'MotherTongue': ['Hindi', 'English', 'Marathi',                                    'Bhojpuri', 'Oriya']})  print("The original data frame")df
Output:
Step 2: Selecting Column using dataframe.column name:
print("Selecting Single column value using dataframe.column name")series_one = pd.Series(df.Age)print(series_one)  print("Type of selected one")print(type(series_one))
Output:
Step 3: Selecting column using dataframe[column_name]
# using [] methodprint("Selecting Single column value using dataframe[column name]")series_one = pd.Series(df['Age'])print(series_one)  print("Type of selected one")print(type(series_one))
Output:
In the above two examples we have used pd.Series() to select a single column of a data frame as a series.
Python Pandas-exercise
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Math subtractExact(long x, long y) method

27 Apr, 2018
The java.lang.Math.subtractExact() is a built-in math function in java which returns the difference of thearguments.It throws an exception if the result overflows a long.As subtractExact(long x, long y) is static,so object creation is not required.
Syntax :
public static long subtractExact(long x, long y)
Parameter :
 x : the first value
 y : the second value to be subtracted from the first
Return :
This method returns the difference of the arguments.
Exception :
It throws ArithmeticException - if the result overflows a long.

Example :To show working of java.lang.Math.subtractExact() method.
// Java program to demonstrate working// of java.lang.Math.subtractExact() methodimport java.lang.Math;  class Gfg1 {      // driver code    public static void main(String args[])    {        long x = 11111111111l;        long y = 999l;          System.out.println(Math.subtractExact(x, y));    }}
Output:
11111110112

// Java program to demonstrate working// of java.lang.Math.subtractExact() methodimport java.lang.Math;  class Gfg2 {      // driver code    public static void main(String args[])    {        long a = Long.MIN_VALUE;        long b = 1;          System.out.println(Math.subtractExact(a, b));    }}
Output:
Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: long overflow
    at java.lang.Math.subtractExact(Math.java:849)
    at Gfg2.main(File.java:13)

Java
Mathematical
Mathematical
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
Stream In Java
ArrayList in Java
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Exporting PDF Data using Python

10 May, 2020
Sometimes, we have to extract data from PDF. we have to copy & paste the data from PDF. It is time-consuming. In Python, there are packages that we can use to extract data from a PDF and export it in a different format using Python. We will learn how to extract data from PDFs.
PDFMiner is a text extraction tool for PDF documents. you can try using pip to install PDFminer in your system as:
pip install pdfminer
Let’s get started with extracting all the text of PDF page by page. It requires the following steps to extract pages data
create a resource manager instance.
create a file-like object via Python’s io module.
create a converter.
create a PDF interpreter object that will take our resource manager and converter objects and extract the text.
open the PDF and loop through each page.
Below is the implementation.
PDF File Used:
import iofrom pdfminer.converter import TextConverterfrom pdfminer.pdfinterp import PDFPageInterpreterfrom pdfminer.pdfinterp import PDFResourceManagerfrom pdfminer.pdfpage import PDFPage    def extract_text_by_page(pdf_path):      with open(pdf_path, 'rb') as fh:                  for page in PDFPage.get_pages(fh,                                       caching=True,                                      check_extractable=True):                          resource_manager = PDFResourceManager()            fake_file_handle = io.StringIO()                          converter = TextConverter(resource_manager,                                       fake_file_handle)                          page_interpreter = PDFPageInterpreter(resource_manager,                                                  converter)                          page_interpreter.process_page(page)            text = fake_file_handle.getvalue()                          yield text                          # close open handles            converter.close()            fake_file_handle.close()              def extract_text(pdf_path):    for page in extract_text_by_page(pdf_path):        print(page)        print()          # Driver codeif __name__ == '__main__':    print(extract_text('GFG.pdf'))
Output:
In this example, we create a function that yields the text for each page. The extract_text function prints out the text of each page.
python-utility
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
std::tuple_element() and std::tuple_size() in C++ with Examples - GeeksforGeeks

10 Jul, 2021
A tuple is an object that can hold a number of elements. The elements can be different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed.
The functions-tuple_element() and tuple_size()are only defined for elements using tuple_like interface.
tuple_element():The C++ function tuple_element(array) provides compile-type indexed access to the type of the elements of the array using a tuple-like interface.
Syntax-
template< size_t I, class T, size_t N >
struct tuple_element<I, array<T, N> >;
Parameters-
T − type for which the tuple element is obtained.
I − index of the element.
N − the size of the array.
Example-Below is the C++ program to implement the concept of tuple_element(array)-
C++
// C++ program to implement// the above approach  #include <array>#include <iostream>#include <tuple>#include <type_traits>using namespace std;  // Driver codeint main(){    // Define array    array<int, 3> data{ 3, 5, 10 };      // Type of element at index 0    using type = std::tuple_element<0,                                    decltype(data)>::type;      // Compare type with int    // returns true    cout << std::is_same<type,                         int>::value         << '\n';      // Compare type with char    // returns false    cout << std::is_same<type,                         char>::value         << '\n';}
1
0
tuple_size():The C++ function tuple_size(array) returns the total number of elements present in the array.
Syntax-
template< class T, size_t N >
class tuple_size< array<T, N> > :
 integral_constant<size_t, N>
{ };
Parameters-
T − type for which the tuple size is obtained.
Example-Below is the C++ program to implement the concept of tuple_size()-
C++
// C++ program to implement// the above approach#include <array>#include <iostream>using namespace std;  // Driver codeint main(){    // Array of size 6    array<int, 6> a;      // Find size using tuple_size    cout << tuple_size<decltype(a)>::value;    return 0;}
6
CPP-Functions
cpp-tuple
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
HEAD method - Python requests - GeeksforGeeks

09 Dec, 2021
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make HEAD request to a specified URL using requests.head() method. Before checking out the HEAD method, let’s figure out what a Http HEAD request is –
HEAD is a request method supported by HTTP used by the World Wide Web. The HEAD method asks for a response identical to that of a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
Python’s requests module provides in-built method called head() for making a HEAD request to a specified URI.
Syntax –
requests.head(url, params={key: value}, args)

Example –
Let’s try making a request to httpbin’s APIs for example purposes.
Python3
import requests  # Making a HEAD requestr = requests.head('https://httpbin.org/', data ={'key':'value'})  # check status code for response received# success code - 200print(r)  # print headers of requestprint(r.headers)  # checking if request contains any contentprint(r.content)
python request.py
Output –
The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.
sweetyty
clintra
Python-requests
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
GATE | GATE CS Mock 2018 | Question 39 - GeeksforGeeks

10 Jan, 2018
Consider the following C-program :
int fun(){  static int num = 16;  return num--;}  int main(){  for(fun(); fun(); fun())    printf("%d ", fun());  return 0;}
What is output of above program?
(A) Infinite loop(B) 13 10 7 4 1(C) 15 12 8 5 2(D) 14 11 8 5 2Answer: (D)Explanation: Option (D) is correct. Refer : https://www.geeksforgeeks.org/c-storage-classes-and-type-qualifiers-question-9/Quiz of this Question
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
Python | Assign ids to each unique value in a list - GeeksforGeeks

01 May, 2019
Sometimes, while working in web development domain or in competitive programming, we require to assign a unique id to each of the different value to track for it’s occurrence for count or any other required use case. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using defaultdict + lambda + list comprehension
The combination of above functions can be used to accomplish this particular task. The defaultdict function performs the main task of assigning Ids using lambda function, it assigns the current number of keys to every new key. The list comprehension is used in later stage to form the list.
# Python3 code to demonstrate# assigning ids to values# using list comprehension + defaultdict + lambdafrom collections import defaultdict  # initializing listtest_list = [5, 6, 7, 6, 5, 1]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + defaultdict + lambda# assigning ids to valuestemp = defaultdict(lambda: len(temp))res = [temp[ele] for ele in test_list]  # print resultprint("The ids of assigned values is : " + str(res))
The original list : [5, 6, 7, 6, 5, 1]
The ids of assigned values is : [0, 1, 2, 1, 0, 3]

 
Method #2 : Using OrderedDict.fromkeys() + enumerate() + list comprehension
This method performs the task similar to the above method. In this orderedDict.fromkeys function performs the function to remove the duplicates and enumerate function helps us get the indices of values to map them together.
# Python3 code to demonstrate# assigning ids to values using # list comprehension + OrderedDict.fromkeys() + enumerate()from collections import OrderedDict  # initializing listtest_list = [5, 6, 7, 6, 5, 1]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + OrderedDict.fromkeys() + enumerate()# assigning ids to valuesres = [{val : key for key, val in enumerate(           OrderedDict.fromkeys(test_list))}                 [ele] for ele in test_list]  # print resultprint("The ids of assigned values is : " + str(res))
The original list : [5, 6, 7, 6, 5, 1]
The ids of assigned values is : [0, 1, 2, 1, 0, 3]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Display ISO 8601 standard date in Java

Use the ‘F’ date conversion character to display ISO 8601 standard date.
System.out.printf("ISO 8601 standard date = %tF\n", d);
Above, d is a date object.
Date d = new Date();
 Live Demo
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Demo {
   public static void main(String[] args) throws Exception {
      Date d = new Date();
      System.out.printf("Four-digit Year = %TY\n",d);
      System.out.printf("Two-digit Year = %ty\n",d);
      System.out.printf("ISO 8601 standard date = %tF\n", d);
   }
}
Four-digit Year = 2018
Two-digit Year = 18
ISO 8601 standard date = 2018-11-26
Java Examples - Matrix multiplication

How to multiply two matrices of different dimensions ?
Following example shows multiplication of two rectangular matrices with the help of two user defined methods multiply( int [] [] ,int [] []) and mprint(int [] []).
public class Matrix{
   public static int[][] multiply(int[][] m1, int[][] m2){
      int m1rows = m1.length;
      int m1cols = m1[0].length;
      int m2rows = m2.length;
      int m2cols = m2[0].length;
      if (m1cols != m2rows){
         throw new IllegalArgumentException("matrices 
         don't match: "+ m1cols + " != " + m2rows);
         int[][] result = new int[m1rows][m2cols];
         for (int i=0; i< m1rows; i++){
            for (int j=0; j< m2cols; j++){
               for (int k=0; k< m1cols; k++){
                  result[i][j] += m1[i][k] * m2[k][j];
                  return result;
               )
            }
         }
      }			
   }
/** Matrix print.
*/
   public static void mprint(int[][] a){
      int rows = a.length;
      int cols = a[0].length;
      System.out.println("array["+rows+"]["+cols+"] = {");
      for (int i=0; i< rows; i++){
         System.out.print("{");
         for (int j=0; j< cols; j++){
            System.out.print(" " + a[i][j] + ",");
            System.out.println("},");
         }
      }
      System.out.println(":;");
   }
   public static void main(String[] argv){
      int x[][] ={
      { 3, 2, 3 },
      { 5, 9, 8 },
      };

      int y[][] ={
      { 4, 7 },
      { 9, 3 },
      { 8, 1 },
      };

      int z[][] = Matrix.multiply(x, y);
      Matrix.mprint(x);
      Matrix.mprint(y);
      Matrix.mprint(z);
   }
}

The above code sample will produce the following result.
array[2][3]={
{3, 2, 3}
 {5, 9, 8}
};

array[3][2]={
{4, 7}
{9, 3}
{8, 1}
};

array[2][2]={
{63, 30}
{165, 70}
};


Advertisements

 Print
 Add Notes
 Bookmark this page