code-rag-bench/online-tutorials huggingface dataset:
Python | Difference between iterable and iterator - GeeksforGeeks

23 Aug, 2019
Iterable is an object, which one can iterate over. It generates an Iterator when passed to iter() method. Iterator is an object, which is used to iterate over an iterable object using __next__() method. Iterators have __next__() method, which returns the next item of the object.
Note that every iterator is also an iterable, but not every iterable is an iterator. For example, a list is iterable but a list is not an iterator. An iterator can be created from an iterable by using the function iter(). To make this possible, the class of an object needs either a method __iter__, which returns an iterator, or a __getitem__ method with sequential indexes starting with 0.
Code #1 :
for city in ["Berlin", "Vienna", "Zurich"]:    print(city)  print("\n")      for city in ("Python", "Perl", "Ruby"):    print(city)  print("\n")      for char in "Iteration is easy":    print(char, end = " ")
Output :
Berlin
Vienna
Zurich

Python
Perl
Ruby

I t e r a t i o n   i s   e a s y 
 When a for loop is executed, for statement calls iter() on the object, which it is supposed to loop over. If this call is successful, the iter call will return an iterator object that defines the method __next__(), which accesses elements of the object one at a time. The __next__() method will raise a StopIteration exception, if there are no further elements available. The for loop will terminate as soon as it catches a StopIteration exception. Let’s call the __next__() method using the next() built-in function.
Code #2 : Function ‘iterable’ will return True, if the object ‘obj’ is an iterable and False otherwise.
# list of citiescities = ["Berlin", "Vienna", "Zurich"]  # initialize the objectiterator_obj = iter(cities)  print(next(iterator_obj))print(next(iterator_obj))print(next(iterator_obj))
Output :
Berlin
Vienna
Zurich

Note: If ‘next(iterator_obj)’ is called one more time, it would return ‘StopIteration’. 
Code #3 : Check object is iterable or not
# Function to check object# is iterable or not def iterable(obj):    try:        iter(obj)        return True              except TypeError:        return False  # Driver Code     for element in [34, [4, 5], (4, 5),             {"a":4}, "dfsdf", 4.5]:                       print(element, " is iterable : ", iterable(element))
Output :
34  is iterable :  False
[4, 5]  is iterable :  True
(4, 5)  is iterable :  True
{'a': 4}  is iterable :  True
dfsdf  is iterable :  True
4.5  is iterable :  False

KAPILGAHLOT
Akanksha_Rai
Python-Miscellaneous
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Swing Examples - Create a Masked TextField

Following example showcase how to create and show a masked text field in swing based application.
We are using the following APIs.
JFormattedTextField − To create a formatted text field.
JFormattedTextField − To create a formatted text field.
MaskFormatter − To create a formatter to allows only characters specified in the pattern passed to MaskFormatter.
MaskFormatter − To create a formatter to allows only characters specified in the pattern passed to MaskFormatter.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.text.ParseException;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

     JLabel zipLabel = new JLabel("Zip Code");
     JFormattedTextField zipTextField = null;
      try {
         zipTextField = new JFormattedTextField(
            new MaskFormatter("#####")); 
         zipTextField.setColumns(5);
      } catch (ParseException e) {
         e.printStackTrace();
      }

      zipLabel.setLabelFor(zipTextField);
      
      panel.add(zipLabel);
      panel.add(zipTextField);

      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
}
Here we've used "#####" as pattern signifying that only numbers are allowed in the text fields, no other characters can be entered. And we can not enter more than 5 numbers. Following is the list of patterns to control characters.
Any digit.
Escape character, to escape special formatting characters.
Any character. Will be converted to Upper case.
Any character. Will be converted to Lower case.
Any character or number.
Any character.
Anything.
Any hex character (0-9, a-f or A-F).
 Print
 Add Notes
 Bookmark this page
Java 8 static methods in interfaces

An interface can also have static helper methods from Java 8 onwards.
public interface vehicle {
   default void print() {
      System.out.println("I am a vehicle!");
   }
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}
Live Demo
public class Java8Tester {
   public static void main(String args[]) {
      Vehicle vehicle = new Car(); vehicle.print();
   }
}
interface Vehicle {
   default void print() {
      System.out.println("I am a vehicle!");
   }
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}
interface FourWheeler {
   default void print() {
      System.out.println("I am a four wheeler!");
   }
}
class Car implements Vehicle, FourWheeler {
   public void print() {
      Vehicle.super.print();
      FourWheeler.super.print();
      Vehicle.blowHorn();
      System.out.println("I am a car!");
   }
}
I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!
How to display HTML5 client-side validation error bubbles?

To display HTML5 client-side validation error bubbles, use the required attribute.
You do not need to have JavaScript for client side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have a value:
<!DOCTYPE HTML>
<html>
   <body>
      <form action = "/cgi-bin/html5.cgi" method = "get">
         Enter email : <input type = "text" name = "newinput" required/>
         <p>Try to submit using Submit button</p>
         <input type = "submit" value = "submit" />
      </form>
   </body>
</html>
Applications of various Automata - GeeksforGeeks

20 Nov, 2019
Automata is a machine that can accept the Strings of a Language L over an input alphabet .So far we are familiar with the Types of Automata . Now, let us discuss the expressive power of Automata and further understand its Applications.
Expressive Power of various Automata:The Expressive Power of any machine can be determined from the class or set of Languages accepted by that particular type of Machine. Here is the increasing sequence of expressive power of machines :
As we can observe that FA is less powerful than any other machine. It is important to note that DFA and NFA are of same power because every NFA can be converted into DFA and every DFA can be converted into NFA .The Turing Machine i.e. TM is more powerful than any other machine.
(i) Finite Automata (FA) equivalence:
Finite Automata 
≡ PDA with finite Stack 
≡ TM with finite tape 
≡ TM with unidirectional tape 
≡ TM with read only tape 
(ii) Pushdown Automata (PDA) equivalence:
PDA ≡ Finite Automata with Stack 
(iii) Turing Machine (TM) equivalence:
Turing Machine 
≡ PDA with additional Stack 
≡ FA with 2 Stacks 
The Applications of these Automata are given as follows:
1. Finite Automata (FA) –
For the designing of lexical analysis of a compiler.
For recognizing the pattern using regular expressions.
For the designing of the combination and sequential circuits using Mealy and Moore Machines.
Used in text editors.
For the implementation of spell checkers.
2. Push Down Automata (PDA) –
For designing the parsing phase of a compiler (Syntax Analysis).
For implementation of stack applications.
For evaluating the arithmetic expressions.
For solving the Tower of Hanoi Problem.
3. Linear Bounded Automata (LBA) –
For implementation of genetic programming.
For constructing syntactic parse trees for semantic analysis of the compiler.
4. Turing Machine (TM) –
For solving any recursively enumerable problem.
For understanding complexity theory.
For implementation of neural networks.
For implementation of Robotics Applications.
For implementation of artificial intelligence.
Technical Scripter 2018
GATE CS
Technical Scripter
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Clustered and Non-clustered index
Phases of a Compiler
Preemptive and Non-Preemptive Scheduling
Differences between IPv4 and IPv6
Introduction of Process Synchronization
Difference between DFA and NFA
Introduction of Finite Automata
Regular Expressions, Regular Grammar and Regular Languages
Conversion from NFA to DFA
Pumping Lemma in Theory of Computation
Scala Collections - FoldRight Method

foldRight() method is a member of TraversableOnce trait, it is used to collapse elements of collections. It navigates elements from Right to Left order.
The following is the syntax of foldRight method.
def foldRight[B](z: B)(op: (B, A) ? B): B

Here, fold method takes associative binary operator function as a parameter. This method returns the resulted value.
Below is an example program of showing how to use foldRight method −
object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get sum of all elements of the list
      val result = list.foldRight(0)(_ + _)
      //print result
      println(result)      
   }
}
Here we've passed 0 as initial value to foldRight function and then all values are added. Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

10


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to Change Position of ggplot Title in R ? - GeeksforGeeks

30 May, 2021
In this article, we will discuss how to change the position of title in a plot using ggplot in R Programming Language. ggtitle() function can be used to give an appropriate title to a plot.
Syntax:
ggtitle("title")
By Default the title is left aligned. Thus, if the requirement is a left-aligned title nothing much has to be done.
Example:
R
library("ggplot2")  x<-c(1,2,3,4,5)y<-c(10,30,20,40,35)  df<-data.frame(x,y)  ggplot(df,aes(x,y))+geom_line()+ggtitle("Default title")
Output:
To display the title at the at any other position of the plot use theme() function. Within theme() function use plot.title parameter with element_text() function as value to it. Again within this function pass the value for hjust attribute.
Syntax: 
theme(plot.title=element_text(hjust=value))
To get the title at the center the value of hjust should be assigned to 0.5.
Example:
R
library("ggplot2")  x<-c(1,2,3,4,5)y<-c(10,30,20,40,35)  df<-data.frame(x,y)  ggplot(df,aes(x,y))+geom_line()+ggtitle("Title at center")+theme(plot.title = element_text(hjust=0.5))
Output
To display title at the right, hjust should be assigned 1 as value.
Example:
R
library("ggplot2")  x<-c(1,2,3,4,5)y<-c(10,30,20,40,35)  df<-data.frame(x,y)  ggplot(df,aes(x,y))+geom_line()+ggtitle("Title at right")+theme(plot.title = element_text(hjust=1))
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ?
Python Assignment Operators Example

Assume variable a holds 10 and variable b holds 20, then −
Assume variable a holds 10 and variable b holds 20, then −
#!/usr/bin/python

a = 21
b = 10
c = 0

c = a + b
print "Line 1 - Value of c is ", c

c += a
print "Line 2 - Value of c is ", c 

c *= a
print "Line 3 - Value of c is ", c 

c /= a 
print "Line 4 - Value of c is ", c 

c  = 2
c %= a
print "Line 5 - Value of c is ", c

c **= a
print "Line 6 - Value of c is ", c

c //= a
print "Line 7 - Value of c is ", c
When you execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Scala List mkString() method with a separator with example - GeeksforGeeks

13 Aug, 2019
The mkString() method is utilized to display all the elements of the list in a string along with a separator.
Method Definition: def mkString(sep: String): String
Return Type: It returns all the elements of the list in a string along with a separator.
Example #1:
// Scala program of mkString()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a list        val m1 = List(2, 3, 5, 7, 8)                  // Applying mkString method        val result = m1.mkString("*")                  // Displays output        println(result)          }} 
2*3*5*7*8

Example: 2#
// Scala program of mkString()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a list        val m1 = List(2, 3, 5, 7, 5)                  // Applying mkString method        val result = m1.mkString("_")                  // Displays output        println(result)              }}   
2_3_5_7_5

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Class and Object in Scala
Break statement in Scala
Scala String replace() method with example
Operators in Scala
Scala Constructors
Scala | Arrays
How to get the first element of List in Scala
Anonymous Functions in Scala
Program to convert level order binary tree traversal to linked list in Python

Suppose we have a binary search tree, we have to convert it to a singly linked list using levelorder traversal.
So, if the input is like
then the output will be [5, 4, 10, 2, 7, 15, ]
To solve this, we will follow these steps −
head := a new linked list node
head := a new linked list node
currNode := head
currNode := head
q := a list with value root
q := a list with value root
while q is not empty, docurr := delete first element from qif curr is not null, thennext of currNode := a new linked list node with value of currcurrNode := next of currNodeinsert left of curr at the end of qinsert right curr at the end of q
while q is not empty, do
curr := delete first element from q
curr := delete first element from q
if curr is not null, thennext of currNode := a new linked list node with value of currcurrNode := next of currNodeinsert left of curr at the end of qinsert right curr at the end of q
if curr is not null, then
next of currNode := a new linked list node with value of curr
next of currNode := a new linked list node with value of curr
currNode := next of currNode
currNode := next of currNode
insert left of curr at the end of q
insert left of curr at the end of q
insert right curr at the end of q
insert right curr at the end of q
return next of head
return next of head
Let us see the following implementation to get better understanding −
class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.val = data
      self.left = left
      self.right = right

def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
print(']')
   
class Solution:
   def solve(self, root):
      head = ListNode(None)
      currNode = head
      q = [root]
      while q:
         curr = q.pop(0)
         if curr:
            currNode.next = ListNode(curr.val)
            currNode = currNode.next
            q.append(curr.left)
            q.append(curr.right)
      return head.next

ob = Solution()
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(10)
root.left.left = TreeNode(2)
root.right.left = TreeNode(7)
root.right.right = TreeNode(15)
head = ob.solve(root)
print_list(head)
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(10)
root.left.left = TreeNode(2)
root.right.left = TreeNode(7)
root.right.right = TreeNode(15)
head = ob.solve(root)
[5, 4, 10, 2, 7, 15, ]
How to extract data from a plot created by ggplot2 in R?

Of course, a plot is created with some data but we might want to get the data from plot as well. This is possible in R with ggplot_build function but it works only for ggplot objects, if we create a plot with plot function then we cannot extract the data with the plot using ggplot_build. Also, it is not necessary that we create the plot using ggplot2 and save it as an object in R to get the data from ggplot_build, we can simply use this function while creating the plot.
Consider the below data frame −
set.seed(111)
x <-rnorm(10)
y <-rnorm(10,1.5)
df <-data.frame(x,y)
df
x y
1 0.2352207 1.32632587
2 -0.3307359 1.09340122
3 -0.3116238 3.34563626
4 -2.3023457 1.89405411
5 -0.1708760 2.29752850
6 0.1402782 -0.06666536
7 -1.4974267 1.41414899
8 -1.0101884 1.14086052
9 -0.9484756 0.30639103
10 -0.4939622 1.86418674
Creating the plot with ggplot2 −
library(ggplot2)
scatterplot <-ggplot(df,aes(x,y))+geom_point()
scatterplot
Extracting data from the plot −
data_from_scatterplot <-ggplot_build(scatterplot)
data_from_scatterplot
$data
$data[[1]]
x y PANEL group shape colour size fill alpha stroke
1 0.2352207 1.32632587 1 -1 19 black 1.5 NA NA 0.5
2 -0.3307359 1.09340122 1 -1 19 black 1.5 NA NA 0.5
3 -0.3116238 3.34563626 1 -1 19 black 1.5 NA NA 0.5
4 -2.3023457 1.89405411 1 -1 19 black 1.5 NA NA 0.5
5 -0.1708760 2.29752850 1 -1 19 black 1.5 NA NA 0.5
6 0.1402782 -0.06666536 1 -1 19 black 1.5 NA NA 0.5
7 -1.4974267 1.41414899 1 -1 19 black 1.5 NA NA 0.5
8 -1.0101884 1.14086052 1 -1 19 black 1.5 NA NA 0.5
9 -0.9484756 0.30639103 1 -1 19 black 1.5 NA NA 0.5
10 -0.4939622 1.86418674 1 -1 19 black 1.5 NA NA 0.5
$layout
<ggproto object: Class Layout, gg>
coord: <ggproto object: Class CoordCartesian, Coord, gg>
aspect: function
backtransform_range: function
clip: on
default: TRUE
distance: function
expand: TRUE
is_free: function
is_linear: function
labels: function
limits: list
modify_scales: function
range: function
render_axis_h: function
render_axis_v: function
render_bg: function
render_fg: function
setup_data: function
setup_layout: function
setup_panel_params: function
setup_params: function
transform: function
super: <ggproto object: Class CoordCartesian, Coord, gg>
coord_params: list
facet: <ggproto object: Class FacetNull, Facet, gg>
compute_layout: function
draw_back: function
draw_front: function
draw_labels: function
draw_panels: function
finish_data: function
init_scales: function
map_data: function
params: list
setup_data: function
setup_params: function
shrink: TRUE
train_scales: function
vars: function
super: <ggproto object: Class FacetNull, Facet, gg>
facet_params: list
finish_data: function
get_scales: function
layout: data.frame
map_position: function
panel_params: list
panel_scales_x: list
panel_scales_y: list
render: function
render_labels: function
reset_scales: function
setup: function
setup_panel_params: function
train_position: function
xlabel: function
ylabel: function
super: <ggproto object: Class Layout, gg>
$plot
attr(,"class")
[1] "ggplot_built"
Python timedelta total_seconds() Method with Example - GeeksforGeeks

06 Sep, 2021
The total_seconds() function is used to return the total number of seconds covered for the specified duration of time instance. This function is used in the timedelta class of module DateTime.
Syntax: total_seconds()
Parameters: This function does not accept any parameter.
Return values: This function returns the total number of seconds covered for the specified duration of time instance.
Example 1: In the below example, 55 minutes is going to be returned in terms of the second value with the help of total_seconds() function. 
Python3
# Python3 code for getting# total seconds for the# given duration of time # Importing time and timedelta modulefrom datetime import time, timedelta      # Specifying a time durationA = timedelta(minutes = 55) # Calling the total_seconds() function# over the specified time durationtotalsecond = A.total_seconds() # Getting the Total seconds for# the duration of 55 minutesprint("Total seconds in 55 minutes:", totalsecond)
Output:
Total seconds in 55 minutes: 3300.0
Example 2: In the below example, -3*13 minutes is going to be returned in terms of the second value with the help of total_seconds() function. 
Python3
# Python3 code for getting# total seconds for the# given duration of time # Importing time and timedelta modulefrom datetime import time, timedelta      # Specifying a time durationA = timedelta(minutes = -3*13) # Calling the total_seconds() function# over the specified time durationtotalsecond = A.total_seconds() # Getting the Total seconds for# the duration of -3*13 minutesprint("Total seconds in -3*13 minutes:", totalsecond)
Output:
Total seconds in -3*13 minutes: -2340.0
Example 3: In the below example, the total_seconds() function is converting the duration of “days = 2, hours = 3, minutes = 43, and seconds = 35” into its equivalent seconds value.
Python3
# Python3 code for getting# total seconds for the# given duration of time # Importing time and timedelta modulefrom datetime import time, timedelta      # Specifying a time durationA = timedelta(days = 2, hours = 3,              minutes = 43,              seconds = 35) # Calling the total_seconds() function# over the specified time durationtotalsecond = A.total_seconds() # Getting the Total secondsprint("Total seconds are:", totalsecond)
Output:
Total seconds are: 186215.0
arorakashish0911
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
numpy.reshape

This function gives a new shape to an array without changing the data. It accepts the following parameters −
numpy.reshape(arr, newshape, order')

Where,
arr
Array to be reshaped
newshape
int or tuple of int. New shape should be compatible to the original shape
order
'C' for C style, 'F' for Fortran style, 'A' means Fortran like order if an array is stored in Fortran-like contiguous memory, C style otherwise
import numpy as np
a = np.arange(8)
print 'The original array:'
print a
print '\n'

b = a.reshape(4,2)
print 'The modified array:'
print b
Its output would be as follows −
The original array:
[0 1 2 3 4 5 6 7]

The modified array:
[[0 1]
 [2 3]
 [4 5]
 [6 7]]


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Display array items on a div element on click of button using vanilla JavaScript

To embed the elements of an array inside a div, we just need to iterate over the array and keep
appending the element to the div
This can be done like this −
const myArray = ["stone","paper","scissors"];
const embedElements = () => {
   myArray.forEach(element => {
      document.getElementById('result').innerHTML +=
      `<div>${element}</div><br />`;
      // here result is the id of the div present in the DOM
   });
};
This code makes the assumption that the div in which we want to display the elements of array
has an id ‘result’.
The complete code for this will be −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
   <div id="result"></div>
   <button onclick="embedElements()">Show Data</button>
<script>
{
   const myArray = ["stone","paper","scissors"];
   function embedElements(){
      myArray.forEach(el => {
         document.getElementById('result').innerHTML +=`<div>${el}</div><br />`;
         // here result is the id of the div present in the dom
      });
   };
}
</script>
</body>
</html>
On clicking the button “Show Data”, the following is visible −
Deep Learning with Keras - Compiling the Model

The compilation is performed using one single method call called compile.
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')

The compile method requires several parameters. The loss parameter is specified to have type 'categorical_crossentropy'. The metrics parameter is set to 'accuracy' and finally we use the adam optimizer for training the network. The output at this stage is shown below −
Now, we are ready to feed in the data to our network.
As said earlier, we will use the mnist dataset provided by Keras. When we load the data into our system, we will split it in the training and test data. The data is loaded by calling the load_data method as follows −
(X_train, y_train), (X_test, y_test) = mnist.load_data()

The output at this stage looks like the following −
Now, we shall learn the structure of the loaded dataset.
The data that is provided to us are the graphic images of size 28 x 28 pixels, each containing a single digit between 0 and 9. We will display the first ten images on the console. The code for doing so is given below −
# printing first 10 images
for i in range(10):

plot.subplot(3,5,i+1)
plot.tight_layout()
plot.imshow(X_train[i], cmap='gray', interpolation='none')
plot.title("Digit: {}".format(y_train[i]))
plot.xticks([])
plot.yticks([])
In an iterative loop of 10 counts, we create a subplot on each iteration and show an image from X_train vector in it. We title each image from the corresponding y_train vector. Note that the y_train vector contains the actual values for the corresponding image in X_train vector. We remove the x and y axes markings by calling the two methods xticks and yticks with null argument. When you run the code, you would see the following output −
Next, we will prepare data for feeding it into our network.

    87 Lectures 
     11 hours 

 Abhilash Nelson

    106 Lectures 
     13.5 hours 

 Abhilash Nelson

    28 Lectures 
     4 hours 

 Abhilash Nelson

    58 Lectures 
     8 hours 

 Soumyadeep Dey

    59 Lectures 
     2.5 hours 

 Mike West

    128 Lectures 
     5.5 hours 

 TELCOMA Global
 Print
 Add Notes
 Bookmark this page
DB2 - Views

This chapter describes introduction of views, creating, modifying and dropping the views.
A view is an alternative way of representing the data stored in the tables. It is not an actual table and it does not have any permanent storage. View provides a way of looking at the data in one or more tables. It is a named specification of a result table.
You can create a view using the following syntax:
Syntax:
db2 create view <view_name> (<col_name>,
<col_name1...) as select <cols>.. 
from <table_name> 
Example: Creating view for shopper.sales1 table
db2 create view view_sales1(id, itemname, qty, price) 
as select id, itemname, qty, price from 
shopper.sales1  
You can modify a view using the following syntax:
Syntax:
db2 alter view <view_name> alter <col_name> 
add scope <table_or_view_name> 
Example: [To add new table column to existing view ‘view_sales1’]
db2 alter view view_sales1 alter id add 
scope shopper.sales1  
You can drop a view using the following syntax:
Syntax:
db2 drop view <view_name> 
Example:
db2 drop view sales1_view  

    10 Lectures 
     1.5 hours 

 Nishant Malik

    41 Lectures 
     8.5 hours 

 Parth Panjabi

    53 Lectures 
     11.5 hours 

 Parth Panjabi

    33 Lectures 
     7 hours 

 Parth Panjabi

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    178 Lectures 
     14.5 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Position of rightmost set bit in C++

In this problem, we are given a number N. Our task is to print the index of the rightmost set bit of the number.
Let’s take an example to understand the problem,
Input − 4
Output − 3
Explanation − binary of 4 is 100, the index of the rightmost set bit is 3.
To solve this problem, a simple solution would be shifting the number till a set bit is encountered but this could take a lot of computation if the number is large.
A more efficient solution will be using boolean algebra. For this we will first calculate 2’s complement of the number, this will flip all bits of the number leaving the first set bit as it is. Then we will compute bit-wise & of the number and it’s 2’s complement. This will result in a number with only one set bit and the position we want. The solution will be given by log2 of the number +1.
This seems a bit complex to understand let’s solve an example using this method.
N= 10 , binary = 1010
2’s complement, 0101
1010 & 0101 = 0010
log2(2) = 1
1+1 = 2 which is the given index.
Program to show the implementation of our solution,
 Live Demo
#include <iostream>
#include <math.h>
using namespace std;
void rightSetBit(int N) {
   int bitIndex = log2(N & -N)+1;
   cout<<bitIndex;
}
int main() {
   int N = 10;
   cout<<"The rightmost Set bit of the number "<<N<<" is : ";
   rightSetBit(N);
   return 0;
}
The rightmost Set bit of the number 10 is : 2
When to use @JsonAutoDetect annotation in Java?

The @JsonAutoDetect annotation can be used at the class level to override the visibility of the properties of a class during serialization and deserialization. We can set the visibility with the properties like "creatorVisibility", "fieldVisibility", "getterVisibility", "setterVisibility" and "isGetterVisibility". The JsonAutoDetect class can define public static constants that are similar to Java class visibility levels like "ANY", "DEFAULT", "NON_PRIVATE", "NONE", "PROTECTED_AND_PRIVATE" and "PUBLIC_ONLY".
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class JsonAutoDetectTest {
   public static void main(String[] args) throws IOException {
      Address address = new Address("Madhapur", "Hyderabad", "Telangana");
      Name name = new Name("Raja", "Ramesh");
      Student student = new Student(address, name, true);
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
      System.out.println("JSON: " + jsonString);
   }
}
// Address class
class Address {
   private String firstLine;
   private String secondLine;
   private String thirdLine;
   public Address(String firstLine, String secondLine, String thirdLine) {
      this.firstLine = firstLine;
      this.secondLine = secondLine;
      this.thirdLine = thirdLine;
   }
   public String getFirstLine() {
      return firstLine;
   }
   public String getSecondLine() {
      return secondLine;
   }
   public String getThirdLine() {
      return thirdLine;
   }
}
// Name class
class Name {
   private String firstName;
   private String secondName;
   public Name(String firstName, String secondName) {
      this.firstName = firstName;
      this.secondName = secondName;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getSecondName() {
      return secondName;
   }
}
// Student class
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
class Student {
   private Address address;
   private Name name;
   private Boolean isActive;
   public Student(Address address, Name name, Boolean isActive) {
      this.address = address;
      this.name = name;
      this.isActive = isActive;
   }
}
{
 "address" : {
    "firstLine" : "Madhapur",
    "secondLine" : "Hyderabad",
    "thirdLine" : "Telangana"
 },
 "name" : {
    "firstName" : "Raja",
    "secondName" : "Ramesh"
 },
 "isActive" : true
}
How to Create Typewriter Animation using HTML and CSS ?

22 Jul, 2021
Typewriter animation as the name suggests is an effect that looks like a typing animation, as being typed by a typewriter. We are going to create this animation without JavaScript and just using HTML and CSS.
Approach: To achieve the typewriter effect we will use the following CSS properties.
animation-timing-function: We need to specify the time of the animation in seconds or milliseconds so that the animation is faster and looks perfect. We also need to specify steps so that each letter appears not in a single flow but one by one as seen in typewriters. In the below code we are using the example GeeksforGeeks as the total number of letters in GeeksforGeeks is 13, so the number of steps used is 13.
overflow: So that each text appears according to the animation and is not revealed all at once, overflow: hidden is used in the below code.
white-space: To get the animation on a single line white-space: nowrap is used.
border-color: As seen in the below code the border color is animated from black too transparent to give the animation a realistic touch of a blinking cursor any color other than black can also be used.
width: To get a typing like animation width is animated from 0% to 50% (this can vary as per the text height/width or the given text spacing). 
Example: In this example, we will be going to use above-defined properties to create typewriter animation.
index.htm
<!DOCTYPE html><html>  <head>    <title>Typewriter Effect</title>    <link rel="stylesheet" type="text/css" href="style.css" />    <style type="text/css">       {        box-sizing: border-box;        padding: 0;        margin: 0;        outline: none;      }      body {        background-color: #2ca32c;        justify-content: center;        align-items: center;        height: 100vh;        display: flex;      }        h1 {        font-size: 90px;        white-space: nowrap;        overflow: hidden;        animation: typewriter 2s steps(13) infinite alternate,          blink 800ms steps(13) infinite normal;        border-right: 5px solid black;      }      @keyframes typewriter {        from {          width: 0%;        }        to {          width: 50%;        }      }      @keyframes blink {        from {          border-color: black;        }        to {          border-color: transparent;        }      }    </style>  </head>  <body>    <h1>GeeksforGeeks</h1>  </body></html>
Output:
Note: For other longer or shorter text, required changes should be done in font size, steps. The time of the animation of text and the cursor should also be changed accordingly.
CSS-Properties
CSS-Questions
HTML-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP headers | Upgrade-Insecure-Requests

07 Nov, 2019
The HTTP header Upgrade-Insecure-Requests is a request type header. It sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and it can successfully handle the upgrade-insecure-requests HTTP headers Content-Security-Policy directive.
Syntax:
Upgrade-Insecure-Requests: 1
Directives: The HTTP Upgrade-Insecure-Requests header does not accepts any directives. It acts as directives with some headers, like Content-Security-Policy for the handling of CSP. With Vary header, it works as a directive containing the value of 1.
Example:
A client request signals to the server that supports the upgrade mechanisms of upgrade-insecure-requests:GET / HTTP/1.0
Host: geeksforgeeks.org
Upgrade-Insecure-Requests: 1
GET / HTTP/1.0
Host: geeksforgeeks.org
Upgrade-Insecure-Requests: 1
The server can now redirect to a secure version of the site. An HTTP header Vary can be used so that the site isn’t served by caches to clients that don’t support the upgrade mechanism:Location: https://www.geeksforgeeks.org
Vary: Upgrade-Insecure-Requests
Location: https://www.geeksforgeeks.org
Vary: Upgrade-Insecure-Requests
To check this Upgrade-Insecure-Requests in action, go to Inspect Element -> Network check the request header forUpgrade-Insecure-Requests like below, Upgrade-Insecure-Requests is highlighted you can see.
Supported Browsers: The browsers are compatible with HTTP Upgrade-Insecure-Requests header are listed below:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | Keyboard keyCode

17 Jun, 2021
The keyCode variable in p5.js always contains the key code of the key that is recently pressed. This key code is recommended to be used when finding out if the user if pressing a modifier key, like the Shift, Control, the Caps Lock key, or the Function keys.
Syntax: 
keyCode
The program below illustrates the keyCode variable in p5.js:Example: 
javascript
function setup() {  createCanvas(400, 300);} function draw() {  clear();  textSize(18);  fill("black");  text("Press any key to see its keyCode", 60, 20);  text("The name of the key pressed", 70, 60);   textSize(52);  fill("red");   // Show the key that is recently pressed  text(key, 170, 120);  textSize(18);  fill("black");     text("The keyCode of the key pressed", 60, 160);  textSize(52);  fill("red");   // Show the key code of the key that is  // recently pressed  text(keyCode, 160, 220);}
Output:
Reference: https://p5js.org/reference/#/p5/keyCodeEnvironment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/setCamera
simranarora5sos
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Font Size for Annotation using ggplot2 in R

03 Mar, 2021
ggplot2 is a data visualization package for the statistical programming language R. After analyzing and plotting graphs, we can add an annotation in our graph by annotate() function. This article discusses how the font size of an annotation can be changed with the annotation() function.
Syntax: annotate() 
Parameters:
geom : specify text
x : x axis location
y : y axis location
label : custom textual content
color : color of textual content
size : size of text
fontface : fontface of text
angle : angle of text
By adding annotate function with only argument geom=’text’, it shows that ggplot knows that it has to add text, but it needs another parameter such as Location of text (x,y) and text data (label=text).
Approach
Import ggplot2
Create/Import Dataset
Plot the data on a graph
Add annotation() function with required parameters
Let us first create a basic plot without annotating.
Program :
R
# Import Packagelibrary(ggplot2)  # df datasetdf <- data.frame(a=c(2,4,8),                              b=c(5, 10, 15))  # plot graphplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line()  # outputplot
Output:
Basic Plot
Now, Let us see how annotation can be added.
Program :
R
# Import Packagelibrary(ggplot2)  # df datasetdf <- data.frame(a=c(2,4,8),                              b=c(5, 10, 15))  # plot graphplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line()  plot + annotate('text',                 x = 6, y = 7.5,                 label = 'GeeksForGeeks',                color='darkgreen')
Output:
label & color
To change the size of the text, use the “size” argument. In the below example, the size of GeeksForGeeks is 10 and the color is red.
Program :
R
# Import Packagelibrary(ggplot2)  # df datasetdf <- data.frame(a=c(2,4,8),                              b=c(5, 10, 15))  # plot graphplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line()  plot + annotate('text', x = 6, y = 7.5,                   label = 'GeeksForGeeks',                  color='red',                  size = 10)
Output:
Size
Picked
R-ggplot
Technical Scripter 2020
R Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Date toLocaleDateString() Method

22 Oct, 2021
Below is the example of Date toLocaleDateString() method.
Example:<script>    var dateObj = new Date();     var options = { weekday: "long",                     year: "numeric",                     month: "short",                     day: "numeric" };     document.write(dateObj    .toLocaleDateString("en-US"));    document.write("<br>");    document.write(dateObj    .toLocaleDateString("en-US", options));</script>
<script>    var dateObj = new Date();     var options = { weekday: "long",                     year: "numeric",                     month: "short",                     day: "numeric" };     document.write(dateObj    .toLocaleDateString("en-US"));    document.write("<br>");    document.write(dateObj    .toLocaleDateString("en-US", options));</script>
Output:6/24/2018
Sunday, Jun 24, 2018

6/24/2018
Sunday, Jun 24, 2018

The date.toLocaleDateString() method is used to convert a date to a string.Syntax:
dateObj.toLocaleDateString( [locales][, options])
Parameters: This method accepts two parameters as mentioned above and described below:
locales: This parameter is an array of locale strings that contain one or more language or locale tags.Note that it is an optional parameter.If you want to use specific format of the language in your application then specify that language in the locales argument.
Options: It is also an optional parameter and contains properties that specify comparison options.Some properties are localeMatcher, timeZone, weekday, year, month, day, hour, minute, second etc.
Return values: It returns a date as a string value in specific format that is specified by locale.
Note: The dateObj should be a valid Date object.
More codes for the above method are as follows:Program 1: Without parameters return value of this method cannot be relied upon in scripting.It uses the operating system’s locale’s conventions.
<script>   var dateObj = new Date(1993, 6, 28, 14, 39, 7);   document.write(dateObj.toLocaleDateString());</script>
Output:
7/28/1993 
Note: The locales and options arguments are not supported in all browsers.To check whether it is supported or not we can use following function :
function toLocaleDateStringSupportsLocales()
{
    try {
        new Date().toLocaleDateString('i');
    }
    catch (e) {
        return e.name === 'RangeError';
    }
    return false;
}

Supported Browsers: The browsers supported by JavaScript Date toLocaleDateString() Method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 5.5 and above
Opera 5 and above
Safari 1 and above
ysachin2314
javascript-date
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write a function that returns a passed string with letters in alphabetical order in JavaScript ?

21 Feb, 2022
Let’s say we need to convert the string into alphabetical order –
For example:
geeksforgeeks -> eeeefggkkorss
Approach: The task is to create a function that takes a string and returns the alphabetical order of that string.
Hence to achieve this we will go under the split, sort, and join method in javascript.
Step 1:Split the given string into characters with the help of the split() method in javascript and store that in an array
Step 2:Sort the array of characters in alphabetical order with the help of sort() function
Step 3:Join the characters into one string with the help of join() method
Example:
Javascript
<script>  function alpha(str) {    var arr = str.split(""); // splits the string    res = arr.sort().join(""); // sort the array and joins to form a string    return res; // returns the result  }  console.log("taking geeksforgeeks as a string");  console.log(alpha("geeksforgeeks"));</script>
 
Output:
Exceptional case:
If we try to put whitespace in between our passing string it will result in putting that white space in starting of the resultant string. Like in the above example string has 1 white space and in the resultant string it is useless, so to get rid of that we can use white space regular expression i.e. \s+ for selecting white spaces and replacing it with an empty string.
Example:
Javascript
<script>  function alpha(str) {    var arr = str.split("");    res = arr.sort().join("");    rws = res.replace(/\s+/g, "");    return rws;  }   console.log("taking geeksforgeeks portal as a string");  console.log(alpha("geeksforgeeks portal"));</script>
Output:
as5853535
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.