code-rag-bench/online-tutorials huggingface dataset:
Custom Events in Spring

There are number of steps to be taken to write and publish your own custom events. Follow the instructions given in this chapter to write, publish and handle Custom Spring Events.
Here is the content of CustomEvent.java file
package com.tutorialspoint;

import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent{
   public CustomEvent(Object source) {
      super(source);
   }
   public String toString(){
      return "My Custom Event";
   }
}
Following is the content of the CustomEventPublisher.java file
package com.tutorialspoint;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public class CustomEventPublisher implements ApplicationEventPublisherAware {
   private ApplicationEventPublisher publisher;
   
   public void setApplicationEventPublisher (ApplicationEventPublisher publisher) {
      this.publisher = publisher;
   }
   public void publish() {
      CustomEvent ce = new CustomEvent(this);
      publisher.publishEvent(ce);
   }
}
Following is the content of the CustomEventHandler.java file
package com.tutorialspoint;

import org.springframework.context.ApplicationListener;

public class CustomEventHandler implements ApplicationListener<CustomEvent> {
   public void onApplicationEvent(CustomEvent event) {
      System.out.println(event.toString());
   }
}
Following is the content of the MainApp.java file
package com.tutorialspoint;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ConfigurableApplicationContext context = 
         new ClassPathXmlApplicationContext("Beans.xml");
	  
      CustomEventPublisher cvp = 
         (CustomEventPublisher) context.getBean("customEventPublisher");
      
      cvp.publish();  
      cvp.publish();
   }
}
Following is the configuration file Beans.xml
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id = "customEventHandler" class = "com.tutorialspoint.CustomEventHandler"/>
   <bean id = "customEventPublisher" class = "com.tutorialspoint.CustomEventPublisher"/>

</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −
y Custom Event
y Custom Event


    102 Lectures 
     8 hours 

 Karthikeya T

    39 Lectures 
     5 hours 

 Chaand Sheikh

    73 Lectures 
     5.5 hours 

 Senol Atac

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac

    69 Lectures 
     5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to split Python tuples into sub-tuples?

Here is a tuple with 12 integers. In order to split it in four sub-tuple of three elements each, slice a tuple of three successive elements from it and append the segment in a lis. The result will be a list of 4 tuples each with 3 numbers.
>>> tup=(7,6,8,19,2,4,13,1,10,25,11,34)
>>> lst=[]
>>> for i in range(0,10,3):
lst.append((tup[i:i+3]))
>>> lst
[(7, 6, 8), (19, 2, 4), (13, 1, 10), (25, 11, 34)]
Reading a Text file in java

Java provides Reader classes to read data from various sources. You can read the contents of a file using the BufferedReader class.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {
   public static void main(String[] args) {
      try (BufferedReader br = new BufferedReader(new FileReader("myFile"))) {
         String sCurrentLine;
         
         while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}
Hi welcome to Tutorialspoint
Unset an attribute from a single array element in MongoDB?

Use $unset operator to unset an attribute. Let us first create a collection with documents −
> db.unsetAnAttributeDemo.insertOne(
...    {
...       _id: 1,
...       "StudentDetails": [
...          {
...             "StudentFirstName": "Ramit",
...             "StudentCountryName":"UK"
...          },
...          {
...             "StudentFirstName": "Bob",
...             "StudentCountryName":"US"
...          },
...          {
...             "StudentFirstName": "Carol",
...             "StudentCountryName":"AUS"
...
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }
Following is the query to display all documents from the collection with the help of find() method −
> db.unsetAnAttributeDemo.find().pretty();
This will produce the following output −
{
   "_id" : 1,
   "StudentDetails" : [
      {
         "StudentFirstName" : "Ramit",
         "StudentCountryName" : "UK"
      },
      {
         "StudentFirstName" : "Bob",
         "StudentCountryName" : "US"
      },
      {
         "StudentFirstName" : "Carol",
         "StudentCountryName" : "AUS"
      }
   ]
}
Following is the query to unset an attribute from a single array element. The attribute “StudentCountryName” with value “AUS” will unset −
> db.unsetAnAttributeDemo.update({"StudentDetails.StudentCountryName": "AUS"}, {$unset:
   {"StudentDetails.$.StudentCountryName": 1}});
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display the document from the collection to check that attribute StudentCountryName with value “AUS” has been cleared or not −
> db.unsetAnAttributeDemo.find().pretty();
This will produce the following output −
{
   "_id" : 1,
   "StudentDetails" : [
      {
         "StudentFirstName" : "Ramit",
         "StudentCountryName" : "UK"
      },
      {
         "StudentFirstName" : "Bob",
         "StudentCountryName" : "US"
      },
      {
         "StudentFirstName" : "Carol"
      }
   ]
}
Tk - Entry Widgets

Entry widgets are used to accept a single line of text as input. Getting user input is almost mandatory in all Tk applications. The syntax for entry widget is shown below −
entry entryName options

The options available for the entry widget are listed below in the following table −
-background color
Used to set background color for widget.
-borderwidth width
Used to draw with border in 3D effects.
-font fontDescriptor
Used to set font for widget.
-foreground color
Used to set foreground color for widget.
-pady number
Sets the pady for the widget.
-relief condition
Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove.
-textvariable varName
Variable associated with the widget. When the text of widget changes, the variable is set to text of widget.
-width number
Sets the width for widget.
-justify side
Sets the justification side. The valid sides are left and right.
-show character
Sets the character for secure entry.
A simple example using entry widget is shown below −
#!/usr/bin/wish

grid [entry .myEntry -background red -foreground white -relief ridge -borderwidth 8
   -font {Helvetica -18 bold} -width 35 -textvariable myvariable -justify right ]
set myvariable "Hello World"
When we run the above program, we will get the following output −
An example for secure entry is shown below −
#!/usr/bin/wish

grid [entry .myEntry -background red -foreground white  -relief ridge -borderwidth 8
   -font {Helvetica -18 bold} -width 35 -textvariable myvariable -justify left -show "*"]
set myvariable "Hello World"
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page
How to Start and Stop a Timer in PHP ? - GeeksforGeeks

10 May, 2021
You can start and stop a timer in PHP using the microtime() function in PHP. The microtime() function is an inbuilt function in PHP which is used to return the current Unix timestamp with microseconds.
 In this article, you will learn the uses of the microtime() function.
Syntax:
microtime( $get_as_float )
Parameters: The $get_as_float is sent as a parameter to the microtime() function, and it returns the string microsec by default.
Return Value: By default, the microtime() function returns the time as a string, but if it is set to TRUE, then the function returns the time as a string. So the default is FALSE.
Example 1: The following example uses false as the parameter for the microtime() method.
PHP
<?php    // Displaying the micro time as a string  echo ("Displaying the micro time as a string :");  echo(microtime());?>
Displaying the micro time as a string :0.62248800 1620222618
Example 2: The following example uses true as the parameter for the microtime() method.
PHP
<?php      // Displaying the micro time as a float type    echo ("Displaying the micro time as a float :");    echo(microtime(true));?>
Displaying the micro time as a float :1620222618.9294
The microtime() function can also be used to measure the speed of code written in PHP, which is discussed below.
Note: The microtime() function is an inbuilt function in PHP which is used to return the current Unix timestamp with microseconds. 
Example 3: In the following code, the timestamp function is placed twice in a program once at starting of the program and another at end of the program. Then the time difference between end time and start time is the actual speed of code.
PHP
<?php  // Use microtime() function to measure// starting time$time_start = microtime(true);  // Code of program$num = 0;  for( $i = 0; $i < 100000000; $i += 1 ) {    $num += 5;}  // Use microtime() function to measure// ending time$time_end = microtime(true);  // Time difference$time = $time_end - $time_start;  echo "The speed of code = ".$time;  ?>
The speed of code = 3.625461101532
Example 4: The following code uses the microtime() function to get the current time in milliseconds.
PHP
<?php   //current time in milliseconds    $milliseconds = round(microtime(true) * 1000);    echo $milliseconds;?>
1620222618825
PHP-basics
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
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
How to insert spaces/tabs in text using HTML/CSS?
How to add vertical lines to a distribution plot (sns.distplot) in Matplotlib?

To add vertical lines to a distribution plot, we can take the following steps−
Create a list of numbers.
Create an axis using sns.displot().
Get x and y data of the axis ax.
Plot a vertical line on the plot.
Remove the line at the 0th index.
To display the figure, use show() method.
import seaborn as sns, numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [5, 6, 7, 2, 3, 4, 1, 8, 2]
ax = sns.distplot(x, kde=True)
x = ax.lines[0].get_xdata()
y = ax.lines[0].get_ydata()
plt.axvline(x[np.argmax(y)], color='red')
ax.lines[0].remove()
plt.show()
String substring(beginIndex, endIndex)

This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1, if the second argument is given.
Here is the syntax of this method −
public String substring(int beginIndex, int endIndex)

Here is the detail of parameters −
beginIndex − the begin index, inclusive.
beginIndex − the begin index, inclusive.
endIndex − the end index, exclusive.
endIndex − the end index, exclusive.
The specified substring.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");

      System.out.print("Return Value :" );
      System.out.println(Str.substring(10, 15) );
   }
}
This will produce the following result −
Return Value : Tuto


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python Program to Merge a Matrix By the Elements of First Column

11 Oct, 2020
Given a Matrix, perform merge on the basis of the element in the first column.
Input : test_list = [[4, “geeks”], [3, “Gfg”], [4, “CS”], [4, “cs”], [3, “best”]] Output : [[4, ‘geeks’, ‘CS’, ‘cs’], [3, ‘Gfg’, ‘best’]] Explanation : 4 is paired with geeks, CS and cs hence are merged into 1 row.
Input : test_list = [[4, “geeks”], [3, “Gfg”], [4, “CS”], [5, “cs”], [3, “best”]] Output : [[4, ‘geeks’, ‘CS’, ‘cs’], [3, ‘Gfg’, ‘best’], [5, ‘cs’]] Explanation : 4 is paired with geeks and CS hence are merged into 1 row.  
Method 1 : Using setdefault() and list comprehension
In this, the task of grouping is done using setdefault(), which assigns key as first column element and rest of elements as values of list. List comprehension is used post that to get all the values from dictionary constructed.
Python3
# initializing listtest_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"],              [4, "cs"], [3, "best"]]  # printing original listprint("The original list is : " + str(test_list))  res = {}for key, val in test_list:      # setdefault used to merge similar values    res.setdefault(key, []).append(val)  # getting all valuesres = [[key] + val for key, val in res.items()]  # printing resultprint("Merged Matrix : " + str(res))
Output:
The original list is : [[4, ‘geeks’], [3, ‘Gfg’], [4, ‘CS’], [4, ‘cs’], [3, ‘best’]]Merged Matrix : [[4, ‘geeks’, ‘CS’, ‘cs’], [3, ‘Gfg’, ‘best’]]
Method 2 : Using values() and setdefault()
Here, we extract the values using values(), rest all the operations are performed in a similar manner as explained above. This program omits from the list the first column element based on which grouping was performed.
Python3
# initializing listtest_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"],             [4, "cs"], [3, "best"]]  # printing original listprint("The original list is : " + str(test_list))  res = {}for key, val in test_list:      # setdefault used to merge similar values    res.setdefault(key, []).append(val)  # fetch values using value()res = list(res.values())  # printing resultprint("Merged Matrix : " + str(res))
Output:
The original list is : [[4, ‘geeks’], [3, ‘Gfg’], [4, ‘CS’], [4, ‘cs’], [3, ‘best’]]Merged Matrix : [[‘geeks’, ‘CS’, ‘cs’], [‘Gfg’, ‘best’]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Function Decorators in Python | Set 1 (Introduction)

10 Nov, 2018
In Python, we can define a function inside another function.In Python, a function can be passed as parameter to another function (a function can also return another function).
In Python, we can define a function inside another function.
In Python, a function can be passed as parameter to another function (a function can also return another function).
# A Python program to demonstrate that a function# can be defined inside another function and a# function can be passed as parameter.  # Adds a welcome message to the stringdef messageWithWelcome(str):      # Nested function    def addWelcome():        return "Welcome to "      # Return concatenation of addWelcome()    # and str.    return  addWelcome() + str  # To get site name to which welcome is addeddef site(site_name):    return site_name  print messageWithWelcome(site("GeeksforGeeks"))
Output:
Welcome to GeeksforGeeks
We use @func_name to specify a decorator to be applied on another function.
# Adds a welcome message to the string# returned by fun(). Takes fun() as# parameter and returns welcome().def decorate_message(fun):      # Nested function    def addWelcome(site_name):        return "Welcome to " + fun(site_name)      # Decorator returns a function    return addWelcome  @decorate_messagedef site(site_name):    return site_name;  # Driver code  # This call is equivalent to call to# decorate_message() with function# site("GeeksforGeeks") as parameterprint site("GeeksforGeeks")
Output:
Welcome to GeeksforGeeks
Decorators can also be useful to attach data (or add attribute) to functions.
# A Python example to demonstrate that# decorators can be useful attach data  # A decorator function to attach# data to funcdef attach_data(func):       func.data = 3       return func  @attach_datadef add (x, y):       return x + y  # Driver code  # This call is equivalent to attach_data()# with add() as parameterprint(add(2, 3))  print(add.data)
Output:
5
3
‘add()’ returns sum of x and y passed as arguments but it is wrapped by a decorator function, calling add(2, 3) would simply give sum of two numbers but when we call add.data then ‘add’ function is passed into then decorator function ‘attach_data’ as argument and this function returns ‘add’ function with an attribute ‘data’ that is set to 3 and hence prints it.
Python decorators are a powerful tool to remove redundancy.
Please refer Decorators in Python for more details.
This article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How to use clock() function in C++

Here we will see how to use the clock() in C++. This clock() is present in the time.h or ctime header file. Here we will find the elapsed time of a process using this clock() function
To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the taks, then subtract the values to get the differences. After that we will divide the difference by CLOCK_PER_SEC (Number of clock ticks per second) to get the processor time.
#include <iostream>
#include <ctime>
using namespace std;
void take_enter() {
   cout << "Press enter to stop the counter" <<endl;
   while(1) {
      if (getchar())
      break;
   }
}
main() {
   // Calculate the time taken by take_enter()
   clock_t t;
   t = clock();
   cout << "Timer starts\n";
   take_enter();
   cout << "Timer ends \n";
   t = clock() - t;
   double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
   cout << "The program took "<< time_taken <<" seconds to execute";
}
Timer starts
Press enter to stop the counter
Timer ends
The program took 3.546 seconds to execute
How to place text on image using HTML and CSS?

30 Jul, 2021
CSS position property is used to set the position of text over an image. This can be done by enclosing the image and text in an HTML “div”. Then make the position of div “relative” and that of text “absolute”. The absolute elements are positioned relative to their parent (div). The top, right, bottom, and left properties of these elements specify their location from the parent.
Example 1:
<!DOCTYPE html><html>  <head>    <style>        .gfg {            margin: 3%;            position: relative;        }          .first-txt {            position: absolute;            top: 17px;            left: 50px;        }          .second-txt {            position: absolute;            bottom: 20px;            left: 10px;        }    </style></head>  <body>    <div class="gfg">        <img src="gfg.png">        <h3 class="first-txt">            GeeksforGeeks        </h3>                  <h3 class="second-txt">            A computer science portal        </h3>    </div></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <style>        .gfg {            margin: 3%;            position: relative;        }          .first-txt {            position: absolute;            top: 17px;            left: 20px;        }          .second-txt {            position: absolute;            top: 17px;            left: 150px;        }    </style></head>  <body>    <div class="gfg">        <img src="gfg.png">        <h3 class="first-txt">Left</h3>        <h3 class="second-txt">Right</h3>    </div></body>  </html>
Output:
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
How to save a plot using ggplot2 in R?

17 Jun, 2021
In this article, we are going to see how to save GGPlot in R Programming language. ggplot2 is a plotting package in R that is used to create complex plots from data specified in a data frame. It provides a more programmatic interface for specifying which variables to plot on to the graphical device, how they are displayed, and general visual properties. The package can be installed and downloaded into the working space using the following syntax : 
install.packages("ggplot2")
The ggplot() method is used to create different types of plots on the screen. It is used to bind a data frame to the data argument of the plot. It is used to also define the aesthetics and component mappings using the aes() attribute of the graph. It is used to create complex plots by selecting which variables are to be plotted and how to present them in the graph, for instance, the coordinates, shape, color, etc. The graphical representations can also be created in the form of geoms specific to the type of plot to be created. 
ggplot (data , mapping = aes(x, y)) + geom_point()
The ggsave() is a method in the ggplot2 package which is used for saving the last plot that was displayed in the screen. It also makes assumption about the type of graphics device from the specified extension. The filename needs to be specified into the function call. The plot can be saved with both a .png or .pdf extension. 
Syntax: ggsave( filename, plot = last_plot(), width = NA, height = NA, units = c(“in”, “cm”, “mm”),  path )
Arguments : 
filename – The character string name to assign to the plot
plot – By default, it is used to save the last displayed plot.
width, height, units – The dimensions of the plot
path – The path to save the image can also be specified
Code:
R
# importing the reqd librarieslibrary(ggplot2)  # defining the x and y coordinatesxpos <- 1:5ypos <- xpos**3  # creating a data framedata_frame <- data.frame(xpos = xpos, ypos = ypos)  # creating a plotgraph <- ggplot(data_frame, aes(xpos,ypos)) +   geom_point()  # saving the plot as pdf ggsave("cubegfg.pdf", graph, path = "/Users/mallikagupta/Desktop")
Output
Saving 7.47 x 5.96 in image
The plot can also be saved to the working space without using the ggsave() method. The png() method in R can be used to save a ggplot in the png format into the specified directory. The name of the plot along with the path name can be specified as an argument of the method. 
png(plot-path)
The dev.off() method is then used to terminate this graphical device window and save the plot. 
R
# importing the reqd librarieslibrary(ggplot2)  # defining the x and y coordinatesxpos <- 1:5ypos <- xpos**3  # creating a data framedata_frame <- data.frame(xpos = xpos, ypos = ypos)  # creating a plotgraph <- ggplot(data_frame, aes(xpos,ypos)) +   geom_point()png("Check.png")print(graph)dev.off()
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Adding Time in Python

Suppose we have a string that is representing a 12-hour clock time with suffix am or pm, and an integer n is also given, we will add n minutes to the time and return the new time in the same format.
So, if the input is like s = "8:20pm" and n = 150, then the output will be 10:50pm
To solve this, we will follow these steps −
h, m := take the hour and minute part from s
h, m := take the hour and minute part from s
h := h mod 12
h := h mod 12
if the time s is in 'pm', thenh := h + 12
if the time s is in 'pm', then
h := h + 12
h := h + 12
t := h * 60 + m + n
t := h * 60 + m + n
h := quotient of t/60, m := remainder of t/60
h := quotient of t/60, m := remainder of t/60
h := h mod 24
h := h mod 24
suffix := 'am' if h < 12 otherwise 'pm'
suffix := 'am' if h < 12 otherwise 'pm'
h := h mod 12
h := h mod 12
if h is same as 0, thenh := 12
if h is same as 0, then
h := 12
h := 12
return the time h:m suffix
return the time h:m suffix
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s, n):
      h, m = map(int, s[:-2].split(':'))
      h %= 12
      if s[-2:] == 'pm':
         h += 12
      t = h * 60 + m + n
      h, m = divmod(t, 60)
      h %= 24
      suffix = 'a' if h < 12 else 'p'
      h %= 12
      if h == 0:
         h = 12
      return "{:02d}:{:02d}{}m".format(h, m, suffix)
ob = Solution()
print(ob.solve("8:20pm", 150))
"8:20pm", 150
10:50pm
ReactJS dangerouslySetInnerHTML Attribute

25 May, 2021
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component.
In class-based components, the dangerouslySetInnerHTML attribute is used to set innerHTML for the page. This is the replacement for innerHTML attribute.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';  // Defining our App Componentconst App = () => {    // Function to demonstrate dangerouslySetInnerHTML attribute  function Set() {    return { __html: 'Setting HTML using dangerouslySetInnerHTML attribute' };  }    // Returning our JSX code  return <>    <div>      <h1>GeeksforGeeks</h1>      <div        dangerouslySetInnerHTML={Set()}></div>    </div>  </>;}  // Exporting your Default App Componentexport default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference:https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
ReactJS Attributes
ReactJS DOM Elements
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add a new line in the alert box ?

20 May, 2019
To add a new line to the content of alert box we are going to use \n backslash(n).
Example-1: This example adds \n between the 2 lines to the text of alert box.
<!DOCTYPE HTML><html>  <head>    <title>        JavaScript |      New line in alert box.    </title></head>  <body style="text-align:center;"      id="body">    <h1 style="color:green;">              GeeksForGeeks          </h1>    <p>        Click on the button to pop       alert box with added new line.    </p>    <button onclick="gfg_Run()">        click here    </button>    <script>        var text =            "This is line 1\nThis is line 2";          function gfg_Run() {            alert(text);        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
Example-2: This example adds \n among the 3 lines to the text of alert box.
<!DOCTYPE HTML><html>  <head>    <title>        JavaScript       | New line in alert box.    </title></head>  <body style="text-align:center;"       id="body">    <h1 style="color:green;">              GeeksForGeeks          </h1>    <p>        Click on the button to pop      alert box with added new line.    </p>    <button onclick="gfg_Run()">        click here    </button>    <script>        var text =             "This is first line\nThis is "+            "middle line\nThis is last line";          function gfg_Run() {            alert(text);        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Johnson SU Distribution in Statistics

10 Jan, 2020
scipy.stats.johnsonsu() is a Johnson SU continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : Johnson SU continuous random variable
Code #1 : Creating Johnson SU continuous random variable
# importing library  from scipy.stats import johnsonsu      numargs = johnsonsu.numargs a, b = 4.32, 3.18rv = johnsonsu(a, b)     print ("RV : \n", rv)  
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D4E91708

Code #2 : Johnson SU continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = johnsonsu.rvs(a, b, scale = 2, size = 10) print ("Random Variates : \n", R)   # PDF R = johnsonsu.pdf(a, b, quantile, loc = 0, scale = 1) print ("\nProbability Distribution : \n", R)  
Output :
Random Variates : 
 [-6.33841843 -5.35469028 -5.36145351 -4.4504208  -1.91574847 -5.01633416
 -5.37699657 -4.15794134 -4.90450547 -2.93846617]

Probability Distribution : 
 [5.34745702e-06 2.86846536e-05 2.54767528e-05 1.66921608e-05
 9.34800722e-06 4.69729578e-06 2.16525150e-06 9.26607636e-07
 3.70800055e-07 1.39402846e-07]

Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution)      plot = plt.plot(distribution, rv.pdf(distribution)) 
Output :
Distribution : 
 [0.         0.06122449 0.12244898 0.18367347 0.24489796 0.30612245
 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449  0.67346939
 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633
 1.10204082 1.16326531 1.2244898  1.28571429 1.34693878 1.40816327
 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102
 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714
 2.20408163 2.26530612 2.32653061 2.3877551  2.44897959 2.51020408
 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102
 2.93877551 3.        ]
 
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np      x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = johnsonsu .pdf(x, 1, 3) y2 = johnsonsu .pdf(x, 1, 4) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert given Pandas series into a dataframe with its index as another column on the dataframe

17 Aug, 2020
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor.
Syntax: pandas.Series(data, index, dtype, copy)
Return: Series object.
Now, Let’s create a pandas Series:
Python3
# importing pandas packageimport pandas as pd  # Creating Series of # programming languagess = pd.Series(['C', 'C++', 'Java',                'Python', 'Perl', 'Ruby',               'Julia'])  s
Output:
Now, we will convert given Pandas series into a dataframe with its index as another column on the dataframe by using Series.to_frame() and Dataframe.reset_index() methods together.
Syntax: Series.to_frame(name=None)
Return: Dataframe.
Syntax: Dataframe.reset_index(level=None, drop=False, name=None, inplace=False)
Return: Dataframe.
Example 1: We will convert given Pandas series into a dataframe with its index as another column.
Python3
# using series.to_frame to# convert series to dataframedf = s.to_frame().reset_index()  # show the dataframedf
Output:
Example 2: We can also rename our index column.
Python3
# Renaming our index column as 'new_index'df.rename(columns = {'index':'new_index'},          inplace = True)  # show the dataframedf
Output: 
Python pandas-dataFrame
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
8086 program to convert a 16 bit decimal number to binary - GeeksforGeeks

03 Jun, 2021
Problem: We are given a 16 bit decimal number we have to print the number in binary format
Examples: 
Input: d1 = 16
Output: 10000

Input: d1 = 7
Output: 111 
Explanation:  
Load the value stored into registerDivide the value by 2 to convert it to binaryPush the remainder into the stackIncrease the countRepeat the steps until the value of the register is greater than 0Until the count is greater than zeroPOP the stackAdd 48 to the top element to convert it into ASCIIPrint the character using interruptDecrements the count
Load the value stored into register
Divide the value by 2 to convert it to binary
Push the remainder into the stack
Increase the count
Repeat the steps until the value of the register is greater than 0
Until the count is greater than zero
POP the stack
Add 48 to the top element to convert it into ASCII
Print the character using interrupt
Decrements the count
Program: 
;8086 program to convert a 16 bit decimal number to binary    .MODEL SMALL    .STACK 100H    .DATA        d1 dw 16    .CODE        MAIN PROC FAR            MOV AX,    @DATA        MOV DS,    AX  ;load the value stored;in variable d1    mov ax,    d1  ;convert the value to binary;print the value    CALL PRINT  ;interrupt to exit    MOV AH,    4CH INT 21H      MAIN ENDP        PRINT PROC  ;initialize count    mov cx,    0 mov dx, 0 label1:;if    ax is zero        cmp ax,        0 je print1  ;initialize bx to 2 mov bx, 2  ;divide it by 2;to convert it to binary    div bx  ;push it in the stack    push dx  ;increment the count    inc cx  ;set dx to 0    xor dx,    dx        jmp label1            print1:  ;check if count;is greater than zero    cmp cx,    0 je exit  ;pop the top of stack    pop dx  ;add 48 so that it;represents the ASCII;value of digits    add dx,    48  ;interrupt to print a;character    mov ah,    02h int 21h  ;decrease the count    dec cx        jmp print1            exit : ret                       PRINT ENDP                           END MAIN
Output: 
10000
Note: The program cannot be run on an online editor, please use MASM to run the program and use dos box to run MASM, you might use any 8086 emulator to run the program 
arorakashish0911
Computer Organization and Architecture
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Architecture of 8086
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Addressing modes in 8085 microprocessor
Computer Organization | RISC and CISC
8085 program to add two 8 bit numbers
Architecture of 8085 microprocessor
Interrupts
Memory Hierarchy Design and its Characteristics
Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)
numpy.nper() in Python - GeeksforGeeks

28 Nov, 2018
numpy.pmt(rate, pmt, pv, fv, when = ‘end’) : This financial function helps user to compute number of periodic payments.
Parameters :rate : [scalar or (M, )array] Rate of interest as decimal (not per cent) per periodpmt : [scalar or (M, )array] Payment valuefv : [scalar or (M, )array] Future valuepv : [scalar or (M, )array] present valuewhen : at the beginning (when = {‘begin’, 1}) or the end (when = {‘end’, 0}) of each period. Default is {‘end’, 0}.
Return : Number of periodic payments.
Equation being solved :
fv + pv*(1+rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper – 1) == 0
or when rate == 0fv + pv + pmt * nper == 0
Code:
# Python program explaining # pmt() function   import numpy as np   ''' Question :   how much time would it take to pay-off a loan of $10, 000 at 10 % annual rate of interest, if we had $100 to pay each month ? '''  # rate    pmt    pv Solution = np.nper(0.1 / 12, -100, 10000)   # Here fv = 0 ; Also Default value of fv = 0 print("Solution - No. of periods : % f months" %(Solution)) 
Output:
Solution - No. of periods : 215.905777 months

Python numpy-Financial Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
How to set the width of a Tkinter Entry widget in pixels?

Tkinter has an Entry widget to accept single-line user input. It has many properties and attributes that can be used to configure the Entry widget. To change the size (width or height of the Entry widget), we can use Internal Padding Properties – ipadx and ipady. By defining the value of internal padding, we can actually change the width and height of the Entry widget.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x350")

#Define a function to submit the validate the value of Entry widget
def submit_name():
   Label(frame, text="Hello "+ entry.get(), font=('Helvetica',12, 'bold')).pack(pady=20)
   submit.configure(state= "disabled")

#Creates a Frame
frame = LabelFrame(win, width= 400, height= 180, bd=3)
frame.pack()
#Create an Entry widget in the Frame for Accepting the Username
entry = ttk.Entry(frame, width= 40)
entry.insert(INSERT, "Enter Your Name")
entry.pack(ipadx= 30, ipady=30)

#Set the focus on Entry1
entry.focus_set()

#Create a submit button
submit= ttk.Button(win, text= "submit",command=submit_name)
submit.pack(pady=10)
win.mainloop()
Run the above code to display the Entry widget which has some internal padding in it.
In the given output, we will click the "submit" button and it will display the greeting message as the output on the screen.
How to turn off the ticks and marks of a matlibplot axes?

To turn off the ticks and marks of a matplotlib axes, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Plot x and y data points using plot() method.
Get the current axis of the plot.
Use set_tick_params() to hide X and Y axes label marks.
Use set_xticks() and set_yticks() to hide X and Y axes tick marks.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create x and y data points
x = np.linspace(-10, 10, 100)
y = np.sin(x)

plt.plot(x, y)
ax = plt.gca()

# Hide X and Y axes label marks
ax.xaxis.set_tick_params(labelbottom=False)
ax.yaxis.set_tick_params(labelleft=False)

# Hide X and Y axes tick marks
ax.set_xticks([])
ax.set_yticks([])

plt.show()
It will produce the following output
Python - Change List Item - GeeksforGeeks

02 Dec, 2020
List in python is mutable types which means it can be changed after assigning some value. The list is similar to arrays in other programming languages. In this article, we are going to see how to change list items in python. 
Accessing the first element mylist[0]
Accessing the second element mylist[1]
Accessing the last element mylist[-1] or mylist[len(mylist)-1]
Python3
# codegfg = [ 10, 20, 30, 40, 50, 60]  #first elementprint(gfg[0])  #second elementprint(gfg[1])  #last elementprint(gfg[-1])
Output:
10
20
60
Example 1: Change Single list item.
Approach:
Change first element mylist[0]=value
Change third element mylist[2]=value
Change fourth element mylist[3]=value
Code:
Python3
# listList=[ 10, 20, 30, 40, 50, 60]print("original list ")print(List)  #changing the first valueList[0] = 11  #changing the second valueList[1] = 21  #changing the last elementList[ -1] = 61  print("\nNew list")print(List)
Output:
original list 
[10, 20, 30, 40, 50, 60]

New list
[11, 21, 30, 40, 50, 61]
Example 2: Changing all values using loops.
Python3
# listlist = [ 10, 20, 30, 40, 50, 60]print("Original list ")print(list)      print("After incrementing each element of list by 2")    # adding 2 to each value of list# len method to calculate length of list# range method is used to go upto a certain rangefor i in range( len(list)):    list[i] = list[i] + 2  print(list)
Output:
Original list 
[10, 20, 30, 40, 50, 60]
After incrementing each element of list by 2
[12, 22, 32, 42, 52, 62]
Example 3: Changing all values of a list using List comprehension.
Python3
# listList_1 = [ 10, 20, 30, 40, 50]print("Original list ")print(List_1)  print("After incrementing each element of list by 2")List_2=[ i+2 for i in List_1]  print(List_2)
Output:
Original list 
[10, 20, 30, 40, 50]
After incrementing each element of list by 2
[12, 22, 32, 42, 52]
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to integrate Git Bash with Visual Studio Code? - GeeksforGeeks

22 Nov, 2021
Git Bash is an application that provides Git command line experience on the Operating System. It is a command-line shell for enabling git with the command line in the system. VSCode is a Text editor that provides support for development operations and version control systems. It provides tools for a user to build hassle-free codes. One should have an adequate understanding of these as they serve as pre-requisites. In order to download and install prior downloaded and install Git Bash while VSCode from its official website.
Now dwelling further to the integration of GitBash with VSCode we need to follow sequential steps in order to integrate Git Bash with Visual Studio Code which is as follows:
Open Terminal in VScode Open settingsAdd the properties to the setting page.Reopen VS Code
Open Terminal in VScode 
Open settings
Add the properties to the setting page.
Reopen VS Code
Step 1: Open Terminal in VScode by using the shortcut key Ctrl+~. Here you will see that currently, it has PowerShell and we have to add bash to it.
Step 2: Then, you have to open settings by File->Preferences->Settings or by pressing Ctrl+, . You have to click on the Open Settings(JSON) icon as shown in the image below:
Step 3: On clicking, you will see the settings page. You have to add the below properties at the last of all settings as shown in the image below:
Javascript
"terminal.integrated.profiles.windows":{"Git Bash":{"path":"C:\\Program Files\\Git\\bin\\bash.exe"},  },"terminal.integrated.defaultProfile.windows": "Git Bash"
Step 4: And that’s all when you will reopen VS Code then you will see that Git Bash has been integrated. Now you can run Git Bash commands directly in VS Code.
muskan02
rajeshgsn9
Git
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
Difference Between Git Push Origin and Git Push Origin Master
Git - Difference Between Git Fetch and Git Pull
How to Undo a Commit in Git ?
How to Push Git Branch to Remote?
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to Align Text in HTML?
How to install Jupyter Notebook on Windows?
How to filter object array based on attributes?
Inner Join vs Outer Join - GeeksforGeeks

09 May, 2017
What is Join?An SQL Join is used to combine data from two or more tables, based on a common field between them. For example, consider the following two tables.
Student Table
StudentCourse Table
Following is join query that shows names of students enrolled in different courseIDs.
SELECT StudentCourse.CourseID,Student.StudentName
FROM Student
INNER JOIN StudentCourse 
ON StudentCourse.EnrollNo = Student.EnrollNo
ORDER BY StudentCourse.CourseID
Note:  INNER is optional above.  Simple JOIN is also considered as INNER JOIN
The above query would produce following result.
What is the difference between inner join and outer join?
Outer Join is of 3 types1) Left outer join2) Right outer join3) Full Join
1) Left outer join returns all rows of table on left side of join. The rows for which there is no matching row on right side, result contains NULL in the right side.
SELECT Student.StudentName,
       StudentCourse.CourseID
FROM Student
LEFT OUTER JOIN StudentCourse 
ON StudentCourse.EnrollNo = Student.EnrollNo
ORDER BY StudentCourse.CourseID
Note: OUTER is optional above. Simple LEFT JOIN is also considered as LEFT OUTER JOIN
2) Right Outer Join is similar to Left Outer Join (Right replaces Left everywhere)
3) Full Outer Join Contains results of both Left and Right outer joins.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
DBMS-SQL
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | WITH clause
SQL | Join (Inner, Left, Right and Full Joins)
SQL query to find second highest salary?
SQL Interview Questions
SQL Trigger | Student Database
CTE in SQL
Difference between Clustered and Non-clustered index
Data Preprocessing in Data Mining
Difference between SQL and NoSQL
SQL | Views