code-rag-bench/online-tutorials huggingface dataset:
Get column index from column name of a given Pandas DataFrame - GeeksforGeeks

26 Jul, 2020
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together.
Syntax: DataFrame.columns
Return: column names index
Syntax: Index.get_loc(key, method=None, tolerance=None)
Return: loc : int if unique index, slice if monotonic index, else mask
Code: Let’s create a Dataframe:
Python3
# import pandas libraryimport pandas as pd  # dictionaryrecord = {'Math': [10, 20, 30,                    40, 70],          'Science': [40, 50, 60,                      90, 50],           'English': [70, 80, 66,                       75, 88]}  # create a dataframedf = pd.DataFrame(record)  # show the dataframeprint(df)
Output:
Dataframe
Example 1: Get a index number of “Science” column.
Python3
# import pandas libraryimport pandas as pd  # dictionaryrecord = {'Math': [10, 20, 30, 40, 70],          'Science': [40, 50, 60, 90, 50],           'English': [70, 80, 66, 75, 88]}  # give column namecol_name = "Science"  # find the index noindex_no = df.columns.get_loc(col_name)  print("Index of {} column in given dataframe is : {}".format(col_name, index_no))
Output :
index number of Science column
Example 2: Get a index number of “English” column.
Python3
# import pandas libraryimport pandas as pd  # dictionaryrecord = {'Math': [10, 20, 30,                   40, 70],          'Science': [40, 50, 60,                      90, 50],           'English': [70, 80, 66,                      75, 88]}  # create a dataframedf = pd.DataFrame(record)  # give column namecol_name = "English"  # find the index noindex_no = df.columns.get_loc(col_name)  print("Index of {} column in given dataframe is : {}".format(col_name, index_no))
Output :
index number of English column
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
How to change an input button image using CSS?

29 Apr, 2019
The default button in HTML can be changed to an image using CSS. The required button is selected using the respective CSS selector. The background property can then be set to include a background image and change the image type as required. The border of the button can also be removed to show only the image itself.
Example-1: Setting an image to the button.
<!DOCTYPE html><html>  <head>    <title>      How to change an input       button image using CSS?  </title>    <style>        button {            background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20190314004249/sample-image2.png');            background-size: cover;            width: 300px;            height: 200px;            font-size: 2rem;        }    </style></head>  <body>    <h1 style="color: green">      GeeksForGeeks  </h1>    <b>      How to change an input      button image using CSS?  </b>    <p>      The button below has a custom       background image applied through CSS  </p>    <button type="submit">      Test button  </button></body>  </html>
Output:
Example-2: Applying the image when the button is hovered upon. This effect can be useful in making buttons that react to the mouse.
<!DOCTYPE html><html>  <head>    <title>      How to change an input       button image using CSS?  </title>    <style>        button {            width: 300px;            height: 200px;            border: 0;            cursor: pointer;            font-size: 2rem;        }                  button:hover {            background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20190314004249/sample-image2.png');            background-size: cover;        }    </style></head>  <body>    <h1 style="color: green">      GeeksForGeeks  </h1>    <b>How to change an input       button image using CSS?</b>        <p>The button below has a custom      background image applied       through CSS when hovered over it</p>        <button type="submit">      Test button  </button></body>  </html>
Output:Before hovering on the button:
After hovering on the button:
CSS-Misc
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Half Adder and Half Subtractor using NAND NOR gates

22 Feb, 2019
Implementation of Half Adder using NAND gates :Total 5 NAND gates are required to implement half adder.
Implementation of Half Adder using NOR gates :Total 5 NOR gates are required to implement half adder.
Implementation of Half Subtractor using NAND gates :Total 5 NAND gates are required to implement half subtractor.
Implementation of Half Subtractor using NOR gates :Total 5 NOR gates are required to implement half subtractor.
This article is contributed by Sumouli Choudhury
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Compare Two TreeMap Objects in Java? - GeeksforGeeks

05 Aug, 2021
TreeMap class in java provides a way of storing key-value pairs in sorted order. The below example shows how to compare two TreeMap objects using the equals() method. It compares two TreeMap objects and returns true if both of the maps have the same mappings else returns false.
Syntax:
boolean equals(Object o)
Return: It returns true if both the maps are equal else returns false.
Java
// Java program to Compare Two TreeMap Objectsimport java.io.*;import java.util.ArrayList;import java.util.TreeMap; public class GFG {     public static void main(String[] args)    {         // Creating first TreeMap        TreeMap<Integer, String> Office1            = new TreeMap<Integer, String>();         Office1.put(1, "Mumbai");        Office1.put(2, "Delhi");         // Creating second TreeMap        TreeMap<Integer, String> Office2            = new TreeMap<Integer, String>();         Office2.put(1, "Mumbai");        Office2.put(2, "Delhi");         // equals compares two TreeMap objects and        // returns true if both of the maps have the same        // mappings.        System.out.println(Office1.equals(Office2));         // add new mapping to second TreeMap        Office2.put(3, "Goa");         // this will return false as both TreeMap objects do        // not contain same mappings        System.out.println(Office1.equals(Office2));    }}
true
false
 
surinderdawra388
java-TreeMap
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Create a queue using LinkedList class in Java

To create a queue using LinkedList class, try the following −
Queue<String> q = new LinkedList<String>();
q.offer("abc");
q.offer("def");
q.offer("ghi");
q.offer("jkl");
q.offer("mno");
q.offer("pqr");
q.offer("stu");
q.offer("vwx");
After that to print the elements, you need to use check a condition for Queue as shown below −
Object ob;
while ((ob = q.poll()) != null) {
   System.out.println(ob);
}
The following is an example −
 Live Demo
import java.util.LinkedList;
import java.util.Queue;
public class Demo {
   public static void main(String[] args) {
      Queue<String> q = new LinkedList<String>();
      q.offer("abc");
      q.offer("def");
      q.offer("ghi");
      q.offer("jkl");
      q.offer("mno");
      q.offer("pqr");
      q.offer("stu");
      q.offer("vwx");
      System.out.println("Queue head = " + q.element());
      System.out.println("Size = " + q.size());
      System.out.println("\nQueue elements...");
      Object ob;
      while ((ob = q.poll()) != null) {
         System.out.println(ob);
      }
   }
}
Queue head = abc
Size = 8
Queue elements...
abc
def
ghi
jkl
mno
pqr
stu
vwx
Java program to find the smallest number in an array

To find the smallest element of the given array, first of all, sort the array.
Compare the first two elements of the array
If the first element is greater than the second swap them.
Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.
Repeat this till the end of the array.
After sorting an array print the 1st element of the array.
Live Demo
public class SmallestNumberInAnArray {
   public static void main(String args[]){
      int temp, size;
      int array[] = {10, 20, 25, 63, 96, 57};
      size = array.length;

      for(int i = 0; i<size; i++ ){
         for(int j = i+1; j<size; j++){
            if(array[i]>array[j]){
               temp = array[i];
               array[i] = array[j];
               array[j] = temp;
            }
         }
      }
      System.out.println("Smallest element of the array is:: "+array[0]);
   }
}
Smallest element of the array is:: 10
You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the 1st element of the array.
import java.util.Arrays;
public class LargestNumberSample {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;
      Arrays.sort(array);
      System.out.println("sorted Array ::"+Arrays.toString(array));
      int res = array[0];
      System.out.println("smallest element is ::"+res);
   }
}
sorted Array ::[10, 20, 25, 57, 63, 96]
largest element is ::10
Tryit Editor v3.7

Tryit: Top tooltip with bottom arrow
Read CSV file and select specific rows and columns in R

20 May, 2021
In this article, we are going to see how to read CSV file and select specific rows and columns in R Programming Language.
CSV file:
To import a CSV file into the R environment we need to use a pre-defined function called read.csv(). Pass filename.csv as a parameter within quotations. First, we need to set the path to where the CSV file is located using setwd( ) otherwise we can pass the full path of the CSV file into read.csv( ) as a parameter.
Example 1: Selecting specific multiple rows
R
df = read.csv('C:/Users/KRISHNA KARTHIKEYA/Documents/item.csv')  a = df[c(2, 7),]print(a)
Output :
Explanation :
In the first step, we have imported a CSV file into the R environment using read.csv( ) function.
In the next step, we have selected 2,7 rows from CSV file using indexing and storing the result into a variable
Example 2: Selecting specific single rows
R
df = read.csv('C:/Users/KRISHNA KARTHIKEYA/Documents/item.csv')a = df[ 2, ]print(a)
Output :
Example 3: Selecting multiple columns
R
df = read.csv('C:/Users/KRISHNA KARTHIKEYA/Documents/item.csv')a = df[, c(3 , 4)]print(a)
Output : 
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
R - if statement
Supplier Interface in Java with Examples

08 Oct, 2018
The Supplier Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take in any argument but produces a value of type T.
Hence this functional interface takes in only one generic namely:-
T: denotes the type of the result
The lambda expression assigned to an object of Supplier type is used to define its get() which eventually produces a value. Suppliers are useful when we don’t need to supply any value and obtain a result at the same time.
The Supplier interface consists of only one function:
This method does not take in any argument but produces a value of type T.
Syntax:
T get()
Returns: This method returns a value of type T.
Below is the code to illustrate get() method:
Program:
import java.util.function.Supplier;  public class Main {    public static void main(String args[])    {          // This function returns a random value.        Supplier<Double> randomValue = () -> Math.random();          // Print the random value using get()        System.out.println(randomValue.get());    }}
0.5685808855697841

Java - util package
Java 8
java-basics
java-interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Array join() Method

01 Nov, 2021
Below is the example of the Array join() method.
Example:<script>    function func() {       var a = [ 1, 2, 3, 4, 5, 6 ];       document.write(a.join('|'));    }    func(); < /script> 
<script>    function func() {       var a = [ 1, 2, 3, 4, 5, 6 ];       document.write(a.join('|'));    }    func(); < /script> 
Output:1|2|3|4|5|6
1|2|3|4|5|6
The arr.join() method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).
Syntax:
array.join(separator)
Parameters: This method accept single parameter as mentioned above and described below:
separator: It is Optional i.e, it can be either used as parameter or not.Its default value is comma(, ).
Return Value: It returns the String which contain the collection of array’s elements.
Below example illustrate the Array join() method in JavaScript:
Example 1: In this example the function join() joins together the elements of the array into a string using ‘|’.var a = [1, 2, 3, 4, 5, 6];
print(a.join('|'));Output:1|2|3|4|5|6
var a = [1, 2, 3, 4, 5, 6];
print(a.join('|'));
Output:
1|2|3|4|5|6
Example 2: In this example the function join() joins together the elements of the array into a string using ‘, ‘ since it is the default value.var a = [1, 2, 3, 4, 5, 6];
print(a.join()); Output:1, 2, 3, 4, 5, 6
var a = [1, 2, 3, 4, 5, 6];
print(a.join()); 
Output:
1, 2, 3, 4, 5, 6
Example 3: In this example the function join() joins together the elements of the array into a string using ‘ ‘ (empty string).var a = [1, 2, 3, 4, 5, 6];
print(a.join(''));Output:123456
var a = [1, 2, 3, 4, 5, 6];
print(a.join(''));
Output:
123456
Code for the above method is provided below:Program 1:
<script>    function func() {       var a = [ 1, 2, 3, 4, 5, 6 ];       document.write(a.join());    }      func(); </script> 
Output:
1, 2, 3, 4, 5, 6
Program 2:
<script>    function func() {       var a = [ 1, 2, 3, 4, 5, 6 ];       document.write(a.join(''));    }    func(); </script> 
Output:
123456
Supported Browsers: The browsers supported by JavaScript Array join() method are listed below:
Google Chrome 1.0 and above
Microsoft Edge 12 and above
Mozilla Firefox 1.0
Safari 1 and above
Opera 4 and above
nidhi_biet
ysachin2314
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
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 Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
C# | Byte.MaxValue Field

23 Apr, 2019
The MaxValue field of Byte Struct is used to represent the maximum value of the byte data type. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 255. Its hexadecimal value is 0xFF.
Syntax:
public const byte MaxValue = 255;
Return Value: This field always returns 255.
Example:
// C# program to illustrate the// Byte.MaxValue Fieldusing System;  class GFG {      // Main Method    static public void Main()    {        // display the Maximum        // value of Byte struct        Console.WriteLine("Maximum Value is: " + Byte.MaxValue);          // taking a variable        byte var1 = 255;          if (var1.Equals(Byte.MaxValue))         {            Console.WriteLine("Equal..!!");            Console.WriteLine("Type of var1 is: {0}",                                 var1.GetTypeCode());        }          else         {            Console.WriteLine("Not equal..!!");            Console.WriteLine("Type of var1 is: {0}",                                 var1.GetTypeCode());        }    }}
Maximum Value is: 255
Equal..!!
Type of var1 is: Byte

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.byte.maxvalue?view=netstandard-2.1
CSharp-Byte-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
Python | Pandas Index.append()

16 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.append() function is used to append a single or a collection of indices together. In case of collection of indices, all of them gets appended to the original index in the same order as they are passed to the Index.append() function. The function returns an appended index.
Syntax: Index.append(other)
Parameters :other : Index or list/tuple of indices
Returns : appended : bool or array_like (if axis is specified)A single element array_like may be converted to bool.
Example #1: Use Index.append() function to append a single index to the given index.
# importing pandas as pdimport pandas as pd  # Creating the first Indexdf1 = pd.Index([17, 69, 33, 5, 0, 74, 0])  # Creating the second Indexdf2 = pd.Index([11, 16, 54, 58])  # Print the first and second Indexprint(df1, "\n", df2)
Output :
Let’s append df2 index at the end of df1.
# append df2 at the end of df1df1.append(df2)
Output :
As we can see in the output, the second index i.e. df2 has been appended at the end of df1. Example #2: Use Index.append() function to append a collection of index at the end of the given index.
# importing pandas as pdimport pandas as pd  # Creating the first Indexdf1 = pd.Index(['Jan', 'Feb', 'Mar', 'Apr'])  # Creating the second Indexdf2 = pd.Index(['May', 'Jun', 'Jul', 'Aug'])  # Creating the third Indexdf3 = pd.Index(['Sep', 'Oct', 'Nov', 'Dec'])  # Print the first, second and third Indexprint(df1, "\n", df2, "\n", df3)
Output :
Let’s append both the indexes df2 and df3 at the end of df1.
# We pass df2 and df3 as a list of# indexes to the append functiondf1.append([df2, df3])
Output :
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find the Strongest Neighbour

28 Jul, 2020
Given an array arr[] of N positive integers. The task is to find the maximum for every adjacent pair in the array.
Examples:
Input: 1 2 2 3 4 5
Output: 2 2 3 4 5

Input: 5 5
Output: 5

Approach:
Read the input array i.e,arr1.for i=1 to sizeofarray-1find the max value between arr1[i] and arr1[i-1].store the above value in another array i.e, arr2.print the values of arr2.
Read the input array i.e,arr1.
for i=1 to sizeofarray-1find the max value between arr1[i] and arr1[i-1].store the above value in another array i.e, arr2.
find the max value between arr1[i] and arr1[i-1].
store the above value in another array i.e, arr2.
print the values of arr2.
Below is the implementation.
Python3
# define a function for finding# the maximum for adjacent# pairs in the arraydef maximumAdjacent(arr1, n):          # array to store the max     # value between adjacent pairs    arr2 = []            # iterate from 1 to n - 1    for i in range(1, n):                # find max value between         # adjacent  pairs gets         # stored in r        r = max(arr1[i], arr1[i-1])                  # add element         arr2.append(r)              # printing the elements    for ele in arr2 :        print(ele,end=" ")  if __name__ == "__main__" :      # size of the input array  n = 6        # input array  arr1 = [1,2,2,3,4,5]      # function calling  maximumAdjacent(arr1, n)
Output: 
2 2 3 4 5

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.
Compute the Value of Poisson Quantile Function in R Programming – qpois() Function

25 Jun, 2020
qpois() function in R Language is used to compute the value of Poisson Quantile Function. It creates a quantile density plot for poisson distribution.
Syntax: qpois(vec, lambda)
Parameters:vec: Sequence of integer valueslambda: Average number of events per interval
Example 1:
# R program to compute # Poisson Quantile Density  # Sequence of x-valuesx <- seq(0, 1, by = .01)  # Calling qpois() Functiony <- qpois(x, lambda = 5)y
Output:
  [1]   0   1   1   1   1   2   2   2   2   2   2   2   2   3   3   3   3   3
 [19]   3   3   3   3   3   3   3   3   3   4   4   4   4   4   4   4   4   4
 [37]   4   4   4   4   4   4   4   4   4   5   5   5   5   5   5   5   5   5
 [55]   5   5   5   5   5   5   5   5   6   6   6   6   6   6   6   6   6   6
 [73]   6   6   6   6   6   7   7   7   7   7   7   7   7   7   7   8   8   8
 [91]   8   8   8   8   9   9   9  10  10  11 Inf

Example 2:
# R program to compute # Poisson Quantile Density  # Sequence of x-valuesx <- seq(0, 1, by = 0.01)  # Calling qpois() Functiony <- qpois(x, lambda = 15)  # Plot a graphplot(y)
Output:
R Statistics-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Puzzle 40 | (Find missing Row in Excel)

10 May, 2021
We are given an excel sheet which contains integers from 1 to 50, including both. However, the numbers are in a jumbled form and there is 1 integer missing. You have to write a code to identify the missing integer. Only the logic is required.
   
Solution:We know that the sum of all the numbers from 1 to n is (n*(n+1)/2)Therefore, sum of all the numbers from 1 to 50 is
50*(50+1)/2  (Here, n = 50) 
  = 50*(51)/2 
  = 25*51
  = 1275.
Therefore, all we need to do is to sum all the integers present in the file and subtract the sum from 1275. The difference between 1275 and this sum would give us the missing integer.
See this for code.
This puzzle is contributed by Feroz Baig. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Puzzles
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Top 20 Puzzles Commonly Asked During SDE Interviews
Puzzle 8 | (Find the Jar with contaminated pills)
Puzzle 18 | (Torch and Bridge)
Puzzle 11 | (1000 Coins and 10 Bags)
Puzzle 16 | (100 Doors)
Puzzle 10 | (A Man with Medical Condition and 2 Pills)
Puzzle 13 | (100 Prisoners with Red/Black Hats)
Container with Most Water
Puzzle 19 | (Poison and Rat)
How to get an interactive plot of a pyplot when using PyCharm?

To get an interactive plot of a pyplot when using PyCharm, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Set the background style.
Set the background style.
Plot the data on the axes.
Plot the data on the axes.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib as mpl
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

mpl.use('Qt5Agg')

plt.plot(range(10))

plt.show()
How to zip a folder recursively using Python?

Use the zipfile module to create a zip archive of a directory. Walk the directory tree using os.walk and add all the files in it recursively. 
import os
import zipfile
def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))
zipf = zipfile.ZipFile('Zipped_file.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('./my_folder', zipf)
zipf.close()
The above code will zip the contents of my_folder in a file 'Zipped_file.zip'. and store it in the current directory.
Find largest prime factor of a number using C++.

Consider we have an element x, we have to find the largest prime factor of x. If the value of x is 6,  then-largest prime factor is 3. To solve this problem, we will just factorize the number by dividing it with the divisor of a number and keep track of the maximum prime factor.
 Live Demo
#include <iostream>
#include<cmath>
using namespace std;
long long getMaxPrimefactor(long long n) {
   long long maxPF = -1;
   while (n % 2 == 0) {
      maxPF = 2;
      n /= 2;
   }
   for (int i = 3; i <= sqrt(n); i += 2) {
      while (n % i == 0) {
         maxPF = i;
         n = n / i;
      }
   }
   if (n > 2)
   maxPF = n;
   return maxPF;
}
int main() {
   long long n = 162378;
   cout << "Max Prime factor of " << n << " is " << getMaxPrimefactor(n);
}
Max Prime factor of 162378 is 97
Container to create a grid of Bootstrap 4 cards of equal height and width

Set a container of cards, using the card-deck class.
Work it inside the following div that would be of equal width and height −
<div class="card-deck">
  <div class="card bg-primary">
  <!- - One  - ->
</div>
<div class="card bg-primary">
  <!- - Two  - ->
  </div>
</div>
You can try to run the following code to implement the card-deck class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h3>Demo Messages</h3>
    <p>Note: Resize the browser to check the effect.</p>
    <div class="card-deck">
      <div class="card bg-primary">
        <div class="card-body text-center">
        <p class="card-text">Nothing new!</p>
      </div>
    </div>
   <div class="card bg-warning">
     <div class="card-body text-center">
       <p class="card-text">Warning! Compile-time error!</p>  
       <p class="card-text">Check again!</p>
     </div>
   </div>
   <div class="card bg-success">
     <div class="card-body text-center">
       <p class="card-text">We won!</p>
     </div>
   </div>
  </div>
</div>

</body>
</html>
Spiral Matrix III in C++

Suppose we have a 2 dimensional grid with R rows and C columns, we start from (r0, c0) facing east. Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the grid is at the last row and column. We will walk in a clockwise spiral shape to visit every position in this grid. When we are at the outside the boundary of the grid, we continue our walk outside the grid (but may return to the grid boundary later.). We have to find a list of coordinates representing the positions of the grid in the order they were visited. So if the grid is like −
Then the arrow will be the path.
To solve this, we will follow these steps −
Create dirr := [[0,1],[1,0],[0,-1],[-1,0]]
Create dirr := [[0,1],[1,0],[0,-1],[-1,0]]
create a matrix ret, len := 0, dir := 0
create a matrix ret, len := 0, dir := 0
insert (r0, c0) into ret
insert (r0, c0) into ret
while size of ret < R*Cif dir = 0 or dir = 2, then increase len by 1for i in range 0 to len – 1r0 := r0 + dirr[dir, 0], c0 := c0 + dirr[dir, 1]if r0 in range of 0 to R, and c0 in range 0 to C, then go for next iterationinsert (r0, c0) into retdir := (dir + 1) mod 4
while size of ret < R*C
if dir = 0 or dir = 2, then increase len by 1
if dir = 0 or dir = 2, then increase len by 1
for i in range 0 to len – 1r0 := r0 + dirr[dir, 0], c0 := c0 + dirr[dir, 1]if r0 in range of 0 to R, and c0 in range 0 to C, then go for next iterationinsert (r0, c0) into ret
for i in range 0 to len – 1
r0 := r0 + dirr[dir, 0], c0 := c0 + dirr[dir, 1]
r0 := r0 + dirr[dir, 0], c0 := c0 + dirr[dir, 1]
if r0 in range of 0 to R, and c0 in range 0 to C, then go for next iteration
if r0 in range of 0 to R, and c0 in range 0 to C, then go for next iteration
insert (r0, c0) into ret
insert (r0, c0) into ret
dir := (dir + 1) mod 4
dir := (dir + 1) mod 4
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
int dirr[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
class Solution {
   public:
   vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {
      vector < vector <int> > ret;
      int len = 0;
      int dir = 0;
      ret.push_back({r0, c0});
      while(ret.size() < R * C){
         if(dir == 0 || dir == 2) len++;
         for(int i = 0; i < len; i++){
            r0 = r0 + dirr[dir][0];
            c0 = c0 + dirr[dir][1];
            if(r0 < 0 || c0 < 0 || c0 >= C || r0 >= R) continue;
            ret.push_back({r0, c0});
         }
         dir = (dir + 1) % 4;
      }
      return ret;
   }
};
main(){
   Solution ob;
   print_vector(ob.spiralMatrixIII(5,5,1,3));
}
5

5

1

3
[[1,3],[1,4],[2,4],[2,3],[2,2],[1,2],[0,2],[0,3],[0,4],[3,4],[3,3],[3,2],[3,1],[2,1],[1,1],[0,1],[4,4],[4,3],[4,2],[4,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
How to generate armstrong numbers in Python?

Any three digit number is called an Armstrong number of sum of cube of its digits equals the number itself. In order to check if a number satisfies this condition, each digit from it is successively separated from right and its cube is cumulatively added. In the end if the sum is found to be equal to original number, it is called Armstrong number.
Following Python code prints all armstrong numbers between 100 to 999
for num in range(100,1000):
  temp=num
  sum=0
  while temp>0:
    digit=temp%10
    sum=sum+digit**3
    temp=temp//10

  if sum==num:
    print (num)
The output is list of armstrong numbers
153
370
371
407
PHP Associative Array

In PHP, an array is a comma separated collection of key => value pairs. Such an array is called Associative Array where value is associated to a unique key. The key part has to ba a string or integer, whereas value can be of any type, even another array.
Use of key is optional. If array consists only of values, it becomes an indexed array, with zero based positional index of value behaves as a key.
Array object can be initialized by array() function as well as assignment by putting elements inside square brackets []
//Associative array using array() function
$arr=array(key1=>val1, key2=>val2,key3=val3,..);
//Associative array using assignment method
$arr=[key1=>val1, key2=>val2,key3=val3,..];
Key should either be integer or string. Value component can be of any PHP type. If a certain key appears repeatedly, last value assigned will overwrite earlier values. We can access value associated with a certain key by following syntax −
$arr[key1];
Use of square brackets for assignment of array is available since PHP 5.4
Following example uses array() function to declare an associative array
 Live Demo
<?php
$arr=array(1=>"one", 2=>"two", 3=>"three");
var_dump($arr);
?>
This will produce following result −
array(3) {
   [1]=>
   int(11)
   [2]=>
   int(22)
   [3]=>
   int(33)
}
This Example uses square brackets for assignment of associative array
 Live Demo
<?php
$arr=[1=>"one", 2=>"two", 3=>"three"];
var_dump($arr);
?>
This will produce following result −
array(3) {
   [1]=>
   string(3) "one"
   [2]=>
   string(3) "two"
   [3]=>
   string(5) "three"
}
We can traverse the array elements using foreach loop as follows:
 Live Demo
<?php
$arr=[1=>"one", 2=>"two", 3=>"three"];
//using foreach loop
foreach ($arr as $key=>$value){
   echo $key . "=>" . $value . "\n";
}
?>
This will produce following result −
1=>one
2=>two
3=>three
This Example shows modify value of existing element and add new key-value pair using square brackets
 Live Demo
<?php
$arr=[1=>"one", 2=>"two", 3=>"three"];
//modify array element
$arr[2]="twenty";
//add new element in array
$arr[10]="ten";
//using foreach loop
foreach ($arr as $key=>$value){
   echo $key . "=>" . $value . "\n";
}
?>
This will produce following result −
1=>one
2=>twenty
3=>three
10=>ten
C program to display all prime numbers between 1 to N using for loop

Write a C program to display all the prime numbers between 1 and n is a value given by the user at run time.
C program to display all the prime numbers between 1 and n is a value given by the user at run time is explained below −
Given below is an algorithm to display all the prime numbers between 1 and n is a value given by the user at run time.
Step 1 − Read n value.
Step 2 − Initialize count = 0
Step 3 − for i = 2 to n
   a. for j = 1 to i
   b. if i % j = 0
   c. then increment count
   d. if count is equal to 2
   e. then print i value
A flowchart is given below to explain the algorithm for the C program to display all the prime numbers between 1 and n is a value given by the user at run time.
Following is the C program to display all the prime numbers between 1 and n is a value given by the user at run time −
 Live Demo
#include<stdio.h>
void main(){
   int i, num, n, count;
   printf("Enter the range: \n");
   scanf("%d", &n);
   printf("The prime numbers in between the range 1 to %d:",n);
   for(num = 1;num<=n;num++){
      count = 0;
      for(i=2;i<=num/2;i++){
         if(num%i==0){
            count++;
         break;
      }
   }
   if(count==0 && num!= 1)
      printf("%d ",num);
   }
}
When the above program is executed, it produces the following result −
Enter the range:50
The prime numbers in between the range 1 to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Excel Pivot Table Calculated Field - GeeksforGeeks

30 Nov, 2021
“Pivot Table calculated field” is an option to include more data or calculations in the pivot table.  Often, we need to add our own custom calculations that can refer to other fields in the data set for our reports.  
In the below examples we create a sales report by-product with an additional column “Sales Differences” [2020_Sales – 2019_Sales].  Calculated field “Sales Differences” calculation refers to other fields in the dataset [subtract 2019_Sales from 2020_Sales].
Eg: We have a data set in four columns “Product”, ”Customer”, “2019_Sales” and “2020_Sales” as below
Follow the below steps to create a pivot table:
Step 1: Select Insert >> Pivot >> From Table/Range (Img1)  to popup “PivotTable from table or range” dialog box (Img 2).
Img 1
Img 2
Step 2: Enter your data set range in “Table/Range” input, choose New worksheet, and Click “OK
Step 3: Above step add a new sheet with a pivot table for your data set.
Pivot Table
Step 4: Drag the field “Products” to the Rows pane
Step 5: Drag 2019_Sales and 2020_Sales to Values pane.
You created a pivot table for your dataset.  Now we add a calculated field to display the sales_differences in the pivot table
Step 6: To popup the “Insert Calculated Field” dialog box.  Click anywhere in the pivot table. Goto PivotTable Analyze in Ribbon >> Fields, Items & Sets >> Calculated Field...
Step 7: Above step popup below dialog box and type “Sales_Differences” [Calculated field Name] in the Name input box
Step 8: Select “2020_Sales” from the fields list and Click Insert Field.
Step 9: Just type “-“ in Formula (for Subtraction).
Step 10: Select “2019_Sales” from the fields list and Click Insert Field.
Step 11: Please make sure your formula is like below
='2020_Sales'-'2019_Sales'  
Step 12: Finally click Add then OK, you can see the pivot with additional columns “Sales_Differences” [Calculated Field] as in the below output
Output:
Excel-functions
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Show Percentages in Stacked Column Chart in Excel?
How to Get Length of Array in Excel VBA?
How to Remove Duplicates From Array Using VBA in Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
How to Easily Calculate the Dot Product in Excel?
Python seek() function

28 Apr, 2022
The concept of file handling is used to preserve the data or information generated after running the program. Like other programming languages like C, C++, Java, Python also support file handling. 
Refer the below article to understand the basics of File Handling.  
File Handling in Python.  
Reading and Writing to files in Python 
 
 
In Python, seek() function is used to change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file.  
Syntax: f.seek(offset, from_what), where f is file pointerParameters: Offset: Number of positions to move forward from_what: It defines point of reference.Returns: Return the new absolute position.
The reference point is selected by the from_what argument. It accepts three values:  
0: sets the reference point at the beginning of the file  
1: sets the reference point at the current file position  
2: sets the reference point at the end of the file  
By default from_what argument is set to 0.Note: Reference point at current position / end of file cannot be set in text mode except when offset is equal to 0.Example 1: Let’s suppose we have to read a file named “GfG.txt” which contains the following text:  
"Code is like humor. When you have to explain it, it’s bad."    
 
Python3
# Python program to demonstrate# seek() method  # Opening "GfG.txt" text filef = open("GfG.txt", "r") # Second parameter is by default 0# sets Reference point to twentieth# index position from the beginningf.seek(20) # prints current positionprint(f.tell()) print(f.readline())f.close()
20
When you have to explain it, it’s bad.
 
Example 2: Seek() function with negative offset only works when file is opened in binary mode. Let’s suppose the binary file contains the following text. 
b'Code is like humor. When you have to explain it, its bad.'
 
Python3
# Python code to demonstrate# use of seek() function       # Opening "GfG.txt" text file# in binary modef = open("data.txt", "rb") # sets Reference point to tenth# position to the left from endf.seek(-10, 2) # prints current positionprint(f.tell()) # Converting binary to string and# printingprint(f.readline().decode('utf-8')) f.close()
47
, its bad.
 
sweetyty
tanaypandey
python-file-handling
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
How to clear the text entered in Selenium with python?

We can enter text on any field in Selenium. After entering the text, we may need to remove or clear the text we entered in that field. This interaction with the web elements can be achieved with the help of clear() method.
Thus a clear() method is used to clear or reset an input field belonging to a form/ edit box. It replaces the text content on that particular element of the page.
driver.find_element_by_xpath("//input[class ='gsc-search']").clear()
Code Implementation with clear() method.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/current_affairs.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box and entering text in edit box
driver.find_element_by_xpath("//*[@class='gsc-input']"). send_keys("Selenium")
# clears the content
driver.find_element_by_xpath("//*[@class='gsc-input']").clear()
#to close the browser
driver.close
Scala Map toSeq() method with example

29 Jul, 2019
The toSeq() method is utilized to display a sequence from the Scala map.
Method Definition: def toSeq: Seq[A]
Return Type: It returns a sequence from the stated map.
Example #1:
// Scala program of toSeq()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 4 -> "for")                  // Applying toSeq method        val result = m1.toSeq                  // Displays output        println(result)          }}
ArrayBuffer((3, geeks), (4, for))

Example #2:
// Scala program of toSeq()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying toSeq method        val result = m1.toSeq                  // Displays output        println(result)          }}
ArrayBuffer((3, geeks), (4, for), (2, cs))

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Operators in Scala
Scala Constructors
Scala | Arrays
Inheritance in Scala
Enumeration in Scala
How to get the first element of List in Scala
Lambda Expression in Scala
How to Install Scala with VSCode?
Data Classes in Python | Set 5 (post-init) - GeeksforGeeks

15 Apr, 2019
Prerequisite: Data Classes in Python | Set 4
In this post, we will discuss how to modify values of some attributes during object creation without coding it in __init__() by using post-init processing.
__post_init__(): This function when made, is called by in-built __init__() after initialization of all the attributes of DataClass. Basically, object creation of DataClass starts with __init__() (constructor-calling) and ends with __post__init__() (post-init processing).Use –This feature is very handy at times when certain attributes are dependent on the parameters passed in the __init__() but do not get their values directly from them. That is, they get their values after performing some operation on a subset of arguments received in the constructor.Continuing the same example we’ve been seeing in this series of articles, suppose there is an attribute called author_name which gets its value from the profile handle to name mapping in the defined dictionary name.So author_name is dependent on profile handle which author attribute receives, so using __post_init__() should be an ideal choice this case.
from dataclasses import dataclass, field  name = {'vibhu4agarwal': 'Vibhu Agarwal'}    @dataclassclass GfgArticle:      title : str    language: str    author: str    author_name: str = field(init = False)    upvotes: int = 0      def __post_init__(self):        self.author_name = name[self.author]    dClassObj = GfgArticle("DataClass", "Python3", "vibhu4agarwal")print(dClassObj)
Output:
GfgArticle(title=’DataClass’, language=’Python3′, author=’vibhu4agarwal’, author_name=’Vibhu Agarwal’, upvotes=0)
Can default_factory be an alternative?No, because default_factory accepts zero argument function or callable, so it can’t receive any arguments and return a value after performing some operations on them.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How to pass objects to functions in C++?

There are four ways of passing objects to functions. Let's assume you have a class X and want to pass it to a function fun, then −
This creates a shallow local copy of the object in the function scope. Things you modify here won't be reflected in the object passed to it. For example,
Declaration
void fun(X x);

Calling
X x;
fun(x);

This passes a reference to the object to the function. Things you modify here will be reflected in the object passed to it. No copy of the object is created. For example,
Declaration
void fun(X &x);

Calling
X x;
fun(x);

This passes a const reference to the object to the function. You cannot modify/reassign the object here directly(you can use its methods that do so though). This is useful if you want the function to have only a readonly copy of the object. No copy of the object is created. For example,
Declaration
void fun(X const &x);

Calling
X x;
fun(x);

This passes a const pointer to the object to the function. You cannot modify/reassign the pointer here. This is useful if you want the function to have only the address of this object in the pointer. No copy of object is created. For example,
Declaration
void fun(X const *x);

Calling
X x;
fun(&x);

This passes a pointer to the object to the function. This is similar to passing a reference to the object. No copy of object is created. For example,
Declaration
void fun(X *x);

Calling
X x;
fun(&x);
How to catch all JavaScript unhandled exceptions?

To catch all JavaScript unhandled exceptions, use window.error. The onerror event handler provides three pieces of information to identify the exact nature of the error −
Error message − The same message that the browser would display for the given error
URL − The file in which the error occurred
Line number− The line number in the given URL that caused the error
You can try to run the following code to catch unhandled exceptions −
<html>
   <head>
      <script>
         <!--
            window.onerror = function (msg, url, line) {
               alert("Message : " + msg );
               alert("url : " + url );
               alert("Line number : " + line );
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following to see the result:</p>
      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>
   </body>
</html>