code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas Series.last_valid_index()

11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.last_valid_index() function return index for the last non-NA/null value in the given series object.
Syntax: Series.last_valid_index()
Parameter : None
Returns : scalar
Example #1: Use Series.last_valid_index() function to return the last valid index of the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio'])  # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.last_valid_index() function to return the last valid index of the given series object.
# return the last valid indexresult = sr.last_valid_index()  # Print the resultprint(result)
Output :
As we can see in the output, the Series.last_valid_index() function has returned the last valid index in the given series object. Example #2: Use Series.last_valid_index() function to return the last valid index of the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, 16.8, 20.124, None, None, None])  # Print the seriesprint(sr)
Output :
Now we will use Series.last_valid_index() function to return the last valid index of the given series object.
# return the last valid indexresult = sr.last_valid_index()  # Print the resultprint(result)
Output :As we can see in the output, the Series.last_valid_index() function has returned the last valid index in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
Python Program to Convert Matrix to String

02 Feb, 2021
Given a matrix, our task is to write a Python program to convert to the matrix, with different delimiters for element and row separation.
Examples:
Input : test_list = test_list = [[1, 3, “gfg”], [2, “is”, 4], [“best”, 9, 5]], in_del, out_del = “,”, ” “
Output : 1,3,gfg 2,is,4 best,9,5
Explanation : Element in list separated by “,”, and lists separated by ” “.
Input : test_list = test_list = [[1, 3, “gfg”], [2, “is”, 4], [“best”, 9, 5]], in_del, out_del = “,”, “-“
Output : 1,3,gfg-2,is,4-best,9,5
Explanation : Element in list separated by “,”, and lists separated by “-“.
Method #1 : Using join() + list comprehension
In this, we perform task of iterating each element of each row using list comprehension. The inner and outer join for element and row with different delimiters using join().
Python3
# Python3 code to demonstrate working of# Convert Matrix to String# Using list comprehension + join()  # initializing listtest_list = [[1, 3, "gfg"], [2, "is", 4], ["best", 9, 5]]  # printing original listprint("The original list is : " + str(test_list))  # initializing delimsin_del, out_del = ",", " "  # nested join using join()res = out_del.join([in_del.join([str(ele) for ele in sub]) for sub in test_list])  # printing resultprint("Conversion to String : " + str(res))
Output:
The original list is : [[1, 3, ‘gfg’], [2, ‘is’, 4], [‘best’, 9, 5]]
Conversion to String : 1,3,gfg 2,is,4 best,9,5
Method #2 : Using map() + join()
In this, task of inner joining of elements is extending to each character using map(). Rest all the functionalities are similar to upper method.
Python3
# Python3 code to demonstrate working of# Convert Matrix to String# Using map() + join()  # initializing listtest_list = [[1, 3, "gfg"], [2, "is", 4], ["best", 9, 5]]  # printing original listprint("The original list is : " + str(test_list))  # initializing delimsin_del, out_del = ",", " "  # nested join using join()# map() for joining inner elementsres = out_del.join(in_del.join(map(str, sub)) for sub in test_list)  # printing resultprint("Conversion to String : " + str(res))
Output:
The original list is : [[1, 3, ‘gfg’], [2, ‘is’, 4], [‘best’, 9, 5]]
Conversion to String : 1,3,gfg 2,is,4 best,9,5
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Nested try blocks in Exception Handling in Java

23 Oct, 2018
In Java, we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed on to a stack. Given below is an example of a nested try.In this example, inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block) handles the ArrayIndexOutOfBoundsException.
Example 1:
class NestedTry {      // main method    public static void main(String args[])    {        // Main try block        try {              // initializing array            int a[] = { 1, 2, 3, 4, 5 };              // trying to print element at index 5            System.out.println(a[5]);              // try-block2 inside another try block            try {                  // performing division by zero                int x = a[2] / 0;            }            catch (ArithmeticException e2) {                System.out.println("division by zero is not possible");            }        }        catch (ArrayIndexOutOfBoundsException e1) {            System.out.println("ArrayIndexOutOfBoundsException");            System.out.println("Element at such index does not exists");        }    }    // end of main method}
ArrayIndexOutOfBoundsException
Element at such index does not exists

Whenever a try block does not have a catch block for a particular exception, then the catch blocks of parent try block are inspected for that exception, and if a match is found then that catch block is executed.
If none of the catch blocks handles the exception then the Java run-time system will handle the exception and a system generated message would be shown for the exception.
Example 2:
class Nesting {    // main method    public static void main(String args[])    {        // main try-block        try {              // try-block2            try {                  // try-block3                try {                    int arr[] = { 1, 2, 3, 4 };                    System.out.println(arr[10]);                }                  // handles ArithmeticException if any                catch (ArithmeticException e) {                    System.out.println("Arithmetic exception");                    System.out.println(" try-block1");                }            }              // handles ArithmeticException if any            catch (ArithmeticException e) {                System.out.println("Arithmetic exception");                System.out.println(" try-block2");            }        }          // handles ArrayIndexOutOfBoundsException if any        catch (ArrayIndexOutOfBoundsException e4) {            System.out.print("ArrayIndexOutOfBoundsException");            System.out.println(" main try-block");        }        catch (Exception e5) {            System.out.print("Exception");            System.out.println(" handled in main try-block");        }    }}
ArrayIndexOutOfBoundsException main try-block

Java-Exception Handling
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Taking input from the user in Tkinter

There might be times when we need to take the user input in our Tkinter application. We can get the user Input in a Single Line text input through the Entry widget using get() method. To display the Captured input, we can either print the message on the screen or display the input with the help of the Label widget.
#Import the required Libraries
from tkinter import *
from tkinter import ttk

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

#Set the geometry of Tkinter frame
win.geometry("750x250")

def display_text():
   global entry
   string= entry.get()
   label.configure(text=string)

#Initialize a Label to display the User Input
label=Label(win, text="", font=("Courier 22 bold"))
label.pack()

#Create an Entry widget to accept User Input
entry= Entry(win, width= 40)
entry.focus_set()
entry.pack()

#Create a Button to validate Entry Widget
ttk.Button(win, text= "Okay",width= 20, command= display_text).pack(pady=20)

win.mainloop()
Running the above code will display a window that will contain an entry widget that accepts the single line User Input.
Now, write some text in the given entry widget and press "Okay" to validate and display the entry widget on the screen.
Python calendar module : itermonthdays() method

13 May, 2021
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. 
itermonthdays() method returns an iterator of a specified month and a year. Days returned will simply be day numbers. itermonthdays() method is similar to itermonthdates(). 
Syntax: itermonthdays(year, month)

Parameter: 
year: year of the calendar
month: month of the calendar

Returns: an iterator of the specified month.
Code #1: 
Python3
# Python program to demonstrate working# of itermonthdays() method # importing calendar moduleimport calendar year = 2018month = 9  obj = calendar.Calendar() # iterating with itermonthdaysfor day in obj.itermonthdays(year, month):    print(day)
Output: 
0
0
0
0
0
1
2
3
4
5
6
.
.
29
30
Code #2: 
Python3
# Python program to demonstrate working# of itermonthdays() method # importing calendar moduleimport calendar # use with firstweekday = 5obj = calendar.Calendar(firstweekday = 2) # iterating with itermonthdaysfor day in obj.itermonthdays(2018, 4):    print(day)
Output: 
0
0
0
0
1
2
3
4
5
.
.
28
29
30
0
 
anikakapoor
Python Calander-module
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON?
GATE | GATE-CS-2004 | Question 8

23 Dec, 2019
Which of the following grammar rules violate the requirements of an operator grammar ? P, Q, R are nonterminals, and r, s, t are terminals.
1.    P → Q R                    
2.    P → Q s R
3.    P → ε       
4.    P → Q t R r 
(A) 1 only(B) 1 and 3 only(C) 2 and 3 only(D) 3 and 4 onlyAnswer: (B)Explanation: See Question 4 of https://www.geeksforgeeks.org/compilers-set-1/.
Operator grammar should not have two or more variables in its production side by side, and should not have null productions.Quiz of this Question
madarsh986
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE-CS-2016 (Set 1) | Question 45
Python | Menu widget in Tkinter

12 Apr, 2019
Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used package for GUI applications which comes with the Python itself.
Menus are the important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other toplevel windows.
menu = Menu(master, **options)
 Below is the implementation:
# importing only  those functions # which are neededfrom tkinter import * from tkinter.ttk import * from time import strftime  # creating tkinter windowroot = Tk()root.title('Menu Demonstration')  # Creating Menubarmenubar = Menu(root)  # Adding File Menu and commandsfile = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='File', menu = file)file.add_command(label ='New File', command = None)file.add_command(label ='Open...', command = None)file.add_command(label ='Save', command = None)file.add_separator()file.add_command(label ='Exit', command = root.destroy)  # Adding Edit Menu and commandsedit = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='Edit', menu = edit)edit.add_command(label ='Cut', command = None)edit.add_command(label ='Copy', command = None)edit.add_command(label ='Paste', command = None)edit.add_command(label ='Select All', command = None)edit.add_separator()edit.add_command(label ='Find...', command = None)edit.add_command(label ='Find again', command = None)  # Adding Help Menuhelp_ = Menu(menubar, tearoff = 0)menubar.add_cascade(label ='Help', menu = help_)help_.add_command(label ='Tk Help', command = None)help_.add_command(label ='Demo', command = None)help_.add_separator()help_.add_command(label ='About Tk', command = None)  # display Menuroot.config(menu = menubar)mainloop()
Output:
Note: In above application, commands are set to None but one may add different commands to different labels to perform the required task.
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
Ruby | Array push() function

06 Dec, 2019
Array#push() : push() is a Array class method which appends the given object(s) on to the end of this array.
Syntax: Array.push()
Parameter: Array
Return: appends the given object(s) on to the end of this array.
Example #1 :
# Ruby code for push() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [34, 5, 7]  # push method exampleputs "push() method form : #{a.push(3)}\n\n"  puts "push() method form : #{b.push()}\n\n"  puts "push() method form : #{c.push(2)}\n\n"
Output :
push() method form : [18, 22, 33, nil, 5, 6, 3]

push() method form : [1, 4, 1, 1, 88, 9]

push() method form : [34, 5, 7, 2]


Example #2 :
# Ruby code for push() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayc = [nil, "abc", "nil", "dog"]  # declaring arrayb = ["cow", nil, "dog"]    # push method exampleputs "push() method form : #{a.push(2)}\n\n"  puts "push() method form : #{b.push(1)}\n\n"  puts "push() method form : #{c.push(0)}\n\n"
Output :
push() method form : ["abc", "nil", "dog", 2]

push() method form : ["cow", nil, "dog", 1]

push() method form : [nil, "abc", "nil", "dog", 0]


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby For Beginners
Ruby | Array class find_index() operation
Ruby | String concat Method
Ruby on Rails Introduction
Ruby | Array shift() function
Ruby | Types of Variables
How static variables in member functions work in C++?

The static variables in member functions are declared using the keyword static. The space for the static variables is allocated only one time and this is used for the entirety of the program. Also, there is only one copy of these static variables in the whole program.
A program that demonstrates static variables in member functions in C++ is given as follows.
 Live Demo
#include <iostream>
using namespace std;
class Base {
   public :
   int func() {
      static int a;
      static int b = 12;
      cout << "The default value of static variable a is: " << a;
      cout << "\nThe value of static variable b is: " << b;
   }
};
int main() {
   Base b;
   b.func();
   return 0;
}
The output of the above program is as follows.
The default value of static variable a is: 0
The value of static variable b is: 12
Now let us understand the above program.
The member function func() in class Base contains two static variables a and b. The default value of a is 0 and the value of b is12. Then these values are displayed. The code snippet that shows this is as follows.
class Base {
   public :
   int func() {
      static int a;
      static int b = 12;
      cout << "The default value of static variable a is: " << a;
      cout << "\nThe value of static variable b is: " << b;
   }
};
In the main() function, an object b of class Base is created. Then the function func() is called. The code snippet that shows this is as follows.
int main() {
   Base b;
   b.func();
   return 0;
}
C# Example for Hierarchical Inheritance

More than one class is inherited from the base class in Hierarchical Inheritance.
In the example, our base class is Father −
class Father {
   public void display() {
      Console.WriteLine("Display...");
   }
}
It has Son and Daughter as the derived class. Let us how to add a derived class in Inheritance −
class Son : Father {
   public void displayOne() {
      Console.WriteLine("Display One");
   }
}
The following the complete example of implementing Hierarchical Inheritance in C# −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inheritance {
   class Test {
      static void Main(string[] args) {
         Father f = new Father();
         f.display();
         Son s = new Son();
         s.display();
         s.displayOne();
         Daughter d = new Daughter();
         d.displayTwo();
         Console.ReadKey();
      }
      class Father {
         public void display() {
            Console.WriteLine("Display...");
         }
      }
      class Son : Father {
         public void displayOne() {
            Console.WriteLine("Display One");
         }
      }
      class Daughter : Father {
         public void displayTwo() {
            Console.WriteLine("Display Two");
         }
      }
   }
}
Python Pillow – Flip and Rotate Images

16 Oct, 2021
Prerequisites: Pillow
Python Pillow or PIL is the Python library that provides image editing and manipulating features. The Image Module in it provides a number of functions to flip and rotate images. image.transpose() is the function used to rotate and flip images with necessary keywords as parameters.
Syntax:
image.transpose(appropriate keyword)
In the examples given below, we will be exploring all possible rotations using an appropriate keyword.
Image used:
Anticlockwise: To flip an image in anti-clockwise direction the keyword that needs to be passed is Image.TRANSPOSE.
Syntax:
img.transpose(Image.TRANSPOSE)
Example:
Python
from PIL import Image  img = Image.open('geek.jpg') # flip anti-clockwiseflip_img = img.transpose(Image.TRANSPOSE) flip_img.show()
Output :
Clockwise: To flip an image in the clockwise direction the keyword that needs to be passed is Image.TRANSVERSE.
Syntax:
 img.transpose(Image.TRANSVERSE)
Example:
Python
from PIL import Image  img  = Image.open('geek.jpg') # flip clockwiseflip_img= img.transpose(Image.TRANSVERSE) flip_img.show()
  
Output :
 
 
Horizontal Flip: For horizontal flip, pass Image.FLIP_LEFT_RIGHT as the keyword.
 
Syntax :
 
 img.transpose(Image.FLIP_LEFT_RIGHT)
 
Example:
 
Python
from PIL import Image  img = Image.open('geek.jpg') # flip horizontalflip_img = img.transpose(Image.FLIP_LEFT_RIGHT) flip_img.show()
  
Output :
 
 
Vertical flip: To flip vertically pass image.FLIP_TOP_BOTTOM as keyword
 
Syntax:
 
img.transpose(Image.FLIP_TOP_BOTTOM)
 
Example:
 
Python
from PIL import Image  img = Image.open('geek.jpg') # flip verticalflip_img = img.transpose(Image.FLIP_TOP_BOTTOM) flip_img.show()
  
Output :
 
 
Image rotation is done by specific angles and for that again specific keywords need to passed as discussed below:
 
Rotate by 90 degrees: The keyword used for this is Image.ROTATE_90
 
Syntax :
 
img.transpose(Image.ROTATE_90)
 
Example:
 
Python
from PIL import Image  img = Image.open('geek.jpg') # rotate by 90 degreesrot_img = img.transpose(Image.ROTATE_90) rot_img.show()
  
Output :
 
 
Rotate by 180 degrees: To rotate by 180 degrees the keyword used is Image.ROTATE_180
 
Syntax :
 
 img.transpose(Image.ROTATE_180)
 
Example:
 
Python
from PIL import Image  img = Image.open('geek.jpg') # rotate by 180 degreesrot_img = img.transpose(Image.ROTATE_180) rot_img.show()
  
Output:
 
 
Rotate by 270 degrees: To rotate by 270 degrees the keyword used is Image.ROTATE_270
 
Syntax :
 
img.transpose(Image.ROTATE_270)
 
Example:
 
Python
from PIL import Image  img = Image.open('geek.jpg') # rotate by 270 degreesrot_img = img.transpose(Image.ROTATE_270) rot_img.show()
  
Output:
 
 
anikaseth98
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python String format_map() Method

05 Aug, 2021
Python String format_map() method is an inbuilt function in Python, which is used to return a dictionary key’s value.
Syntax: 
string.format_map(z)
Parameters: 
Here z is a variable in which the input dictionary is stored and string is the key of the input dictionary. input_dict: Takes a single parameter which is the input dictionary.
Returns: 
Returns key’s values of the input dictionary.
Python3
# input stored in variable a.a = {'x':'John', 'y':'Wick'}  # Use of format_map() functionprint("{x}'s last name is {y}".format_map(a))
Output: 
John's last name is Wick
Python3
# input stored in variable a.a = {'x':"geeksforgeeks", 'y':'b'}  # Use of format_map() functionprint('{x} {y}'.format_map(a))
Output: 
geeksforgeeks b
Python3
# Input dictionaryprofession = { 'name':['Barry', 'Bruce'],               'profession':['Engineer', 'Doctor'],               'age':[30, 31] }                       # Use of format_map() function print('{name[0]} is an {profession[0]} and he'      ' is {age[0]} years old.'.format_map(profession))        print('{name[1]} is an {profession[1]} and he'      ' is {age[1]} years old.'.format_map(profession))
Output: 
Barry is an Engineer and he is 30 years old.
Bruce is an Doctor and he is 31 years old.
The format_map() function can be used in any practical application.
Python3
# Python code showing practical # use of format_map() functiondef chk_msg(n):              # input stored in variable a.    a = {'name':"George", 'mesg':n}          # use of format_map() function     print('{name} has {mesg} new messages'.format_map(a))  chk_msg(10)
Output: 
George has 10 new messages
AmiyaRanjanRout
Python-Built-in-functions
python-dict
python-string
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reading a Text File With SQL Server

15 Oct, 2021
Here we will see, how to read a text file with SQL Server. We can read the text file using the OPENROWSET(BULK ) function.
It is a table-valued function that can read data from any file. This function returns a single column table having all the contents of the file. This single large value is known as a   SINGLE_CLOB (single character large object)
Syntax:
SELECT * FROM OPENROWSET (BULK 'file_path', SINGLE_CLOB) as correlation_name;
This query will read the content of the text file and return it as a single column in a table named Bulkcolumn. The correlation name is mandatory to specify. We have the text file named “Geek.txt”. Content of text file:
Hii!! My name is Romy kumari.
I am an engineer.

Welcome to GeeksforGeeks platform.
Query:
SELECT * FROM OPENROWSET(BULK 'E:\Geek.txt', SINGLE_CLOB) AS Contents;
Output:
The entire content is returned as a single column.
Read text file from SQL server such that one row represents data in one line from a text file
Step to read each line of the text file in a single row:
Create a table in your database.
Insert data from a text file into the table using the ‘INSERT’ keyword.
Using WITH clause set ROWTERMINATOR as ‘\n’ (represents newline character). This split the content of the file into separate rows as soon as the new line is encountered in the file.
Step 1: Create Database
Use the below SQL statement to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Using the Database
Use the below SQL statement to switch the database context to geeks.
Query:
USE geeks;
Step 3: Table definition
We have the following demo table in our geek’s database.
CREATE TABLE demo(
Content VARCHAR(1000)
);
Step 4: Insert data from a text file into the table
Use the following command to insert data from a text file.
Syntax:
BULK INSERT dbo.table_name
  FROM 'file_path'
  WITH  
     (
        ROWTERMINATOR ='\n'
     )
Query:
BULK INSERT dbo.demo
  FROM 'E:\Geek.txt'
  WITH  
     (
        ROWTERMINATOR ='\n'
     );
Step 5: See the content of the table
Query:
SELECT * FROM demo;
Output:
Here, NULL represents an empty line.
Picked
SQL-Server
TrueGeek-2021
SQL
TrueGeek
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Can we serialize static variables in Java?

In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI).
But, static variables belong to class therefore, you cannot serialize static variables in Java. Still if you try to do so, the program gets compiled successfully but it raises an exception at the time of execution.
In the following java program, the class Student has a static variable and we are trying to serialize and desterilize its object in the another class named ExampleSerialize.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable{
   private static String name;
   public Student(String name){
      this.name = name;
   }
   public static String getName() {
      return name;
   }
   public static void setAge(String name) {
      Student.name = name;
   }
}
public class ExampleSerialize{
   public static void main(String args[]) throws Exception{
      Student std1 = new Student("Krishna", 30);
      FileOutputStream fos = new FileOutputStream("e:\\student.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(std1);

      FileInputStream fis = new FileInputStream("e:\\student.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Student std2 = (Student) ois.readObject();
      System.out.println(std2.getName());
   }
}
This program gets executed successfully but, while running you will get a run time exception as shown below −
Exception in thread "main" java.lang.ClassCastException: java.io.FileOutputStream cannot be cast to java.io.ObjectOutput
at sample.TestSerialize.main(TestSerialize.java:31)
C/C++ Program for  Finding  the Number Occurring Odd Number of Times?

A C++ program to find a number which occurs odd number of times in a given array of positive integers. In this array, all numbers occur even number of times.
Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7
Use two loops in which the outer loop traversed all elements one by one and inner loop counts the number of occurrences of the element traversed by the outer loop.
#include <iostream>
using namespace std;
int Odd(int arr[], int n){
   for (int i = 0; i < n; i++) {
      int ctr = 0;
      for (int j = 0; j < n; j++) {
         if (arr[i] == arr[j])
            ctr++;
      }
      if (ctr % 2 != 0)
         return arr[i];
   }
   return -1;
}
int main() {
   int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};
   int n = 9;
   cout <<Odd(arr, n);
   return 0;
}
What do you mean by glue in Cucumber?

The glue is a part of Cucumber options that describes the location and
path of the step definition file.
Test Runner file.
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import cucumber.api.testng.AbstractTestNGCucumberTests;
@CucumberOptions(
   features = "src/test/java/features",
   glue="stepDefinations"
)
public class TestRunner extends AbstractTestNGCucumberTests { }
How can we tackle MySQL error ‘ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement’ while importing or exporting the data?

MySQL throws this error because of the two reasons, either no directory is specified under --secure--file--priv variable or we are giving the wrong path in our query while importing or exporting the data. To tackle this error we must have to check the value of –secure—file—priv variable by following query −
mysql> Select @@global.secure_file_priv;
+---------------------------+
| @@global.secure_file_priv |
+---------------------------+
| C:\mysql\bin\mysql-files\ |
+---------------------------+
1 row in set (0.00 sec)
We can see there is path under secure_file_priv variable and all the files would be created under this directory when we export the data.
But, if the above command shows NULL as result then it means there is no path specified and we need to specify the path in my.ini file before exporting the data. Suppose if we will write secure_file_priv = mysql-files/ in our my.ini file then secure_file_priv will have the path like above as its value. Then all the files will be created under this directory.
SQL Tryit Editor v1.6

SELECT 17 % 5;
​
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.
Function Arguments in R Programming

01 Jun, 2020
Arguments are the parameters provided to a function to perform operations in a programming language. In R programming, we can use as many arguments as we want and are separated by a comma. There is no limit on the number of arguments in a function in R. In this article, we’ll discuss different ways of adding arguments in a function in R programming.
We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis. Below is an implementation of a function with a single argument.
Example:
# Function definition# To check n is divisible by 5 or notdivisbleBy5 <- function(n){  if(n %% 5 == 0)  {    return("number is divisible by 5")  }  else   {    return("number is not divisible by 5")  }}   # Function calldivisbleBy5(100)divisbleBy5(4)divisbleBy5(20.0)
Output:
[1] "number is divisible by 5"
[1] "number is not divisible by 5"
[1] "number is divisible by 5"

A function in R programming can have multiple arguments too. Below is an implementation of a function with multiple arguments.
Example:
# Function definition# To check a is divisible by b or notdivisible <- function(a, b){  if(a %% b == 0)  {    return(paste(a, "is divisible by", b))  }  else   {    return(paste(a, "is not divisible by", b))  }}  # Function calldivisible(7, 3)divisible(36, 6)divisible(9, 2)
 Output:
[1] "7 is not divisible by 3"
[1] "36 is divisible by 6"
[1] "9 is not divisible by 2"

Default value in a function is a value that is not required to specify each time the function is called. If the value is passed by the user, then the user-defined value is used by the function otherwise, the default value is used. Below is an implementation of function with default value.
Example:
# Function definition to check # a is divisible by b or not. # If b is not provided in function call,# Then divisibility of a is checked with 3 as defaultdivisible <- function(a, b = 3){  if(a %% b == 0)  {    return(paste(a, "is divisible by", b))  }   else  {    return(paste(a, "is not divisible by", b))  }}  # Function calldivisible(10, 5)divisible(12)
Output:
[1] "10 is divisible by 5"
[1] "12 is divisible by 3"

Dots argument (...) is also known as ellipsis which allows the function to take an undefined number of arguments. It allows the function to take an arbitrary number of arguments. Below is an example of a function with an arbitrary number of arguments.
Example:
# Function definition of dots operatorfun <- function(n, ...){  l <- list(n, ...)  paste(l, collapse = " ")}  # Function callfun(5, 1L,  6i, TRUE, "GeeksForGeeks", "Dots operator")
Output:
[1] "5 1 0+6i TRUE GeeksForGeeks Dots operator"

In R programming, functions can be passed to another functions as arguments. Below is an implementation of function as an argument.
Example:
# Function definition# Function is passed as argumentfun <- function(x, fun2){  return(fun2(x))}  # sum is built-in functionfun(c(1:10), sum)  # mean is built-in functionfun(rnorm(50), mean)
Output:
[1] 55
[1] 0.2153183

Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Ways to convert hex into binary

29 Jun, 2019
Conversion of hex to binary is a very common programming question. In this article, we will see a few methods to solve the above problem.
Method #1: Using bin and zfill
# Python code to demonstrate # conversion of a hex string# to the binary string  # Initialising hex stringini_string = "1a"scale = 16  # Printing initial stringprint ("Initial string", ini_string)  # Code to convert hex to binaryres = bin(int(ini_string, scale)).zfill(8)  # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial string 1aResultant string 00b11010
 Method #2: Using Naive Method
# Python code to demonstrate # conversion of hex string# to binary string  import math  # Initialising hex stringini_string = "1a"  # Printing initial stringprint ("Initial string", ini_string)  # Code to convert hex to binaryn = int(ini_string, 16) bStr = ''while n > 0:    bStr = str(n % 2) + bStr    n = n >> 1    res = bStr  # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial string 1aResultant string 11010
 Method #3: Using .format
# Python code to demonstrate # conversion of hex string# to binary string  import math  # Initialising hex stringini_string = "1a"  # Printing initial stringprint ("Initial string", ini_string)  # Code to convert hex to binaryres = "{0:08b}".format(int(ini_string, 16))  # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial string 1aResultant string 00011010
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Slicing list from Kth element to last element

28 Jan, 2019
Python list slicing slices the list from start index till end – 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let’s discuss ways in which last element can be included during a list slice.
Method #1 : Using NoneDuring list slicing, giving the desired first index K and specifying ‘None’ as the second argument in slicing works internally as slicing all the elements from K in list till end including it.
# Python3 code to demonstrate # list slicing from K to end# using None  # initializing listtest_list = [5, 6, 2, 3, 9]  # printing original listprint ("The original list is : " + str(test_list))  # index to begin slicingK = 2  # using None # to perform list slicing from K to endres = test_list[K : None]  # printing result print ("The sliced list is : " +  str(res))
The original list is : [5, 6, 2, 3, 9]
The sliced list is : [2, 3, 9]

 
Method #2 : Leaving the last element emptyUsually, not specifying any element as end element of slicing instructs python to include whole list after K in list. But the main drawback in using this is code readability. Hence above method is preferred more than this.
# Python3 code to demonstrate # list slicing from K to end# without specifying last element   # initializing listtest_list = [5, 6, 2, 3, 9]  # printing original listprint ("The original list is : " + str(test_list))  # index to begin slicingK = 2  # without specifying last element  # to perform list slicing from K to endres = test_list[K :]  # printing result print ("The sliced list is : " +  str(res))
The original list is : [5, 6, 2, 3, 9]
The sliced list is : [2, 3, 9]

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.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Difference between die() and exit() functions in PHP

10 Apr, 2022
PHP exit() Function: In PHP, the exit() function prints a message and exits the application. It’s often used to print a different message in the event of a mistake. Use exit() when there is not an error and have to stop the execution.
Syntax:
exit("Message goes here");
or
exit();
Example:
exit("This request is processed");
Program 1:
PHP
<?php   exit ("This is an exit function in php");   echo "This will not printed because "    . "we have executed exit function";?>
Output:
This is an exit function in php
Program 2:
PHP
<?php  $a = 10;  $b = 10.0;  if($a == $b) {    exit('variables are equal');  }  else {    exit('variables are not equal');  }?>
Output:
variables are equal
PHP die() Function: In PHP, die() is the same as exit(). A program’s result will be an empty screen. Use die() when there is an error and have to stop the execution.
Syntax:
die("Message goes here"); 
or 
die();
Example:
die('Oops! Something went wrong');
Program:
PHP
<?php    $num = 1;     // die can only print string values,    // hence there will be no output    die($num);?>
Output:
No Output
Note: The output for the above program will be an empty screen because it is similar to exit(), die() can print only string values.
Differences between die() and exit() Functions:
die()
exit()
mayank007rawa
PHP-Questions
Picked
Difference Between
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove NA Values from Vector in R

31 Aug, 2021
In this article, we are going to discuss how to remove NA values from the vector.
We can remove those NA values from the vector by using is.na(). is.na() is used to get the na values based on the vector index. !is.na() will get the values except na.
Syntax:
vector[!is.na(vector)]
where the vector is the input vector
Example: R program to remove NA values using above method
R
# create a vectora=c(1,2,NA,4,5,NA,4,5,6,NA) # display aa # remove NAa[!is.na(a)]
Output:
[1]  1  2 NA  4  5 NA  4  5  6 NA
[1] 1 2 4 5 4 5 6
we can also remove na values by computing the sum, mean, variance.
Syntax:
sum(vector, na.rm = TRUE)
where 
na.rm is used to remove na
if na.rm=TRUE it will not consider na
if na.rm=FALSE it will consider na
Syntax:
mean(vector, na.rm = TRUE)
Syntax:
var(vector, na.rm = TRUE)
Example: R program to remove na by using sum, var, and mean
R
# create a vectora=c(1,2,NA,4,5,NA,4,5,6,NA) # display aa # remove NA by computing variancevar(a, na.rm = TRUE) # remove NA by computing sumsum(a, na.rm = TRUE) # remove NA by computing meanmean(a, na.rm = TRUE)
Output:
[1]  1  2 NA  4  5 NA  4  5  6 NA
[1] 3.142857
[1] 27
[1] 3.857143
omit() method is used to remove the NA values directly by resulting in the non-NA values and omitted NA values indexes.
Syntax: 
na.omit(vector)
where the vector is the input vector
Return type:
Returns the non-NA values
Returns the indexes of NA values which are removed from the vector
Note: Indexing starts with 1
Example: R program to consider a vector and remove NA values
R
# create a vector with integers along with NAa=c(1,2,NA,4,5,NA,4,5,6,NA) # displayprint(a) print("_______________________") # remove NA using omit() functiona=na.omit(a) # display vectorprint(a)
Output:
[1]  1  2 NA  4  5 NA  4  5  6 NA
[1] "_______________________"
[1] 1 2 4 5 4 5 6
attr(,"na.action")
[1]  3  6 10
attr(,"class")
[1] "omit"
gulshankumarar231
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
PostgreSQL – DROP TABLE

28 Aug, 2020
PostgreSQL has a DROP TABLE statement that is used to remove an existing table or tables from the database.
Syntax: DROP TABLE [IF EXISTS] table_name [CASCADE | RESTRICT];
Let’s analyze the above syntax:
We specify the table name after the DROP TABLE keyword to remove the table permanently from the database.
In case the table that you want to remove is used in views, constraints, or any other objects, the CASCADE allows users to remove those dependent objects together with the table automatically.
RESTRICTrefuses to drop table if there is any object depends on it. PostgreSQL uses RESTRICT by default.
We can put a list of tables after the DROP TABLE to remove multiple tables at once, each table separated by a comma.
We can put a list of tables after the DROP TABLE to remove multiple tables at once, each table separated by a comma.
It is important to note that only superuser, schema owner, and table owner have sufficient privilege to remove the table.
Example 1:We will remove the author table from our database using the below statement:
DROP TABLE author;
PostgreSQL issues an error because the author table does not exist.To avoid this error, you can use the IF EXISTS parameter as follows:
DROP TABLE IF EXISTS author;
This will lead to PostgreSQL issuing a notice instead of an error.
Output:
Example 2:Here we will remove a table that already exists in our database. To check for all available tables in the database use the below command:
\dt
It will list all existing table as below:Here we will remove the categories table using the below statement:
DROP TABLE categories;
Now check the list of tables again to verify the removal using the below command:
\dt
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Fast Fourier Transformation

26 Aug, 2019
It is an algorithm which plays a very important role in the computation of the Discrete Fourier Transform of a sequence. It converts a space or time signal to signal of the frequency domain.The DFT signal is generated by the distribution of value sequences to different frequency component. Working directly to convert on Fourier transform is computationally too expensive. So, Fast Fourier transform is used as it rapidly computes by factorizing the DFT matrix as the product of sparse factors. As a result, it reduces the DFT computation complexity from O(n2) to O(N log N). And this is a huge difference when working on a large dataset. Also, FFT algorithms are very accurate as compared to the DFT definition directly, in the presence of round-off error.
This transformation is a translation from the configuration space to frequency space and this is very important in terms of exploring both transformations of certain problems for more efficient computation and in exploring the power spectrum of a signal. This translation can be from xn to Xk. It is converting spatial or temporal data into the frequency domain data.
It can perform Discrete Fourier Transform (DFT) in the complex domain.Automatically the sequence is padded with zero to the right because the radix-2 FFT requires the sample point number as a power of 2. For short sequences use this method with default arguments only as with the size of the sequence, the complexity of expressions increases.

Parameters : 
-> seq : [iterable] sequence on which DFT is to be applied.
-> dps : [Integer] number of decimal digits for precision.

Returns : 
Fast Fourier Transform

Example 1 :
# import sympy from sympy import fft  # sequence seq = [15, 21, 13, 44]  # ffttransform = fft(seq)print (transform)
Output :
FFT : [93, 2 - 23*I, -37, 2 + 23*I]
Example 2 :
# import sympy from sympy import fft  # sequence seq = [15, 21, 13, 44]  decimal_point = 4  # ffttransform = fft(seq, decimal_point )print ("FFT : ", transform)
Output :
FFT :  [93, 2.0 - 23.0*I, -37, 2.0 + 23.0*I]

Maths
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON