code-rag-bench/online-tutorials huggingface dataset:
Angular 2 - Handling Events

In Angular 2, events such as button click or any other sort of events can also be handled very easily. The events get triggered from the html page and are sent across to Angular JS class for further processing.
Let’s look at an example of how we can achieve event handling. In our example, we will look at displaying a click button and a status property. Initially, the status property will be true. When the button is clicked, the status property will then become false.
Step 1 − Change the code of the app.component.ts file to the following.
import { 
   Component 
} from '@angular/core';  

@Component ({ 
   selector: 'my-app', 
   templateUrl: 'app/app.component.html' 
}) 

export class AppComponent { 
   Status: boolean = true; 
   clicked(event) { 
      this.Status = false; 
   } 
}
Following points need to be noted about the above code.
We are defining a variable called status of the type Boolean which is initially true.
We are defining a variable called status of the type Boolean which is initially true.
Next, we are defining the clicked function which will be called whenever our button is clicked on our html page. In the function, we change the value of the Status property from true to false.
Next, we are defining the clicked function which will be called whenever our button is clicked on our html page. In the function, we change the value of the Status property from true to false.
Step 2 − Make the following changes to the app/app.component.html file, which is the template file.
<div> 
   {{Status}} 
   <button (click) = "clicked()">Click</button> 
</div> 
Following points need to be noted about the above code.
We are first just displaying the value of the Status property of our class.
We are first just displaying the value of the Status property of our class.
Then are defining the button html tag with the value of Click. We then ensure that the click event of the button gets triggered to the clicked event in our class.
Then are defining the button html tag with the value of Click. We then ensure that the click event of the button gets triggered to the clicked event in our class.
Step 3 − Save all the code changes and refresh the browser, you will get the following output.
Step 4 − Click the Click button, you will get the following output.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Find maximum element along with its index in Julia - findmax() Method - GeeksforGeeks

26 Mar, 2020
The findmax() is an inbuilt function in julia which is used to return the maximum element of the specified collection along with its index. If there are multiple maximal elements are present in the collection, then the first one will be returned. If there is any data element is NaN, this element is returned.
Syntax:findmax(itr)orfindmax(A; dims)
Parameters:
itr: Specified collection of elements.
A: Specified array.
dims: Specified dimension.
Returns: It returns the maximum elements with their corresponding index.
Example 1:
# Julia program to illustrate # the use of findmax() method  # Getting the maximum elements# with their corresponding index.println(findmax([1, 2, 3, 4]))println(findmax([5, 0, false, 6]))println(findmax([1, 2, 3, true]))println(findmax([5, 0, NaN, 6]))println(findmax([1, 2, 3, 3]))
Output:
Example 2:
# Julia program to illustrate # the use of findmax() method  # Getting the value and index of# the maximum over the given dimensionsA = [5 10; 15 20];println(findmax(A, dims = 1))println(findmax(A, dims = 2))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vectors in Julia
Comments in Julia
Storing Output on a File in Julia
while loop in Julia
Getting rounded value of a number in Julia - round() Method
Reshaping array dimensions in Julia | Array reshape() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Functions in Julia
Creating array with repeated elements in Julia - repeat() Method
Get array dimensions and size of a dimension in Julia - size() Method
Java nested if statement example

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.
The syntax for a nested if...else is as follows −
if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
   if(Boolean_expression 2) {
      // Executes when the Boolean expression 2 is true
   }
}
You can nest else if...else in the similar way as we have nested if statement.
Live Demo
public class Test {

   public static void main(String args[]) {
      int x = 30;
      int y = 10;

      if( x == 30 ) {
         if( y == 10 ) {
            System.out.print("X = 30 and Y = 10");
         }
      }
   }
}
This will produce the following result −
X = 30 and Y = 10
Select any row from a Dataframe in Pandas | Python - GeeksforGeeks

24 Oct, 2019
In this article, we will learn how to get the rows from a dataframe as a list, without using the functions like ilic[]. There are multiple ways to do get the rows as a list from given dataframe. Let’s see them will the help of examples.
# importing pandas as pd import pandas as pd     # Create the dataframe df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],                     'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],                     'Cost':[10000, 5000, 15000, 2000]})     # using interrors() method  # Create an empty list Row_list =[]     # Iterate over each row for index, rows in df.iterrows():       # Create list for the current row     my_list =[rows.Date, rows.Event, rows.Cost]             # append the list to the final list     Row_list.append(my_list)     # Print the list print(Row_list) 
Output:
[['10/2/2011', 'Music', 10000], ['11/2/2011', 'Poetry', 5000], 
      ['12/2/2011', 'Theatre', 15000], ['13/2/11', 'Comedy', 2000]]

    # Print the first 2 elements print(Row_list[:2]) 
Output:
[['10/2/2011', 'Music', 10000], ['11/2/2011', 'Poetry', 5000]]

pandas-dataframe-program
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
Python | Convert set into a list
Python program to find number of days between two given dates
Python program to print decimal octal hex and binary of first n numbers

Suppose we have a value n. We have to print Decimal, Octal, Hexadecimal and Binary equivalent of first n numbers (1 to n) in four different columns. As we know, we can express the numbers with prefix characters d, o, X and b for decimal, octal, hexadecimal and decimal respectively.
So, if the input is like n = 10, then the output will be
1    1    1    1
2    2    2   10
3    3    3   11
4    4    4  100
5    5    5  101
6    6    6  110
7    7    7  111
8   10    8 1000
9   11    9 1001
10  12    A 1010
To solve this, we will follow these steps −
l := (length of binary equivalent of n) - 2
for i in range 1 to n, dof := blank stringfor each character c in "doXb", doif f is not empty, thenf := f concatenate one blank spacef := f + right aligned formatting string by converting l as string then concatenate cpass i four times to the formatted string f and print the line
f := blank string
for each character c in "doXb", doif f is not empty, thenf := f concatenate one blank spacef := f + right aligned formatting string by converting l as string then concatenate c
if f is not empty, thenf := f concatenate one blank space
f := f concatenate one blank space
f := f + right aligned formatting string by converting l as string then concatenate c
pass i four times to the formatted string f and print the line
Let us see the following implementation to get better understanding
def solve(n):
   l = len(bin(n)) - 2
   for i in range(1, n + 1):
      f = ""
      for c in "doXb":
         if f:
            f += " "
         f += "{:>" + str(l) + c + "}"
      print(f.format(i, i, i, i))

n = 10
solve(n)


10
1    1    1    1
2    2    2   10
3    3    3   11
4    4    4  100
5    5    5  101
6    6    6  110
7    7    7  111
8   10    8 1000
9   11    9 1001
10  12    A 1010
Add 1 to a number represented as a linked list?

The linked list representation of a number is provided in such a way that the all nodes of the linked list are treated as one digit of the number. The node stores the number such that the first element of the linked list holds the most significant digit of the number, and the last element of the linked list holds the least significant bit of the number. For example, the number 202345 is represented in the linked list as (2->0->2->3->4->5).
And to add one to this linked list represented number we have to check the value of the least significant bit of the list. If it is less than 9 than it's ok otherwise the code will change the next digit and so on.
Now lets see an example to know how to do it, 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0)
Input:1999
Output:2000
To add 1 to a given number represented as a linked list meaning to follow some steps that are,
reversing the linked list: you need to reverse the linked list that this means changing the last digit to the first and the first to the last. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1.
for this changed linked list now traverse the list, in the left-most node add one. if this node’s value is equal to 9 then propagate a carry to the next Node. Do the same procedure until the carry is there.
reverse the string back as in original form and then returned the head to get the string printed.
#include <iostream>
using namespace std;
//n=next node ; d=data ; p= previous node; h=head node; c=current node
class Node {
   public:
      int d;
      Node* n;
};
Node *newNode(int d) {
   Node *new_node = new Node;
   new_node->d = d;
   new_node->n = NULL;
   return new_node;
}
Node *reverse(Node *h) {
   Node * p = NULL;
   Node * c = h;
   Node * n;
   while (c != NULL) {
      n = c->n;
      c->n = p;
      p = c;
      c = n;
   }
   return p;
}
Node *addOneUtil(Node *h) {
   Node* res = h;
   Node *temp, *p = NULL;
   int carry = 1, sum;
   while (h != NULL) {
      sum = carry + h->d;
      carry = (sum >= 10)? 1 : 0;
      sum = sum % 10;
      h->d = sum;
      temp = h;
      h = h->n;
   }
   if (carry > 0)
      temp->n = newNode(carry);
   return res;
}
Node* addOne(Node *h) {
   h = reverse(h);
   h = addOneUtil(h);
   return reverse(h);
}
int main() {
   Node *h = newNode(1);
   h->n = newNode(9);
   h->n->n = newNode(9);
   h->n->n->n = newNode(9);
   h = addOne(h);
   while (h != NULL) {
      cout << h->d;
      h = h->n;
   }
   cout<<endl;
   return 0;
}
Plotting A Square Wave Using Matplotlib, Numpy And Scipy

20 Apr, 2022
Prerequisites: linspace, Mathplotlib, Scipy
A square wave is a non-sinusoidal periodic waveform in which the amplitude alternates at a steady frequency between the fixed minimum and maximum values, with the same duration at minimum and maximum. Graphical representations are always easy to understand and are adopted and preferable before any written or verbal communication. In this article, we will try to understand, How can we plot Square waves using the Scipy python module.
Approach:
Import required module.
Create a sample rate.
Plot a square wave.
Label the graph.
Display Graph.
Step 1: Import module
Python3
from scipy import signalimport matplotlib.pyplot as plotimport numpy as np
  
Step 2: The NumPy linspace function is a tool in Python for creating numeric sequences that return evenly spaced numbers over a specified interval.
 
Python3
t = np.linspace(0, 1, 1000, endpoint = True)
Step 3: plot.plot function: This method accepts the following parameters and Plot the square wave signal.
Syntax:
scipy.signal.square(t)
Parameter:
t: The input time array.
Return:
Output array containing the square waveform.
Python3
# Plot the square waveplot.plot(t, signal.square(2 * np.pi * 5 * t))
  
Step 4: Give title name, x-axis label name, y-axis label name. 
 
Python3
# Give x,y, title axis labelplot.xlabel('Time')plot.ylabel('Amplitude')plot.title('Square wave - Geeksforgeeks')
  
Step 5: plot.axhline() : The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis.
 
Python3
# Provide x axis and black line colorplot.axhline(y=0, color='k')
  
Below is the full implementation:
 
Python3
from scipy import signalimport matplotlib.pyplot as plotimport numpy as np t = np.linspace(0, 1, 1000, endpoint=True)     # Plot the square waveplot.plot(t, signal.square(2 * np.pi * 5 * t)) # Give x,y,title axis labelplot.xlabel('Time')plot.ylabel('Amplitude')plot.title('Square wave - Geeksforgeeks') plot.axhline(y = 0, color = 'k') # Displayplot.show()
  
Output:
 
 
sooda367
rkbhola5
Data Visualization
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js req.get() Function

09 Jul, 2020
The req.get() function returns the specified HTTP request header field which is case-insensitive match and the Referrer and Referrer fields are interchangeable.
Syntax:
req.get( field )
Parameter: The field parameter specifies the HTTP request header field.
Return Value: String.
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing the express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
var express = require('express');var app = express();var PORT = 3000;    app.get('/', function (req, res) {    console.log(req.get('Content-Type'));     res.end();});  app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000
Now make a GET request to http://localhost:3000/ with header set to ‘content-type: text/plain’, then you will see the following output on your console:Server listening on PORT 3000
text/plain

The project structure will look like this:
Make sure you have installed express module using the following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000

node index.js
Output:
Server listening on PORT 3000

Now make a GET request to http://localhost:3000/ with header set to ‘content-type: text/plain’, then you will see the following output on your console:Server listening on PORT 3000
text/plain

Server listening on PORT 3000
text/plain

Example 2: Filename: index.js
var express = require('express');var app = express();var PORT = 3000;    app.get('/', function (req, res) {    console.log(req.get('Anything-else'));     res.end();});  app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Now make a GET request to http://localhost:3000/, then you will see the following output on your console:
Server listening on PORT 3000
undefined

Reference: https://expressjs.com/en/4x/api.html#req.get
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
OpenCV | Saving an Image

26 Aug, 2019
This article aims to learn how to save an image from one location to any other desired location on your system in CPP using OpenCv. Using OpenCV, we can generate a blank image with any colour one wishes to.
So, let us dig deep into it and understand the concept with the complete explanation.
// c++ code explaining how to// save an image to a defined// location in OpenCV  // loading library files#include <highlevelmonitorconfigurationapi.h>#include <opencv2\highgui\highgui.hpp>#include <opencv2\opencv.hpp>  using namespace cv;using namespace std;  int main(int argc, char** argv){      // Reading the image file from a given location in system    Mat img = imread("..path\\abcd.jpg");      // if there is no image    // or in case of error    if (img.empty()) {        cout << "Can not open or image is not present" << endl;          // wait for any key to be pressed        cin.get();        return -1;    }      // You can make any changes    // like blurring, transformation      // writing the image to a defined location as JPEG    bool check = imwrite("..path\\MyImage.jpg", img);      // if the image is not saved    if (check == false) {        cout << "Mission - Saving the image, FAILED" << endl;          // wait for any key to be pressed        cin.get();        return -1;    }      cout << "Successfully saved the image. " << endl;      // Naming the window    String geek_window = "MY SAVED IMAGE";      // Creating a window    namedWindow(geek_window);      // Showing the image in the defined window    imshow(geek_window, img);      // waiting for any key to be pressed    waitKey(0);      // destroying the creating window    destroyWindow(geek_window);      return 0;}
Input :Output :
// Reading the image file from a given location in systemMat img = imread("..path\\abcd.jpg");  // if there is no image// or in case of errorif (img.empty()) {    cout << "Can not open or image is not present" << endl;      // wait for any key to be pressed    cin.get();    return -1;}
This part of the code reads the image from the path we have given to it. And it takes care of any error (if occurs). If there is no image present at this path, then “Can not open or image is not present” message will display and at the press of any key, the window will exit.
// writing the image to a defined location as JPEGbool check = imwrite("..path\\MyImage.jpg", img);  // if the image is not savedif (check == false) {    cout << "Mission - Saving the image, FAILED" << endl;      // wait for any key to be pressed    cin.get();    return -1;}  cout << "Successfully saved the image. " << endl;
This part of the code write the image to the defined path and if not successful, it will generate “Mission – Saving the image, FAILED” message and at the press of any key, the window will exit. And rest of the code will create the window and display the image in it. It will keep on displaying the image in the window until the key is pressed. Finally, the window will be destroyed.
OpenCV
Advanced Computer Subject
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to print the octal value of the numbers from 1 to N

24 Jan, 2021
Given a number N, the task is to write a Python program to print the octal value of the numbers from 1 to N.
Examples:
Input: 3
Output: 1
        2
        3
        
Input: 11
Output: 1
        2
        3
        4
        5
        6
        7
        10
        11
        12
        13
Approach:
We will take the value of N as input.
Then, we will run the for loop from 1 to N+1 and traverse each “i” through oct() function.
Print each octal value.
Note: The oct() function is one of the built-in methods in Python3. The oct() method takes an integer and returns its octal representation in a string format. 
Below are the implementations based on the above approach:
Python3
# Python program to print the octal value of the# numbers from 1 to N  # Function to find the octal value of the numbers# in the range 1 to Ndef octal_in_range(n):      # For loop traversing from 1 to N (Both Inclusive)    for i in range(1, n+1):          # Printing octal value of i        print(oct(i)[2:])    # Calling the function with input 3print("Input: 3")octal_in_range(3)  # Calling the function with input 11print("Input: 11")octal_in_range(11)
Output:
Input: 3
1
2
3
Input: 11
1
2
3
4
5
6
7
10
11
12
13
Python-Built-in-functions
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib - Formatting Axes

Sometimes, one or a few points are much larger than the bulk of data. In such a case, the scale of an axis needs to be set as logarithmic rather than the normal scale. This is the Logarithmic scale. In Matplotlib, it is possible by setting xscale or vscale property of axes object to ‘log’.
It is also required sometimes to show some additional distance between axis numbers and axis label. The labelpad property of either axis (x or y or both) can be set to the desired value.
Both the above features are demonstrated with the help of the following example. The subplot on the right has a logarithmic scale and one on left has its x axis having label at more distance.
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1, 2, figsize=(10,4))
x = np.arange(1,5)
axes[0].plot( x, np.exp(x))
axes[0].plot(x,x**2)
axes[0].set_title("Normal scale")
axes[1].plot (x, np.exp(x))
axes[1].plot(x, x**2)
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale (y)")
axes[0].set_xlabel("x axis")
axes[0].set_ylabel("y axis")
axes[0].xaxis.labelpad = 10
axes[1].set_xlabel("x axis")
axes[1].set_ylabel("y axis")
plt.show()
Axis spines are the lines connecting axis tick marks demarcating boundaries of plot area. The axes object has spines located at top, bottom, left and right.
Each spine can be formatted by specifying color and width. Any edge can be made invisible if its color is set to none.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.spines['bottom'].set_color('blue')
ax.spines['left'].set_color('red')
ax.spines['left'].set_linewidth(2)
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.plot([1,2,3,4,5])
plt.show()

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to declare an attribute in Python without a value?



In Python, as well as in several other languages, there is a value that means "no value". In Python, that value with no value is None. So the following shows how None is used −
class Student:
   StudentName = None
   RollNumber = None
Those are like instance variables though, and not class variables, so we may as well write −
class Student(object):
    def __init__(self):
        self.StudentName = None
        self.RollNumber = None
We can see how Python assigns the None value implicitly in the code below −
def h():
    pass
k = h() # k now has the value of None
How to make an anchor tag refer to nothing?

To make an anchor tag refer to nothing, use “javascript: void(0)”. The following link does nothing because the expression "0" has no effect in JavaScript. Here the expression "0" is evaluated, but it is not loaded back into the current document.
Live Demo
<html>
   <head>
      <script>
         <!--
            //-->
      </script>
   </head>
   <body>
      <p>Click the following, This won't react at all...</p>
      <a href="javascript:void(0)">Click me!</a>
   </body>
</html>
Program to find century for a year in C++

In this tutorial, we will be discussing a program to find the century for a year.
For this we will be provided with a year. Our task is to find the century in which the given year falls.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void find_century(int year){
   //year values can only be positive
   if (year <= 0)
      cout << "0 and negative is not allow"
         << "for a year";
   else if (year <= 100)
      cout << "1st century\n";
   else if (year % 100 == 0)
      cout << year/ 100 <<" century";
   else
      cout << year/ 100 + 1 << " century";
}
int main(){
   int year = 2001;
   find_century(year);
   return 0;
}
21 century
Java Program to take Screenshots - GeeksforGeeks

18 Jan, 2018
In this program we will see how we can take screenshots using a java program and save the screenshot in desired folder.We use java.awt.Robot class to capture pixels of screen. It provides method like createScreenCapture which captures the current screen. This method returns captured image as BufferedImage object which can be saved as a file. It also uses ImageIO to save it as PNG image format. Toolkit.getDefaultToolkit().getSize() method is used to get the size of screen.The serialVersionUID is universal version identifier for Serializable class. Thread is used so that after executing the program we can switch to the screen we want to take screenshot of. 120s is the time in seconds i.e. 2 mins.
NOTE : Please keep note of UpperCase and LowerCase in name of methods. A slight change of Case may cause errors.
How to use the program to capture Screenshot :
Write program in Notepad.
Save it as Screenshot.java and run it on CommandPrompt.
Refer to the screenshots at end in case of any problem.
// Java Program to Capture full// Image of Screenimport java.awt.AWTException;import java.awt.Rectangle;import java.awt.Toolkit;import java.awt.Robot;import java.awt.image.BufferedImage;import java.io.IOException;import java.io.File;import javax.imageio.ImageIO;  public class Screenshot {    public static final long serialVersionUID = 1L;    public static void main(String[] args)    {        try {            Thread.sleep(120);            Robot r = new Robot();              // It saves screenshot to desired path            String path = "D:// Shot.jpg";              // Used to get ScreenSize and capture image            Rectangle capture =             new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());            BufferedImage Image = r.createScreenCapture(capture);            ImageIO.write(Image, "jpg", new File(path));            System.out.println("Screenshot saved");        }        catch (AWTException | IOException | InterruptedException ex) {            System.out.println(ex);        }    }}
Output :
References:http://viralpatel.net/blogs/how-to-take-screen-shots-in-java-taking-screenshots-java/http://www.javatechblog.com/java/how-to-take-screenshot-programmatically-in-java/
GBlog
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Types of Software Testing
12 pip Commands For Python Developers
Working with csv files in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
Java Examples - Collection Comparison

How to compare elements in a collection ?
Following example compares the element of a collection by converting a string into a treeset using Collection.min() and Collection.max() methods of Collection class.
import java.util.Collections; 
import java.util.Set;
import java.util.TreeSet;

public class MainClass {
   public static void main(String[] args) {
      String[] coins = { "Penny", "nickel", "dime", "Quarter", "dollar" };
      Set set = new TreeSet();
      
      for (int i = 0; i < coins.length; i++)set.add(coins[i]);
      System.out.println(Collections.min(set));
      System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
      
      for(int i = 0; i <= 10; i++)System.out.print('-');
      System.out.println(Collections.max(set));
      System.out.println(Collections.max(set, 
      String.CASE_INSENSITIVE_ORDER));
   }
}
The above code sample will produce the following result.
Penny
dime
----------
nickle
Quarter

 Print
 Add Notes
 Bookmark this page
C++ basic_streambuf Library - pbase

It is used in pointer to beginning of output sequence and returns a pointer to the first element of the array with the portion of the controlled output sequence that is currently buffered.
Following is the declaration for std::basic_streambuf::pbase.
char_type* pbase() const;
none
It returns a pointer to the beginning of an array with the part of the controlled output sequence that is currently buffered.
Strong guarantee − if an exception is thrown, there are no changes in the stream buffer.
It accesses the stream buffer object.
 Print
 Add Notes
 Bookmark this page
How can we Implement a Stack using Queue in Java?

A Stack is a subclass of Vector class and it represents last-in-first-out (LIFO) stack of objects. The last element added at the top of the stack (In) can be the first element to be removed (Out) from the stack.
A Queue class extends Collection interface and it supports the insert and removes operations using a first-in-first-out (FIFO). We can also implement a Stack using Queue in the below program.
import java.util.*;
public class StackFromQueueTest {
   Queue queue = new LinkedList();
   public void push(int value) {
      int queueSize = queue.size();
      queue.add(value);
      for (int i = 0; i < queueSize; i++) {
         queue.add(queue.remove());
      }
   }
   public void pop() {
      System.out.println("An element removed from a stack is: " + queue.remove());
   }
   public static void main(String[] args) {
      StackFromQueueTest test = new StackFromQueueTest();
      test.push(10);
      test.push(20);
      test.push(30);
      test.push(40);
      System.out.println(test.queue);
      test.pop();
      System.out.println(test.queue);
   }
}
[40, 30, 20, 10]
An element removed from a stack is: 40
[30, 20, 10]
TIKA - Extracting MS-Office Files

Given below is the program to extract content and metadata from a Microsoft Office Document.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.microsoft.ooxml.OOXMLParser;
import org.apache.tika.sax.BodyContentHandler;

import org.xml.sax.SAXException;

public class MSExcelParse {

   public static void main(final String[] args) throws IOException, TikaException {
      
      //detecting the file type
      BodyContentHandler handler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      FileInputStream inputstream = new FileInputStream(new File("example_msExcel.xlsx"));
      ParseContext pcontext = new ParseContext();
      
      //OOXml parser
      OOXMLParser  msofficeparser = new OOXMLParser (); 
      msofficeparser.parse(inputstream, handler, metadata,pcontext);
      System.out.println("Contents of the document:" + handler.toString());
      System.out.println("Metadata of the document:");
      String[] metadataNames = metadata.names();
      
      for(String name : metadataNames) {
         System.out.println(name + ": " + metadata.get(name));
      }
   }
}
Save the above code as MSExelParse.java, and compile it from the command prompt by using the following commands −
javac MSExcelParse.java
java MSExcelParse 

Here we are passing the following sample Excel file.
The given Excel file has the following properties −
After executing the above program you will get the following output.
Output −
Contents of the document:

Sheet1
Name	Age	Designation		Salary
Ramu	50	Manager			50,000
Raheem	40	Assistant manager	40,000
Robert	30	Superviser		30,000
sita	25	Clerk			25,000
sameer	25	Section in-charge	20,000

Metadata of the document:

meta:creation-date:    2006-09-16T00:00:00Z
dcterms:modified:    2014-09-28T15:18:41Z
meta:save-date:    2014-09-28T15:18:41Z
Application-Name:    Microsoft Excel
extended-properties:Company:    
dcterms:created:    2006-09-16T00:00:00Z
Last-Modified:    2014-09-28T15:18:41Z
Application-Version:    15.0300
date:    2014-09-28T15:18:41Z
publisher:    
modified:    2014-09-28T15:18:41Z
Creation-Date:    2006-09-16T00:00:00Z
extended-properties:AppVersion:    15.0300
protected:    false
dc:publisher:    
extended-properties:Application:    Microsoft Excel
Content-Type:    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Last-Save-Date:    2014-09-28T15:18:41Z

 Print
 Add Notes
 Bookmark this page
Node.js crypto.pbkdf2() Method

11 Oct, 2021
The crypto.pbkdf2() method gives an asynchronous Password-Based Key Derivation Function 2 i.e. (PBKDF2) implementation. Moreover, a particular HMAC digest algorithm which is defined by digest is implemented to derive a key of the required byte length (keylen) from the stated password, salt, and iterations.
Syntax:
crypto.pbkdf2( password, salt, iterations, keylen, digest, callback )
Parameters: This method accepts six parameters as mentioned above and described below:
password: It can holds string, Buffer, TypedArray, or DataView type of data.
salt: It must be as unique as possible. However, it is recommended that a salt is arbitrary and in any case it is at least 16 bytes long. It is of type string, Buffer, TypedArray, or DataView.
iterations: It must be a number and should be set as high as possible. So, the more is the number of iterations, the more secure the derived key will be, but in that case it takes greater amount of time to complete. It is of type number.
keylen: It is the key of the required byte length and it is of type number.
digest: It is digest algorithms of string type.
callback: It is a function with two parameters namely err, and derivedKey.
Return Type: It returns the derived password based key.
Below example illustrate the use of crypto.pbkdf2() method in Node.js:
Example 1:
// Node.js program to demonstrate the // crypto.pbkdf2() method  // Including crypto moduleconst crypto = require('crypto');  // Implementing pbkdf2 with all its parameterscrypto.pbkdf2('secret', 'salt', 100000, 64,         'sha512', (err, derivedKey) => {    if (err) throw err;    // Prints derivedKey  console.log(derivedKey.toString('hex'));});
Output:
3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e
47471cc47ed941c7ad618e827304f083f8707f12b7cfdd5f489b782
f10cc269e3c08d59ae

Example 2:
// Node.js program to demonstrate the // crypto.pbkdf2() method  // Including crypto moduleconst crypto = require('crypto');  // Implementing pbkdf2 with all its parameters// but digest is nullcrypto.pbkdf2('secret', 'salt', 677, 6,          null, (err, derivedKey) => {    if (err)   {    console.log(err);  }   else  {    // Prints derivedKey without encoding  console.log(derivedKey);           }});    
Output: Here, a buffer is returned as a derived key is not changed to string.
Buffer 71 1e 7b 7b 9b 53
Reference: https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback
Node.js-crypto-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
How to update NPM ?
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Roadmap to Learn JavaScript For Beginners
Oracle Interview Experience | Applications Engineer

17 Jun, 2020
  
Round 1: 
1) Tell me about yourself 
2) Problem Statement:  
Reverse the words in below string considering all negative test cases 
Input: Hello World 
Output: olleH dlroW  
If the input have more than 1 space as separator then output should contain as much space as input
If the statement have start and trailing spaces then output will also contain those spaces
Input is case sensitive
3) Sql queries  
There are 2 tables: Employee and Department.
Print the employee name with department name
Print the count of employees having same department with department name
Print the count of employees having the same department
  
Round 2: 
1) Problem Statement: 
Check if the given string is palindrome or not. If the string is not palindrome then try to make it palindrome if possible 
2) SQL queries:  
There are 2 tables: Employee and Salary
Print only female employees
Print the female employee who has highest salary
  
Round 3: 
1) Core java related questions  
What is method overloading and overriding with example
How we can achieve inheritance in java
What is default methods in java8 and when should we use it
2) Problem Statement  
geeksforgeeks.org/min-cost-path-dp-6/
3) Glass Puzzle  
My friend was throwing a very grand party and wanted to borrow from me 100 wine glasses. I decided to send them through my boy servant.
Just to give an incentive to Servant to deliver the glasses intact I offered him 3 paise for every glass delivered safely and threatened to forfeit 9 paise for every glass he broke.
On settlement Harish received Rs 2.40 from me. How many glasses did Harish safely deliver?
  
Round 4: 
1) Puzzle:  
Using only 1 to 9 numbers, Arrange the numbers such that
AxBxC = BxGxE = DxExF
A     D 
B  G  E
C     F
Each character should assign distinct numbers
2) Puzzle: 
Using 1 to 16 numbers, sum would be 34 for each column, rows and for both diagonals. Write the program as well to solve the puzzle:
Round 5: 
1) Problem Statement: Merge the sub arrays if possible. Input: List of sub arrays: [1, 10], [11, 15], [13, 25], [30, 40], [40, 50]Output: [1, 25], [30, 50]
2) Puzzle:
There are 101 coins.
1 coin is a faulty coin.
A Faulty coin has different weight other than 100 coins. 
With a minimum number of comparisons, find that if the faulty coin has higher weight or lower weight than other coins.
Thanks, GeeksforGeeks. It helped me a lot in preparation.
Marketing
Oracle
Interview Experiences
Oracle
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas.to_datetime()

17 Sep, 2018
When a csv file is imported and a Data Frame is made, the Date time objects in the file are read as a string object rather a Date Time object and Hence it’s very tough to perform operations like Time difference on a string rather a Date Time object. Pandas to_datetime() method helps to convert string Date time into Python Date time object.
Syntax:
pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin=’unix’, cache=False)
 Parameters:
arg: An integer, string, float, list or dict object to convert in to Date time object.dayfirst: Boolean value, places day first if True.yearfirst: Boolean value, places year first if True.utc: Boolean value, Returns time in UTC if True.format: String input to tell position of day, month and year.
Return type: Date time object series.
For link of the CSV file used, click here.
Example #1: String to DateIn the following example, a csv file is read and the date column of Data frame is converted into Date Time object from a string object.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("todatetime.csv")  # overwriting data after changing formatdata["Date"]= pd.to_datetime(data["Date"])  # info of datadata.info()  # displaydata
Output:As shown in the image, the Data Type of Date column was object but after using to_datetime(), it got converted into a date time object.
Before operation-
After Operation- Example #2: Exception while converting TimeTime object can also be converted with this method. But since in the Time column, a date isn’t specified and hence Pandas will put Today’s date automatically in that case.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("todatetime.csv")  # overwriting data after changing formatdata["Time"]= pd.to_datetime(data["Time"])  # info of datadata.info()  # displaydata
Output:As shown in the output, a date (2018-07-07) that is Today’s date is already added with the Date time object.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Unpacking tuple of lists

04 Apr, 2019
Given a tuple of lists, write a Python program to unpack the elements of the lists that are packed inside the given tuple.
Examples:
Input : (['a', 'apple'], ['b', 'ball'])
Output : ['a', 'apple', 'b', 'ball']

Input : ([1, 'sam', 75], [2, 'bob', 39], [3, 'Kate', 87])
Output : [1, 'sam', 75, 2, 'bob', 39, 3, 'Kate', 87]

 Approach #1 : Using reduce()
reduce() is a classic list operation used to apply a particular function passed in its argument to all of the list elements. In this case we used add function of operator module which simply adds the given list arguments to an empty list.
# Python3 program to unpack # tuple of listsfrom functools import reduceimport operator  def unpackTuple(tup):          return (reduce(operator.add, tup))  # Driver codetup = (['a', 'apple'], ['b', 'ball'])print(unpackTuple(tup))
['a', 'apple', 'b', 'ball']

 
Approach #2 : Using Numpy [Alternative to Approach #1]
# Python3 program to unpack # tuple of listsfrom functools import reduceimport numpy   def unpackTuple(tup):           print (reduce(numpy.append, tup))      # Driver codetup = (['a', 'apple'], ['b', 'ball'])unpackTuple(tup)
['a' 'apple' 'b' 'ball']

 Approach #3 : Using itertools.chain(*iterables)
itertools.chain(*iterables) make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. This makes our job a lot easier, as we can simply append each iterable to the empty list and return it.
# Python3 program to unpack # tuple of listsfrom itertools import chain  def unpackTuple(tup):    res = []    for i in chain(*tup):        res.append(i)              print(res)      # Driver codetup = (['a', 'apple'], ['b', 'ball'])unpackTuple(tup)
['a', 'apple', 'b', 'ball']

Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is TEXT data type in MySQL?

TEXT data objects are useful for storing long-form text strings in a MySQL database. Followings are some point about TEXT data type −
TEXT is the family of column type intended as high-capacity character storage.
The actual TEXT column type is of four types-TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT.
The four TEXT types are very similar to each other; the only difference is the maximum amount of data each can store.
The smallest TEXT type, TINYTEXT shares the same character length as VARCHAR.
TEXT values are treated as character strings.
TEXT has character set other than binary character set and collation.
The comparisons and sorting are based on the collation of its character set.
Truncation of excess trailing spaces from values to be inserted into TEXT columns always generates a warning, regardless of the SQL mode.
A TEXT family column is just like a VARCHAR.
TEXT column cannot have DEFAULT value.
 Following example shows how to declare a column as TEXT.
mysql> Create table magzine(id INT, title Varchar(25), Introduction TEXT);
Query OK, 0 rows affected (0.16 sec)

mysql> Describe magzine;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| id           | int(11)     | YES  |     | NULL    |       |
| title        | varchar(25) | YES  |     | NULL    |       |
| Introduction | text        | YES  |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
3 rows in set (0.11 sec)
How String Hashcode value is calculated? - GeeksforGeeks

01 Apr, 2020
The String hashCode() method returns the hashcode value of this String as an Integer.
Syntax:public int hashCode()
For Example:
import java.io.*;  class GFG {    public static void main(String[] args)    {        String str = "GFG";        System.out.println(str);          int hashCode = str.hashCode();        System.out.println(hashCode);    }}
GFG
70472

But the question here is, how this integer value 70472 is printed. If you will try to find the hashcode value of this string again, the result would be the same. So how is this String hashcode calculated?
How is String hashcode calculated?The hashcode value of a String is calculated with the help of a formula:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

where:
s[i] represents the ith character of the string
^ refers to the exponential operand
n represents the length of the string
Example:
In the above case, the String is “GFG”. Hence:
s[] = {'G', 'F', 'G'}
n = 3

So the hashcode value will be calculated as:
s[0]*31^(2) + s[1]*31^1 + s[2]
= G*31^2 + F*31 + G
= (as ASCII value of G = 71 and F = 70)
  71*312 + 70*31 + 71 
= 68231 + 2170 + 71
= 70472
which is the value received as the output.
Hence this is how the String hashcode value is calculated.
HashCode value of empty string?
In this case, the String is “”. Hence:
s[] = {}
n = 0

So the hashcode value will be calculated as:
s[0]*31^(0)
= 0

Hence the hashcode value of an empty string is always 0.
pavanhareesh97
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
Singleton Class in Java
LinkedList in Java
Multithreading in Java
Inheritance in Java
Python 3 - Comparison Operators Example

These operators compare the values on either side of them and decide the relation among them. They are also called Relational operators.
Assume variable a holds the value 10 and variable b holds the value 20, then −
Assume variable a holds the value 10 and variable b holds the value 20, then −
#!/usr/bin/python3

a = 21
b = 10

if ( a == b ):
   print ("Line 1 - a is equal to b")
else:
   print ("Line 1 - a is not equal to b")

if ( a != b ):
   print ("Line 2 - a is not equal to b")
else:
   print ("Line 2 - a is equal to b")

if ( a < b ):
   print ("Line 3 - a is less than b" )
else:
   print ("Line 3 - a is not less than b")

if ( a > b ):
   print ("Line 4 - a is greater than b")
else:
   print ("Line 4 - a is not greater than b")

a,b = b,a #values of a and b swapped. a becomes 10, b becomes 21

if ( a <= b ):
   print ("Line 5 - a is either less than or equal to  b")
else:
   print ("Line 5 - a is neither less than nor equal to  b")

if ( b >= a ):
   print ("Line 6 - b is either greater than  or equal to b")
else:
   print ("Line 6 - b is neither greater than  nor equal to b")
When you execute the above program, it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not less than b
Line 4 - a is greater than b
Line 5 - a is either less than or equal to  b
Line 6 - b is either greater than  or equal to b


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page