code-rag-bench/online-tutorials huggingface dataset:
BigDecimal round() Method in Java - GeeksforGeeks

04 Dec, 2018
The java.math.BigDecimal.round(MathContext m) is an inbuilt method in Java that returns a BigDecimal value rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place.
Syntax:
public BigDecimal round(MathContext m)

Parameters: The method accepts a single parameter m which refers to the context to use that is the value up to which the BigDecimal value is to be rounded off.
Return value: This method returns a BigDecimal rounded according to the MathContext settings.
Below programs illustrate the working of java.math.BigDecimal.round(MathContext m) method:Program 1:
// Java program to demonstrate the// round() methodimport java.math.*;  public class Gfg {      public static void main(String[] args)    {        // Assign value to BigDecimal object b1        BigDecimal b1 = new BigDecimal("4.2585");          MathContext m = new MathContext(4); // 4 precision          // b1 is rounded using m        BigDecimal b2 = b1.round(m);          // Print b2 value        System.out.println("The value of " + b1 +         " after rounding is " + b2);    }}
The value of 4.2585 after rounding is 4.259

Program 2:
// Java program to demonstrate the// round() methodimport java.math.*;  public class gfg {      public static void main(String[] args)    {        // Assigning value to BigDecimal object b1        BigDecimal b1 = new BigDecimal("-4.2585");          MathContext m = new MathContext(4); // 4 precision          // b1 is rounded using m        BigDecimal b2 = b1.round(m);          // Print b2 value        System.out.println("The value of " + b1 +         " after rounding is " + b2);    }}
The value of -4.2585 after rounding is -4.259

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#round(java.math.MathContext)
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
Singleton Class in Java
Set in Java
LinkedList in Java
Overriding in Java
Queue Interface In Java
Collections in Java
Initializing a List in Java
Multithreading in Java
How can multiple lines be visualized using Bokeh Python?

Bokeh is a Python package that helps in data visualization. It is an open source project. Bokeh renders its plot using HTML and JavaScript. This indicates that it is useful while working with web-based dashboards.
Bokeh converts the data source into a JSON file. This file is used as an input to BokehJS, which is a JavaScript library. This BokehJS is written in TypeScript that helps render visualization on modern browsers.
Matplotlib and Seaborn produce static plots, whereas Bokeh produces interactive plots. This means when the user interacts with these plots, they change accordingly.
Plots can be embedded as output of Flask or Django enabled web applications. Jupyter notebook can also be used to render these plots.
Dependencies of Bokeh −
Numpy
Pillow
Jinja2
Packaging
Pyyaml
Six
Tornado
Python−dateutil
Installation of Bokeh on Windows command prompt
pip3 install bokeh
Installation of Bokeh on Anaconda prompt
conda install bokeh
Let us see an example −
from bokeh.plotting import figure, output_file, show
output_file("patchplot.html")
p = figure(plot_width=500, plot_height=300)

p.multi_line([[1, 2, 2], [3, 2, 5, 8]], [[2, 3, 7], [4, 8, 9, 0]],
   color=["firebrick", "cyan"], alpha=[0.9, 0.3], line_width=4)

show(p)
The required packages are imported, and aliased.
The required packages are imported, and aliased.
The figure function is called along with plot width and height.
The figure function is called along with plot width and height.
The ‘output_file’ function is called to mention the name of the html file that will be generated.
The ‘output_file’ function is called to mention the name of the html file that will be generated.
The ‘multi_line’ function present in Bokeh is called, along with data.
The ‘multi_line’ function present in Bokeh is called, along with data.
The ‘show’ function is used to display the plot.
The ‘show’ function is used to display the plot.
How can we implement editable JComboBox in Java?

A JComboBox can extend JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value.
If the text field portion of the control is editable, the user can enter a value in the field or edit a value retrieved from the drop-down list.
By default, the user not allowed to edit the data in the text field portion of the JComboBox. If we want to allow the user to edit the text field, call setEditable(true) method.
A JComboBox can generate an ActionListener, ChangeListener or ItemListener when the user actions on a combo box.
A getSelectedItem() method can be used to get the selected or entered item from a JComboBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JEditableComboBoxTest extends JFrame {
   public JEditableComboBoxTest() {
      setTitle("JEditableComboBox Test");
      setLayout(new BorderLayout());
      final JComboBox combobox = new JComboBox();
      final JList list = new JList(new DefaultListModel());
      add(BorderLayout.NORTH, combobox);
      add(BorderLayout.CENTER, list);
      combobox.setEditable(true);
      combobox.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent ie) {
            if (ie.getStateChange() == ItemEvent.SELECTED) {
               ((DefaultListModel) list.getModel()).addElement(combobox.getSelectedItem());
               combobox.insertItemAt(combobox.getSelectedItem(), 0);
            }
         }
      });
      setSize(new Dimension(375, 250));
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) throws Exception {
      new JEditableComboBoxTest();
   }
}
Difference between :first-child and :first-of-type selector in CSS - GeeksforGeeks

27 Oct, 2021
Both of them are selectors for the HTML used in the CSS to select specific children. The :first-child: The :first-child selector is used to select those elements which are the first-child elements. For :first-child selector the <!DOCTYPE> must be declared for IE8 and earlier versions.The :first-of-type: The :first-of-type Selector is used to targeting the first child of every element of it’s parent. if we want to style the first child of an element without giving a class, we can use it.Example:  
html
<!DOCTYPE html><html> <head>    <title>:first-child and first-of-type selector</title>    <style>        h1 {            color: green;        }                 h1,        h2 {            text-align: center;        }                 p:first-child {            background: red;        }                 h4:first-of-type {            background: green;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h2>This is :first-child and first-of-type selector</h2>    <div>          <p>I am the First Child</p>          <h4>I am the first of type Child</h4>        <h4>I am the third Child</h4>          <p>I am the fourth Child</p>      </div> </body> </html>
Output: 
Difference between :first-child and :first-of-type selector: 
arorakashish0911
sagar0719kumar
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
PyQt5 - Hello World

Creating a simple GUI application using PyQt involves the following steps −
Import QtCore, QtGui and QtWidgets modules from PyQt5 package.
Import QtCore, QtGui and QtWidgets modules from PyQt5 package.
Create an application object of QApplication class.
Create an application object of QApplication class.
A QWidget object creates top level window. Add QLabel object in it.
A QWidget object creates top level window. Add QLabel object in it.
Set the caption of label as "hello world".
Set the caption of label as "hello world".
Define the size and position of window by setGeometry() method.
Define the size and position of window by setGeometry() method.
Enter the mainloop of application by app.exec_() method.
Enter the mainloop of application by app.exec_() method.
Following is the code to execute Hello World program in PyQt −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QLabel(w)
   b.setText("Hello World!")
   w.setGeometry(100,100,200,50)
   b.move(50,20)
   w.setWindowTitle("PyQt5")
   w.show()
   sys.exit(app.exec_())
if __name__ == '__main__':
   window()
The above code produces the following output −
It is also possible to develop an object oriented solution of the above code.
Import QtCore, QtGui and QtWidgets modules from PyQt5 package.
Import QtCore, QtGui and QtWidgets modules from PyQt5 package.
Create an application object of QApplication class.
Create an application object of QApplication class.
Declare window class based on QWidget class
Declare window class based on QWidget class
Add a QLabel object and set the caption of label as "hello world".
Add a QLabel object and set the caption of label as "hello world".
Define the size and position of window by setGeometry() method.
Define the size and position of window by setGeometry() method.
Enter the mainloop of application by app.exec_() method.
Enter the mainloop of application by app.exec_() method.
Following is the complete code of the object oriented solution −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class window(QWidget):
   def __init__(self, parent = None):
      super(window, self).__init__(parent)
      self.resize(200,50)
      self.setWindowTitle("PyQt5")
      self.label = QLabel(self)
      self.label.setText("Hello World")
      font = QFont()
      font.setFamily("Arial")
      font.setPointSize(16)
      self.label.setFont(font)
      self.label.move(50,20)
def main():
   app = QApplication(sys.argv)
   ex = window()
   ex.show()
   sys.exit(app.exec_())
if __name__ == '__main__':
   main()

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Program to make a copy of a n-ary tree in Python

Suppose, we have been provided a n-ary tree whose root is given to us 'root'. We have to make a copy of the full n-ary binary tree and perform a preorder traversal of both trees. The copied tree has to be stored using another root node. The node structure of the tree is given below −
Node:
   value : <integer>
   children : <array>
So, if the input is like
, then the output will be
[14, 27, 32, 42, 56, 65]
The preorder representation of the input tree and the output tree will be the same as an exact copy of the tree has been created.
To solve this, we will follow these steps −
if root is not empty, thenreturn root
if root is not empty, then
return root
return root
head := a new node with the value of root
head := a new node with the value of root
q := a new deque containing elements root and head
q := a new deque containing elements root and head
while q is not empty, donode := pop the first element from the qcloned := pop the first element from the qfor each chld in node.children, donew_n := a new node containing the value of chldappend new_n to the children of clonedinsert chld and new_n at the end of q
while q is not empty, do
node := pop the first element from the q
node := pop the first element from the q
cloned := pop the first element from the q
cloned := pop the first element from the q
for each chld in node.children, donew_n := a new node containing the value of chldappend new_n to the children of clonedinsert chld and new_n at the end of q
for each chld in node.children, do
new_n := a new node containing the value of chld
new_n := a new node containing the value of chld
append new_n to the children of cloned
append new_n to the children of cloned
insert chld and new_n at the end of q
insert chld and new_n at the end of q
return head
return head
Let us see the following implementation to get better understanding −
 Live Demo
from queue import deque
class Node:
   def __init__(self, value, child = None) -> None:
      self.val = value
      self.children = []
      if child != None:
         for value in child:
            self.children.append(value)

def solve(root):
   if not root:
      return root
   head = Node(root.val)
   q = deque([(root, head)])
   while q:
      node, cloned = q.popleft()
      for chld in node.children:
         new_n = Node(chld.val)
         cloned.children.append(new_n)
         q.append((chld,new_n))
   return head

def treeprint(node, tree):
   if node == None:
      tree.append("None")
      return tree
   if tree == None:
      tree = []
   tree.append(node.val)
   for child in node.children:
      treeprint(child, tree)
   return tree

node6 = Node(65)
node5 = Node(56)
node4 = Node(42, [node5, node6])
node3 = Node(32)
node2 = Node(27)
node1 = Node(14, [node2, node3, node4])
root = node1

copynode = solve(root)
print(treeprint(copynode, None))
node6 = Node(65)
node5 = Node(56)
node4 = Node(42, [node5, node6])
node3 = Node(32)
node2 = Node(27)
node1 = Node(14, [node2, node3, node4])
root = node1
[14, 27, 32, 42, 56, 65]
Downloading files from web using Python?

Python provides different modules like urllib, requests etc to download files from the web. I am going to use the request library of python to efficiently download files from the URLs.
Let’s start a look at step by step procedure to download files using URLs using request library−
import requests
url = 'https://www.facebook.com/favicon.ico'
r = requests.get(url, allow_redirects=True)
open('facebook.ico', 'wb').write(r.content)
save the file as facebook.ico.
import requests


url = 'https://www.facebook.com/favicon.ico'
r = requests.get(url, allow_redirects=True)

open('facebook.ico', 'wb').write(r.content)
We can see the file is downloaded(icon) in our current working directory.
But we may need to download different kind of files like image, text, video etc from the web. So let’s first get the type of data the url is linking to−
>>> r = requests.get(url, allow_redirects=True)
>>> print(r.headers.get('content-type'))
image/png
However, there is a smarter way, which involved just fetching the headers of a url before actually downloading it. This allows us to skip downloading files which weren’t meant to be downloaded.
>>> print(is_downloadable('https://www.youtube.com/watch?v=xCglV_dqFGI'))
False
>>> print(is_downloadable('https://www.facebook.com/favicon.ico'))
True
To restrict the download by file size, we can get the filezie from the content-length header and then do as per our requirement.
contentLength = header.get('content-length', None)
if contentLength and contentLength > 2e8: # 200 mb approx
return False
To get the filename, we can parse the url. Below is a sample routine which fetches the last string after backslash(/).
url= "http://www.computersolution.tech/wp-content/uploads/2016/05/tutorialspoint-logo.png"
if url.find('/'):
print(url.rsplit('/', 1)[1]
Above will give the filename of the url. However, there are many cases where filename information is not present in the url for example – http://url.com/download. In such a case, we need to get the Content-Disposition header, which contains the filename information.
import requests
import re

def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = re.findall('filename=(.+)', cd)
if len(fname) == 0:
return None
return fname[0]


url = 'http://google.com/favicon.ico'
r = requests.get(url, allow_redirects=True)
filename = getFilename_fromCd(r.headers.get('content-disposition'))
open(filename, 'wb').write(r.content)
The above url-parsing code in conjunction with above program will give you filename from Content-Disposition header most of the time.
C# Program to filter array elements based on a predicate

Set an array.
int[] arr = { 40, 42, 12, 83, 75, 40, 95 };
Use the Where clause and predicate to get elements above 50.
IEnumerable<int> myQuery = arr.AsQueryable() .Where((a, index) => a >= 50);
Let us see the complete code −
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      int[] arr = { 40, 42, 12, 83, 75, 40, 95 };
      Console.WriteLine("Array:");
      foreach (int a in arr) {
         Console.WriteLine(a);
      }
      // getting elements above 70
      IEnumerable<int> myQuery = arr.AsQueryable() .Where((a, index) => a >= 50);
      Console.WriteLine("Elements above 50...:");
      foreach (int res in myQuery) {
         Console.WriteLine(res);
      }
   }
}
Array:
40
42
12
83
75
40
95
Elements above 50...:
83
75
95
How to get Client IP address and MAC address in Laravel ? - GeeksforGeeks

16 Mar, 2021
What is a MAC address?MAC is the abbreviation of “Media Access Control” and it is a 48-bit physical address associated with every networking device. It is printed on the NIC (Network Interface Card) and is globally unique for every networking device. MAC address is used by the data-link layer to route a data packet from source to destination.
How to get the MAC address of the connected client in Laravel?
The ‘exec()’ is a function that is used to run an external program in PHP. It returns the last line from the result of the command. To get the MAC address, pass the parameter ‘getmac’ which returns the MAC address of the client. ‘getmac’ is a CMD command to get the MAC address.
To get the MAC address, we use exec() function.
$macAddr = exec('getmac');
What is an IP address?An Internet Protocol(IP) address also known as a logical address is given by the internet service provider(ISP) which uniquely identifies a system over the network. IP address keeps on changing from time to time.
How to get the IP address of the connected client in Laravel?
For getting the IP address we have to include use Illuminate\Http\Request; in the Controller and then add the code of the below pre tag. It will give the AP address of the network.
$ipAddr=\Request::ip();
Laravel
PHP-Questions
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP Database connection
How to pass a PHP array to a JavaScript function?
String comparison using == vs strcmp() in PHP
How to fetch data from localserver database and display on HTML table using PHP ?
How to call PHP function on the click of a Button ?
String comparison using == vs strcmp() in PHP
How to pass a PHP array to a JavaScript function?
How to encrypt and decrypt passwords using PHP ?
Git New Files

You just created your first local Git repo. But it is empty.
So let's add some files, or create a new file using your favourite text editor. Then save or move it to the folder you just created.
If you want to learn how to create a new file using a text editor, you can visit our HTML tutorial:
HTML Editors
For this example, I am going to use a simple HTML file like this:
And save it to our new folder as index.html.
Let's go back to the terminal and list the files in our current working directory:
ls
index.html
ls will list the files in 
the directory. We can see that index.html is there.
Then we check the Git status and see if it is a part of our repo:
git status
On branch master

No commits yet

Untracked files:
  (use "git add ..." to include in what will be committed)
    index.html

nothing added to commit but untracked files present (use "git add" to track)
Now Git is aware of the file, but has not added 
it to our repository!
Files in your Git repository folder can be in one of 2 states:
Tracked - files that Git knows about and are added to the repository
Untracked - files that are in your working directory, but not added to the 
  repository
 When you first add files to an empty repository, they are all 
untracked. To get Git to track them, you need to stage them, or add them to the 
staging environment.
We will cover the staging environment in the next chapter.
Check the status of the Git:
git 


Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Program to find length of substring with consecutive common characters in Python

Suppose we have a string s, we have to find the length of the longest substring with same
characters.
So, if the input is like "abbbaccabbbba", then the output will be 4, as there are four consecutive
b's.
To solve this, we will follow these steps −
if size of s is 0, thenreturn 0
return 0
s := s concatenate blank space
ct:= 1, tem:= 1
for i in range 0 to size of s -2, doif s[i] is same as s[i+1], thentem := tem + 1otherwise,ct:= maximum of tem and cttem:= 1
if s[i] is same as s[i+1], thentem := tem + 1
tem := tem + 1
otherwise,ct:= maximum of tem and cttem:= 1
ct:= maximum of tem and ct
tem:= 1
return ct
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s):
      if len(s)==0:
         return 0
      s+=' '
      ct=1
      tem=1
      for i in range(len(s)-1):
         if s[i]==s[i+1]:
            tem+=1
         else:
            ct=max(tem,ct)
            tem=1
      return ct
ob = Solution()
print(ob.solve("abbbaccabbbba"))
"abbbaccabbbba"
4
What is the data type of a lambda expression in Java?

The lambda expressions have a very simple, precise syntax and provide flexibility to specify the datatypes for the function parameters. Its return type is a parameter -> expression body to understand the syntax, we can divide it into three parts.
Parameters : These are function method parameters and match with the signature of a function defined in the functional interface. Defining the data-type of parameters is optional but the number of parameters can match with the defined signatures in the interface.
Expression Body : This is either a single statement or collection of statements that represent the function definition. Defining the data-type for return object is optional.
-> : This represents the lambda expression operator.
interface Hello {
   String sayHello(String name);
}
public class LambdaExpressionTest {
   public static void main(String args[]) {
      Hello hello = (message) -> {
         String str1 = "Hello ";
         String str2 = str1 + message;
         return str2;
      };
       System.out.println(hello.sayHello("Tutorials Point"));
   }
}
Hello Tutorials Point
How to eject the USB device from the system using PowerShell?

To eject the USB device from the system, we first need to get the USB device using PowerShell. WMI class Win32_Volume will help us to find the USB device.
We know that all removal devices using the DriveType '2'. So we will filter out the USB device among the listed devices.
PS C:\> $usbdev = gwmi win32_volume | where{$_.DriveType -eq '2'}
The below commands will helpful to unallocated the USB from the system.
PS C:\> $usbdev.DriveLetter = $null
PS C:\> $usbdev.Put()
Path : \\localhost\root\cimv2:Win32_Volume.DeviceID="\\\\?\\Volume{6e4d6f1e-a8c2-11eb-9493-005056c00008}\\"
RelativePath : Win32_Volume.DeviceID="\\\\?\\Volume{6e4d6f1e-a8c2-11eb-9493-005056c00008}\\"
Server : localhost
NamespacePath : root\cimv2
ClassName : Win32_Volume
IsClass : False
IsInstance : True
IsSingleton : False
And the below command will dismount the disk from the system.
PS C:\> $usbdev.Dismount($false,$false) | Out-Null
You can find the method Dismount details for the Removal Disk is as below.
https://docs.microsoft.com/
Importance of @Override annotation in Java?

The @Override annotation is one of a default Java annotation and it can be introduced in Java 1.5 Version. The @Override annotation indicates that the child class method is over-writing its base class method.
The @Override annotation can be useful for two reasons
It extracts a warning from the compiler if the annotated method doesn't actually override anything.
It can improve the readability of the source code.
public @interface Override
class BaseClass {
   public void display() {
      System.out.println("In the base class,test() method");
   }
}
class ChildClass extends BaseClass {
   @Override 
   public void display() {
      System.out.println("In the child class, test() method");
   }
}
// main class
public class OverrideAnnotationTest {
   public static void main(String args[]) {
      System.out.println("@Override Example");
      BaseClass test = new ChildClass();
      test.display();
   }
}
@Override Example
In the child class, test() method
C - memcmp function

C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <stdio.h>

int memcmp(const void* cs, const void* ct, int n); 

The memcmp function compares the first n bytes from cs and ct and returns a value indicating their relationship as follows:
 if Return value if < 0 then it indicates cs less than ct
 if Return value if < 0 then it indicates cs less than ct
 if Return value if > 0 then it indicates ct is less than cs
 if Return value if > 0 then it indicates ct is less than cs
 if Return value if = 0 then it indicates cs is equal to ct
 if Return value if = 0 then it indicates cs is equal to ct
#include <stdio.h>

int main() {
  char hexchars [] = "0123456789ABCDEF";
  char hexchars2 [] = "0123456789abcdef";
  char i;

  i = memcmp (hexchars, hexchars2, 16);

  if (i < 0)
    printf ("hexchars < hexchars2\n");
  else if (i > 0)
    printf ("hexchars >  hexchars2\n");
  else
    printf ("hexchars == hexchars2\n");

  return 0;
}

It will proiduce following result:
hexchars < hexchars2


Advertisements


    6 Lectures 
     1.5 hours 

 Mr. Pradeep Kshetrapal

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav
 Print
 Add Notes
 Bookmark this page
AWT ActionListener Interface

The class which processes the ActionEvent should implement this interface.The object of that class must be registered with a component. The object can be registered using the addActionListener() method. When the action event occurs, that object's actionPerformed method is invoked.
Following is the declaration for java.awt.event.ActionListener interface:
public interface ActionListener
   extends EventListener
void actionPerformed(ActionEvent e) 
 Invoked when an action occurs.
This interface inherits methods from the following interfaces:
java.awt.EventListener
java.awt.EventListener
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtListenerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;

   public AwtListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtListenerDemo  awtListenerDemo = new AwtListenerDemo();  
      awtListenerDemo.showActionListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
   
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showActionListenerDemo(){
      headerLabel.setText("Listener in action: ActionListener");      

      ScrollPane panel = new ScrollPane();      
      panel.setBackground(Color.magenta);            

      Button okButton = new Button("OK");

      okButton.addActionListener(new CustomActionListener());        
      panel.add(okButton);
      controlPanel.add(panel);

      mainFrame.setVisible(true); 
   }

   class CustomActionListener implements ActionListener{

      public void actionPerformed(ActionEvent e) {
         statusLabel.setText("Ok Button Clicked.");
      }
   }
}
Compile the program using command prompt. Go to D:/ > AWT  and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
Verify the following output

    13 Lectures 
     2 hours 

 EduOLC
 Print
 Add Notes
 Bookmark this page
JavaScript - The Number Object

The Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.
The syntax for creating a number object is as follows −
var val = new Number(number);

In the place of number, if you provide any non-number argument, then the argument cannot be converted into a number, it returns NaN (Not-a-Number).
Here is a list of each property and their description.
The largest possible value a number in JavaScript can have 1.7976931348623157E+308
The smallest possible value a number in JavaScript can have 5E-324
Equal to a value that is not a number.
A value that is less than MIN_VALUE.
A value that is greater than MAX_VALUE
A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document
Returns the function that created this object's instance. By default this is the Number object.
In the following sections, we will take a few examples to demonstrate the properties of Number.
The Number object contains only the default methods that are a part of every object's definition.
Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.
Formats a number with a specific number of digits to the right of the decimal.
Returns a string value version of the current number in a format that may vary according to a browser's local settings.
Defines how many total digits (including digits to the left and right of the decimal) to display of a number.
Returns the string representation of the number's value.
Returns the number's value.
In the following sections, we will have a few examples to explain the methods of Number.

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
LISP - Keyword Parameters

Keyword parameters allow you to specify which values go with which particular parameter.
It is indicated using the &key  symbol.
When you send the values to the function, you must precede the values with :parameter-name.
The following example illustrates the concept.
Create a new source code file named main.lisp and type the following code in it.
(defun show-members (&key a b c d ) (write (list a b c d)))
(show-members :a 1 :c 2 :d 3)
(terpri)
(show-members :a 'p :b 'q :c 'r :d 's)
(terpri)
(show-members :a 'p :d 'q)
(terpri)
(show-members :a 1 :b 2)
When you execute the code, it returns the following result −
(1 NIL 2 3)
(P Q R S)
(P NIL NIL Q)
(1 2 NIL NIL)


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Counting number of characters in text file using java

We can read characters in a file using BufferedReader class of Java. See the example below −
Consider the following text file in the classpath.
test.txt
This is Line 1
This is Line 2
This is Line 3
This is Line 4
This is Line 5
This is Line 6
This is Line 7
This is Line 8
This is Line 9
This is Line 10
Tester.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Tester {

   private static final String FILE_PATH = "data.txt";
   public static void main(String args[]) throws IOException {
      FileUtil fileUtil = new FileUtil(FILE_PATH);
      System.out.println("No. of characters in file: " + fileUtil.getCharCount());
   }
}

class FileUtil {
   static BufferedReader reader = null;    
   public FileUtil(String filePath) throws FileNotFoundException {
      File file = new File(filePath);
      FileInputStream fileStream = new FileInputStream(file);
      InputStreamReader input = new InputStreamReader(fileStream);
      reader = new BufferedReader(input);
   }

   public static int getCharCount() throws IOException {
      int charCount = 0;
      String data;        
      while((data = reader.readLine()) != null) {
         charCount += data.length();                        
      }            
      return charCount;
   }
}
This will produce the following result −
No. of characters in file: 141
Selenium - Text Box Interaction

In this section, we will understand how to interact with text boxes. We can put values into a text box using the 'sendkeys' method. Similarly, we can also retrieve text from a text box using the getattribute("value") command. Take a look at the following example.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class webdriverdemo {
   public static void main(String[] args) throws InterruptedException {
   
      WebDriver driver = new FirefoxDriver();
      // Puts a Implicit wait, Will wait for 10 seconds before throwing exception
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      
      // Launch website
      driver.navigate().to("http://www.calculator.net/percent-calculator.html");
      
      // Maximize the browser
      driver.manage().window().maximize();
      
      // Enter value 10 in the first number of the percent Calculator
      driver.findElement(By.id("cpar1")).sendKeys("10");
      
      Thread.sleep(5000);
      
      // Get the text box from the application
      String result = driver.findElement(By.id("cpar1")).getAttribute("value");
      
      // Print a Log In message to the screen
      System.out.println(" The Result is " + result);
      
      // Close the Browser.
      driver.close();
   }
}
The output of the above script is displayed as shown below.

    46 Lectures 
     5.5 hours 

 Aditya Dua

    296 Lectures 
     146 hours 

 Arun Motoori

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    22 Lectures 
     7 hours 

 Arun Motoori

    118 Lectures 
     17 hours 

 Arun Motoori

    278 Lectures 
     38.5 hours 

 Lets Kode It
 Print
 Add Notes
 Bookmark this page
PostgreSQL - SUM() Function - GeeksforGeeks

01 Jun, 2020
PostgreSQL provides with a SUM() function that is used to get the addition of values of a numeric column.
Syntax: SUM(column)
The following points needs to be kept in mind while using the above function:
It ignores all NULL values.
If used with DISTINCT operator as SUM(DISTINCT column), it skips duplicate values.
Using SUM() function with SELECT clause returns NULL instead of Zero.
For examples we will be using the sample database (ie, dvdrental).
Example 1:In this example we will calculate the total amount paid by each customer using the SUM() function and GROUP BY clause as follows:
SELECT
    customer_id,
    SUM (amount) AS total
FROM
    payment
GROUP BY
    customer_id;
Output:
Example 2:In this example we will query for the top 10 customers who paid the most as follows:
SELECT
    customer_id,
    SUM (amount) AS total
FROM
    payment
GROUP BY
    customer_id
ORDER BY total DESC
LIMIT 10;
Output:
postgreSQL-aggregate-functions
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - Function Returning A Table
PostgreSQL - Interval Data Type
PostgreSQL - For Loops
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Copy Table
How to add input fields dynamically on button click in AngularJS ? - GeeksforGeeks

13 May, 2020
The task is to add an input field on the page when the user clicks on the button using AngularJs.
Steps:
The required component for the operation is created (add-inputComponent).
In that component, html file (add-input.component.html) required html is written.
In that HTML, the main div for input fields are there and button is created.
There is a (click) event on ADD button that redirects on the working user defined function in add-input.component.ts.
In the user defined function, the createElement() method is used to create a division every time the user clicks on the button and innerHTML() property is used to make an input field.
Then the created element div is append to the main div of add-input.component.html by appendChild() method.
Below is the implementation of above steps:app.module.ts
// Necessary imports of component is doneimport { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';  import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { AddInputComponent } from './add-input/add-input.component';  @NgModule({  declarations: [    AppComponent,    AddInputComponent  ],  imports: [    BrowserModule,    AppRoutingModule,  ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }
add-input.component.html
<!-- Main div and ADD button is created --><center>  CLICK ON BUTTON TO ADD NEW FIELD  <div class="showInputField"></div>    <!-- The add() function is called -->  <button (click)="add()">ADD</button></center>
add-input.component.ts
// The class function add() is made that contains// the necessary code for the actionimport { Component, OnInit } from '@angular/core';  @Component({  selector: 'app-add-input',  templateUrl: './add-input.component.html',  styleUrls: ['./add-input.component.css']})export class AddInputComponent implements OnInit {    constructor() { }    ngOnInit(): void {  }  add(){    let row = document.createElement('div');        row.className = 'row';      row.innerHTML = `      <br>      <input type="text">`;      document.querySelector('.showInputField').appendChild(row);  }}
Output:
Before Clicking the Button:
After Clicking the Button:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Top 10 Angular Libraries For Web Developers
Angular | keyup event
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Sqoop - Eval

This chapter describes how to use the Sqoop ‘eval’ tool. It allows users to execute user-defined queries against respective database servers and preview the result in the console. So, the user can expect the resultant table data to import. Using eval, we can evaluate any type of SQL query that can be either DDL or DML statement.
The following syntax is used for Sqoop eval command.
$ sqoop eval (generic-args) (eval-args) 
$ sqoop-eval (generic-args) (eval-args)
Using eval tool, we can evaluate any type of SQL query. Let us take an example of selecting limited rows in the employee table of db database. The following command is used to evaluate the given example using SQL query.
$ sqoop eval \
--connect jdbc:mysql://localhost/db \
--username root \ 
--query “SELECT * FROM employee LIMIT 3”
If the command executes successfully, then it will produce the following output on the terminal.
+------+--------------+-------------+-------------------+--------+
| Id   | Name         | Designation | Salary            | Dept   |
+------+--------------+-------------+-------------------+--------+
| 1201 | gopal        | manager     | 50000             | TP     |
| 1202 | manisha      | preader     | 50000             | TP     |
| 1203 | khalil       | php dev     | 30000             | AC     |
+------+--------------+-------------+-------------------+--------+

Sqoop eval tool can be applicable for both modeling and defining the SQL statements. That means, we can use eval for insert statements too. The following command is used to insert a new row in the employee table of db database.
$ sqoop eval \
--connect jdbc:mysql://localhost/db \
--username root \ 
-e “INSERT INTO employee VALUES(1207,‘Raju’,‘UI dev’,15000,‘TP’)”
If the command executes successfully, then it will display the status of the updated rows on the console.
Or else, you can verify the employee table on MySQL console. The following command is used to verify the rows of employee table of db database using select’ query.
mysql>
mysql> use db;
mysql> SELECT * FROM employee;
+------+--------------+-------------+-------------------+--------+
| Id   | Name         | Designation | Salary            | Dept   |
+------+--------------+-------------+-------------------+--------+
| 1201 | gopal        | manager     | 50000             | TP     |
| 1202 | manisha      | preader     | 50000             | TP     |
| 1203 | khalil       | php dev     | 30000             | AC     |
| 1204 | prasanth     | php dev     | 30000             | AC     |
| 1205 | kranthi      | admin       | 20000             | TP     |
| 1206 | satish p     | grp des     | 20000             | GR     |
| 1207 | Raju         | UI dev      | 15000             | TP     |
+------+--------------+-------------+-------------------+--------+


    50 Lectures 
     4 hours 

 Navdeep Kaur
 Print
 Add Notes
 Bookmark this page
How to deserialize a JSON into an existing object in Java?

The Flexjson is a lightweight java library for serializing and deserializing java beans, maps, arrays, and collections in JSON format. We can also deserialize a JSON string to an existing object using the deserializeInto() method of JSONDeserializer class, this method deserializes the given input into the existing object target. The values in the json input can overwrite values in the target object. This means if a value is included in JSON a new object can be created and set into the existing object.
public T deserializeInto(String input, T target)
import flexjson.JSONDeserializer;
public class JsonDeserializeTest {
   public static void main(String[] args) {
      Employee emp = new Employee("Adithya", "Ram", 25, 35000.00);
      System.out.println(emp);
      JSONDeserializer<Employee> deserializer = new JSONDeserializer<Employee>();
      String jsonStr =
                     "{" +
                     "\"age\": 30," +
                     "\"salary\": 45000.00" +
                     "}";
      emp = deserializer.deserializeInto(jsonStr, emp);
      System.out.println(emp);
   }
}
// Employee class
class Employee {
   private String firstName;
   private String lastName;
   private int age;
   private double salary;
   public Employee() {}
   public Employee(String firstName, String lastName, int age, double salary) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.salary = salary;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public double getSalary() {
      return salary;
   }
   public void setSalary(double salary) {
      this.salary = salary;
   }
   public String toString() {
      return "Employee[ " +
      "firstName = " + firstName +
      ", lastName = " + lastName +
      ", age = " + age +
      ", salary = " + salary +
      " ]";
   }
}
Employee[ firstName = Adithya, lastName = Ram, age = 25, salary = 35000.0 ]
Employee[ firstName = Adithya, lastName = Ram, age = 30, salary = 45000.0 ]