code-rag-bench/online-tutorials huggingface dataset:
GATE | GATE CS 1996 | Question 13

20 May, 2019
An advantage of chained hash table (external hashing) over the open addressing scheme is
(A) Worst case complexity of search operations is less(B) Space used is less(C) Deletion is easier(D) None of the aboveAnswer: (C)Explanation:
In Open Addressing scheme sometimes though element is present we can't delete it if empty bucket comes in between while searching for that element.
External hashing scheme is free from this limitations .
Hence, Option c is correct answer. 
Quiz of this Question
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2001 | Question 50
GATE | GATE-CS-2004 | Question 31
Python Program to check Armstrong Number

29 Jun, 2022
Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... 
Example:
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153

Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9

Input : 1253
Output : No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723

Input : 1634
Output : Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
Python
# Python program to determine whether# the number is Armstrong number or not # Function to calculate x raised to# the power ydef power(x, y):         if y == 0:        return 1    if y % 2 == 0:        return power(x, y // 2) * power(x, y // 2)             return x * power(x, y // 2) * power(x, y // 2) # Function to calculate order of the numberdef order(x):     # Variable to store of the number    n = 0    while (x != 0):        n = n + 1        x = x // 10             return n # Function to check whether the given# number is Armstrong number or notdef isArmstrong(x):         n = order(x)    temp = x    sum1 = 0         while (temp != 0):        r = temp % 10        sum1 = sum1 + power(r, n)        temp = temp // 10     # If condition satisfies    return (sum1 == x) # Driver codex = 153print(isArmstrong(x)) x = 1253print(isArmstrong(x))
True
False
Time complexity: O((logn)2)
Auxiliary Space: O(1)
Method: A positive integer is called an Armstrong number if an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example, 153 is an Armstrong number because   153 = 1*1*1 + 5*5*5 + 3*3*3    The while loop iterates like first, it checks if the number is not equal to zero or not. if it is not equal to zero then enter into the loop and find the reminder of number ex: 153%10 gives reminder 3. In the next step add the cube of a number to the sum1(3*3*3). Then the step gives the quotient of the number (153//10=15). this loop will continue till the given number is equal to zero. 
Python3
# python 3 program# to check whether the given number is armstrong or not# without using power function n = 153  # or n=int(input()) -> taking input from users = n  # assigning input value to the s variableb = len(str(n))sum1 = 0while n != 0:    r = n % 10    sum1 = sum1+(r**b)    n = n//10if s == sum1:    print("The given number", s, "is armstrong number")else:    print("The given number", s, "is not armstrong number") # This code is contributed by Gangarajula Laxmi
The given number 153 is armstrong number
Please refer complete article on Program for Armstrong Numbers for more details!
Time complexity: O(logn)
Auxiliary Space: O(1)
akash_1998
laxmigangarajula03
hasani
rajsan250
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
BufferedReader ready() method in Java with Examples - GeeksforGeeks

28 May, 2020
The ready() method of BufferedReader class in Java is used to verify whether the buffer stream is ready to be read or not. A buffer stream is said to be ready in two cases either the buffer is not empty or the main stream is ready.
Syntax:
public boolean ready() 
          throws IOException

Overrides: This method overrides ready() method of Reader class.
Parameters: This method does not accept any parameter.
Return value: This method returns true if the stream is ready to be read otherwise it returns false.
Exceptions: This method throws IOException if an I/O error occurs.
Below programs illustrate ready() method in BufferedReader class in IO package:
Program 1: Assume the existence of the file “c:/demo.txt”.
// Java program to illustrate// BufferedReader ready() method  import java.io.*;  public class GFG {    public static void main(String[] args)    {          // Read the stream 'demo.txt'        // containing text "GEEKS"        FileReader fileReader            = new FileReader(                "c:/demo.txt");          // Convert fileReader to        // bufferedReader        BufferedReader buffReader            = new BufferedReader(                fileReader);          boolean b = buffReader.ready();          System.out.println(b);          while (b) {            System.out.println(                (char)buffReader.read());            b = buffReader.ready();        }          System.out.println(b);    }}
Program 2: Assume the existence of the file “c:/demo.txt”.
// Java program to illustrate// BufferedReader ready() method  import java.io.*;  public class GFG {    public static void main(String[] args)    {          // Read the stream 'demo.txt'        // containing text "GEEKSFORGEEKS"        FileReader fileReader            = new FileReader(                "c:/demo.txt");          // Convert fileReader to        // bufferedReader        BufferedReader buffReader            = new BufferedReader(                fileReader);          boolean b = buffreader.ready();          System.out.println(b);          while (b) {            System.out.println(                (char)buffReader.read());            b = buffReader.ready();        }          System.out.println(b);    }}
References: https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#ready()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
LinkedList in Java
Overriding in Java
Queue Interface In Java
Python Design Patterns - State

It provides a module for state machines, which are implemented using subclasses, derived from a specified state machine class. The methods are state independent and cause transitions declared using decorators.
The basic implementation of state pattern is shown below −
class ComputerState(object):

   name = "state"
   allowed = []

   def switch(self, state):
      """ Switch to new state """
      if state.name in self.allowed:
         print 'Current:',self,' => switched to new state',state.name
         self.__class__ = state
      else:
         print 'Current:',self,' => switching to',state.name,'not possible.'

   def __str__(self):
      return self.name

class Off(ComputerState):
   name = "off"
   allowed = ['on']

class On(ComputerState):
   """ State of being powered on and working """
   name = "on"
   allowed = ['off','suspend','hibernate']

class Suspend(ComputerState):
   """ State of being in suspended mode after switched on """
   name = "suspend"
   allowed = ['on']

class Hibernate(ComputerState):
   """ State of being in hibernation after powered on """
   name = "hibernate"
   allowed = ['on']

class Computer(object):
   """ A class representing a computer """
   
   def __init__(self, model='HP'):
      self.model = model
      # State of the computer - default is off.
      self.state = Off()
   
   def change(self, state):
      """ Change state """
      self.state.switch(state)

if __name__ == "__main__":
   comp = Computer()
   comp.change(On)
   comp.change(Off)
   comp.change(On)
   comp.change(Suspend)
   comp.change(Hibernate)
   comp.change(On)
   comp.change(Off)
The above program generates the following output −

    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
C Program to find two’s complement for a given number

The two’s complement for a given binary number can be calculated in two methods, which are as follows −
Method 1 − Convert the given binary number into one’s complement and then, add 1.
Method 1 − Convert the given binary number into one’s complement and then, add 1.
Method 2 − The trailing zero’s after the first bit set from the Least Significant Bit (LSB) including one that remains unchanged and remaining all should be complementing.
Method 2 − The trailing zero’s after the first bit set from the Least Significant Bit (LSB) including one that remains unchanged and remaining all should be complementing.
The logic to find two’s complement for a given binary number is as follows −
for(i = SIZE - 1; i >= 0; i--){
   if(one[i] == '1' && carry == 1){
      two[i] = '0';
   }
   else if(one[i] == '0' && carry == 1){
      two[i] = '1';
      carry = 0;
   } else {
      two[i] = one[i];
   }
}
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s\n",num, two);
The logic for finding one’s complement from a given binary number is −
for(i = 0; i < SIZE; i++){
   if(num[i] == '0'){
      one[i] = '1';
   }
   else if(num[i] == '1'){
      one[i] = '0';
   }
}
one[SIZE] = '\0';
printf("Ones' complement of binary number %s is %s\n",num, one);
Following is the C program to find two’s complement for a given number −
 Live Demo
#include<stdio.h>
#include<stdlib.h>
#define SIZE 8
int main(){
   int i, carry = 1;
   char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
   printf("Enter the binary number\n");
   gets(num);
   for(i = 0; i < SIZE; i++){
      if(num[i] == '0'){
         one[i] = '1';
      }
      else if(num[i] == '1'){
         one[i] = '0';
      }
   }
   one[SIZE] = '\0';
   printf("Ones' complement of binary number %s is %s\n",num, one);
   for(i = SIZE - 1; i >= 0; i--){
      if(one[i] == '1' && carry == 1){
         two[i] = '0';
      }
      else if(one[i] == '0' && carry == 1){
         two[i] = '1';
         carry = 0;
      }
      else{
         two[i] = one[i];
      }
   }
   two[SIZE] = '\0';
   printf("Two's complement of binary number %s is %s\n",num, two);
   return 0;
}
When the above program is executed, it produces the following result −
Enter the binary number
1000010
Ones' complement of binary number 1000010 is 0111101
Two's complement of binary number 1000010 is 0111110
Python PIL | Image.getdata() - GeeksforGeeks

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
getdata() Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).
Syntax: Image.getdata(band=None)
Parameters:
band – What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the “R” band from an “RGB” image).
Returns type: A sequence-like object.
Image Used:
     # importing Image module from PIL package from PIL import Image    # opening a  image im = Image.open(r"C:\Users\System-Pc\Desktop\lion.png").convert("L")    # getting colors # multiband images (RBG) im1 = Image.Image.getdata(im)    print(im1) 
Output:
ImagingCore object at 0x0000026E11CD52D0

Another example:Here we change image.Image Used
# importing Image module from PIL package from PIL import Image    # opening a  image im = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg").convert("L")    # getting colors # multiband images (RBG) im1 = Image.Image.getdata(im)    print(im1) 
Output:
ImagingCore object at 0x0000029BA596C230

Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to exclude specific extension in Get-ChildItem in PowerShell?

To exclude specific extensions, you need to use –Exclude parameter in Get-ChildItem.
For example, as shown below when we run command, it will exclude .html files and display the rest.
Get-ChildItem D:\Temp\ -Recurse -Exclude *.html
Directory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       24-11-2018     11:31                LGPO
    Directory: D:\Temp\LGPO
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       01-06-2017     03:22         410088 LGPO.exe
-a----       01-06-2017     02:25         638115 LGPO.pdf
    Directory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       07-05-2018     23:00            301 cars.xml
-a----       08-12-2017     10:16            393 style.css
-a----       08-12-2017     11:29           7974 Test.xlsx
-a----       25-10-2017     08:13            104 testcsv.csv
You can exclude multiple extensions as well.
In the below example, we will exclude html and xml extensions.
Get-ChildItem D:\Temp\ -Recurse -Exclude *.html,*.xml

Directory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       24-11-2018     11:31                LGPO
    Directory: D:\Temp\LGPO
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       01-06-2017     03:22         410088 LGPO.exe
-a----       01-06-2017     02:25         638115 LGPO.pdf
    Directory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       08-12-2017     10:16            393 style.css
-a----       08-12-2017     11:29           7974 Test.xlsx
-a----       25-10-2017     08:13            104 testcsv.csv
Adding Borders to Tables in CSS

The CSS border property is used to define a border for an element. The syntax of CSS border property is as follows−
Selector {
   border: /*value*/
}
The following examples illustrate CSS border property−
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table {
   margin: 1em;
   border: 3px double green;
   border-right-style: dashed;
   border-left-width: 17px;
   border-bottom-color: orange;
}
td {
   font-size: 24px;
   border-right-style: dotted;
   border-width: 3px;
   border-right-color: red;
}
</style>
</head>
<body>
<table>
<tr>
<td>demo</td>
<td>text</td>
</tr>
<tr>
<td>goes</td>
<td>here</td>
</tr>
</table>
</body>
</html>
This gives the following output−
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table {
   margin: auto;
   caption-side: bottom;
   border: 2px dashed black;
}
td {
   border: 2px solid midnightblue;
   text-align: center;
}
td[colspan] {
   box-shadow: inset 0 0 10px lightblue;
   text-align: center;
}
caption {
   font-size: 16px;
   font-weight: bold;
}
</style>
</head>
<body>
<h2<Ranking</h2>
<table>
<caption>Men's ODI Player Ranking</caption>
<tr>
<th>Player</th>
<th>Rank</th>
</tr>
<tr>
<td>Virat Kohli</td>
<td>1</td>
</tr>
<tr>
<td>Rohit Sharma</td>
<td>2</td>
</tr>
<tr>
<td>Babar Azam</td>
<td>3</td>
</tr>
<tr>
<td>Ross Taylor</td>
<td>4</td>
</tr>
<tr>
<td colspan="2">Sept2019</td>
</tr>
</table>
</body>
</html>
This gives the following output−
Pandas - Removing Duplicates

Duplicate rows are rows 
that have been registered more than one time.

      Duration          Date  Pulse  Maxpulse  Calories
  0         60  '2020/12/01'    110       130     409.1
  1         60  '2020/12/02'    117       145     479.0
  2         60  '2020/12/03'    103       135     340.0
  3         45  '2020/12/04'    109       175     282.4
  4         45  '2020/12/05'    117       148     406.0
  5         60  '2020/12/06'    102       127     300.0
  6         60  '2020/12/07'    110       136     374.0
  7        450  '2020/12/08'    104       134     253.3
  8         30  '2020/12/09'    109       133     195.1
  9         60  '2020/12/10'     98       124     269.0
  10        60  '2020/12/11'    103       147     329.3
  11        60  '2020/12/12'    100       120     250.7
  12        60  '2020/12/12'    100       120     250.7
  13        60  '2020/12/13'    106       128     345.3
  14        60  '2020/12/14'    104       132     379.3
  15        60  '2020/12/15'     98       123     275.0
  16        60  '2020/12/16'     98       120     215.2
  17        60  '2020/12/17'    100       120     300.0
  18        45  '2020/12/18'     90       112       NaN
  19        60  '2020/12/19'    103       123     323.0
  20        45  '2020/12/20'     97       125     243.0
  21        60  '2020/12/21'    108       131     364.2
  22        45           NaN    100       119     282.0
  23        60  '2020/12/23'    130       101     300.0
  24        45  '2020/12/24'    105       132     246.0
  25        60  '2020/12/25'    102       126     334.5
  26        60      20201226    100       120     250.0
  27        60  '2020/12/27'     92       118     241.0
  28        60  '2020/12/28'    103       132       NaN
  29        60  '2020/12/29'    100       132     280.0
  30        60  '2020/12/30'    102       129     380.3
  31        60  '2020/12/31'     92       115     243.0


By taking a look at our test data set, we can assume that row 11 and 12 are duplicates.
To discover duplicates, we can use the duplicated() method.
The duplicated() method returns a Boolean values for each row:
Returns True for every row that is a duplicate, othwerwise False:
To remove duplicates, use the drop_duplicates() method.
Remove all duplicates:
Remember: The (inplace = True) will 
  make sure that the method does NOT return a new DataFrame, but it will remove all 
  duplicates from the original DataFrame.
Insert the correct syntax for removing rows with empty cells.
df.()

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
PHP - Function scandir()

array scandir ( string $directory [, int $sorting_order [, resource $context]] );

It returns an array of files and directories from the passed  directory.
directory(Required)
The directory that will be scanned.
sorting_order(Optional)
It specifies the sort order. Default is 0 (ascending). If set to 1, it indicates descending order.
context(Optional)
It specifies the context of the directory handle. Context is a set of options that can modify the behavior of a stream.
It returns an array of filenames on success, or FALSE on failure.
Following is the usage of this function −
<?php
   $dir    = '/newfolder';
   $files1 = scandir($dir);
   $files2 = scandir($dir, 1);
   
   print_r($files1);
   print_r($files2);
?> 
This will produce the following result −
Array (
   [0] => .
   [1] => ..
   [2] => abc.php
   [3] => bbc.txt
   [4] => somedir
)
Array (
   [0] => somedir
   [1] => indiabbc.txt
   [2] => status999.php
   [3] => ..
   [4] => .
)


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Performing total of a column in a temporary column in SAP

You need to perform select again on your query. Here is the sample
SELECT DATE, FUND_ID, PPT_ID, SOURCE_ID, AMOUNT, SUM (AMOUNT) as TOTAL
FROM (
   SELECT
   AD.CHV_DATE.DATE,
   AD.CHV_FUND.FUND_ID,
   AD.CHV_PARTICT.PPT_ID,
   AD.CHV_PARTICT.SOURCE_ID,
   SUM (AD.CHV_PARTICT.AMOUNT),
FROM
   AD.CHV_DATE,
   AD.CHV_FUND,
   AD.CHV_PARTICT,
   AD.CHV_SOURCE
WHERE
   DC.CHV_SOURCE.FUND_ID=AD.CHV_FUND.FUND_ID
AND (DC.CHV_SOURCE.DATE=AD.CHV_DATE.DATE)
AND (DC.CHV_PARTICT.PPT_ID=AD.CHV_SOURCE.PPT_ID)
AND (
   AD.CHV_DATE.DATE IN ('2017-08-02')  
   AND
   AD.CHV_PARTICT.PPT_ID IN ('PPT0449')
)
GROUP BY
   AD.CHV_DATE.DATE,
   AD.CHV_FUND.FUND_ID,
   AD.CHV_PARTICT.PPT_ID,
   AD.CHV_SOURCE.SOURCE_ID)
GROUP by DATE, FUND_ID, PPT_ID, SOURCE_ID, AMOUNT
Java Program to get the count of child nodes of any node in JTree

Use the getChildCount() method in Java to get the count of child nosed of any node i.e. even if it’s a root node or not.
Let’s say we want the count of child nodes for node 1, which is not a root node, therefore −
node1.getChildCount()
The following is an example to get the count of child nodes of any node −
package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      DefaultMutableTreeNode node = new DefaultMutableTreeNode("Website");
      DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Videos");
      DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Tutorials");
      DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("QA");
      DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Tools");
      node.add(node1);
      node.add(node2);
      node.add(node3);
      node.add(node4);
      DefaultMutableTreeNode one = new DefaultMutableTreeNode("PHP Videos");
      DefaultMutableTreeNode two = new DefaultMutableTreeNode("HTML5 Videos");
      DefaultMutableTreeNode three = new DefaultMutableTreeNode("Blockchain Videos");
      DefaultMutableTreeNode four = new DefaultMutableTreeNode("Java");
      DefaultMutableTreeNode five = new DefaultMutableTreeNode("DBMS");
      DefaultMutableTreeNode six = new DefaultMutableTreeNode("CSS");
      DefaultMutableTreeNode seven = new DefaultMutableTreeNode("MongoDB");
      DefaultMutableTreeNode eight = new DefaultMutableTreeNode("Python QA");
      DefaultMutableTreeNode nine = new DefaultMutableTreeNode("jQuery QA");
      DefaultMutableTreeNode ten = new DefaultMutableTreeNode("Photo Editing Tool");
      node1.add(one);
      node1.add(two);
      node1.add(three);
      node2.add(four);
      node2.add(five);
      node2.add(six);
      node2.add(seven);
      node3.add(eight);
      node3.add(nine);
      node4.add(ten);
      JTree tree = new JTree(node);
      for (int i = 0; i < tree.getRowCount(); i++) {
         tree.expandRow(i);
      }
      tree.putClientProperty("JTree.lineStyle", "Angled");
      System.out.println("Number of children of node1 (Videos) = " + node1.getChildCount());
      System.out.println("Number of children of node2 (Tutorials) = " + node2.getChildCount());
      System.out.println("Number of children of node3 (QA) = " + node3.getChildCount());
      System.out.println("Number of children of node4 (Tools) = " + node4.getChildCount());
      tree.setRowHeight(25);
      frame.add(tree);
      frame.setSize(600,450);
      frame.setVisible(true);
   }
}
The Console displays the count of each node −
The JTree is as follows
Set the width of an element to 75% in Bootstrap

To set the width of an element to 75%, use the .w-75 class in Bootstrap.
You can try to run the following code to set element’s width −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h3>Set element width</h3>
         <div class = "w-100 bg-danger">Normal width</div>
         <div class = "w-75 bg-warning">Width is 75%</div>
   </body>
</html>
How to use a List as a key of a Dictionary in Python 3?

17 May, 2020
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below .
If the Python dictionaries just iterate over their keys to check if the given keys are present or not it would take O(N) time. But python dictionaries take O(1) to check if the key is present or not. So, how dictionaries search the key, for every key it generates a hash value for the key and by this hash value, it can track its elements.
Lists are mutable objects which means that we can change values inside a list append or delete values of the list . So if a hash function is generated from a list and then the items of the lists changed the dictionary will generate a new hash value for this list and could not find it.
For example, If the list is a = [1, 2, 3, 4, 5] and supposes hash of a list is the sum of values inside the list. So hash(a) = 15. Now we append 6 to a . So a = [1, 2, 3, 4, 5, 6] hash(a) = 21. So hash value of a changed. Therefore it can not be found inside the dictionary.
Another problem is different lists with the same hash value. If b = [5, 5, 5] hash(b) = 15. So if a (From the above example with the same hash value) is present is inside the dictionary, and if we search for b. Then the dictionary may give us the wrong result.
We can change the list into immutable objects like string or tuple and then can use it as a key.  Below is the implementation of the approach. 
# Declaring a dictionaryd = {}   # This is the list which we are # trying to use as a key to# the dictionarya =[1, 2, 3, 4, 5]  # converting the list a to a stringp = str(a)d[p]= 1  # converting the list a to a tupleq = tuple(a) d[q]= 1  for key, value in d.items():    print(key, ':', value)
 Output:
[1, 2, 3, 4, 5] : 1
(1, 2, 3, 4, 5) : 1
python-dict
Python
python-dict
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Difference between module.exports and exports in Node.js

06 Jul, 2022
The module is a plain JavaScript Object representing the current module. It is local to each module and also it is private. It has exports property which is a plain JavaScript variable, set to module.exports. At the end of the file, Node.js return module.exports to the required function.
When we want to export a single class/variable/function from one module to another module, we use module.exports.
Example: Create two files calculator.js and operation.js and export the Arithmetic class from calculator.js to operation.js using module.exports method. Here, we have created a class Arithmetic and exported the whole class using module.exports.
Filename: calculator.js
Javascript
class Arithmetic {    constructor(a, b) {        this.a = a;        this.b = b;    }     add() {        return this.a + this.b;    }    subtract() {        return this.a - this.b;    }     multiply() {        return this.a * this.b;    }     divide() {        if (this.b != 0) {            return this.a / this.b;        }        return "divided by zero !!!!";    }}; module.exports = Arithmetic;
Filename: operation.js
Javascript
const Arithmetic = require('./calculator.js'); const op = new Arithmetic(100,40); console.log(`Addition -> ${op.add()}`);console.log(`subtraction -> ${op.subtract()}`);console.log(`Multiplication -> ${op.multiply()}`);console.log(`Division -> ${op.divide()}`);
Run the operation.js file using the following command:
node operation.js
Output:
Using module.exports 
When we want to export multiple variables/functions from one module to another, we use exports.
Example: Create two files calculator.js and operation.js and export multiple functions from calculator.js file. 
Filename: calculator.js
Javascript
exports.add = (a, b) => a + b;exports.subtract = (a, b) => a - b;exports.multiply = (a, b) => a * b;exports.divide = (a, b) => {    if (b != 0) {        return a / b;    }    return `Divided by zero !!!`;}
Filename: operation.js
Javascript
const Arithmetic = require('./calculator.js'); console.log(`Addition -> ${Arithmetic.add(100,40)}`);console.log(`subtraction -> ${Arithmetic.subtract(100,40)}`);console.log(`Multiplication -> ${Arithmetic.multiply(100,40)}`);console.log(`Division -> ${Arithmetic.divide(100,40)}`);
Run the operation.js file using the following command:
node operation.js
Output:
Using exports
Key differences between module.exports and exports: 
S.no
Module.exports
Exports
1
2.
SAKSHIKULSHRESHTHA
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the outer html of an element using jQuery ?

02 Jun, 2020
Sometimes, there is a need to get the entire HTML element by its id and not merely its contents, for doing so, we shall use the HTML DOM outerHTML Property to get the outer HTML of HTML element.
Syntax: 
document.getElementById("your-element-id").outerHTML)

You can use a variable and initialize it to the above to get the value of the outer HTML element. Below is an example that illustrates how to fetch the outer HTML element of an HTML element and store it in a variable newVar.
Example 1:  In this example, it has a div that encloses a paragraph with id = “demo”. When the on-screen button is pressed the JavaScript pushes an alert message on the browser window with the outer HTML of the HTML element with the given id. The myFunction uses the getElementbyId function to fetch the element with the given id and then fetches that elements outerHTML. If an id is given such that there are multiple HTML elements with that id or there are none, then the outerHTML will throw an error as its being called on a null value.
HTML
<!DOCTYPE html><html>    <head>    </head>    <body>        <div id="demo">              <p>This is the text inside</p>          </div>          <button onclick="myFunction()">Try it</button>          <script>            function myFunction() {                var newVar =                   document.getElementById("demo").outerHTML;                alert(newVar);            }        </script>    </body></html>
Output:
<div id="demo">
    <p>This is the text inside</p>
</div>
Example 2:  This example illustrates that the outerHTML DOM displays only the HTML element whose id is given and not its parent 
HTML
<!DOCTYPE html><html>    <head>    </head>    <body>        <div>            <p id="demo">This is the text inside</p>          </div>          <button onclick="myFunction()">Try it</button>          <script>            function myFunction() {                var newVar =                  document.getElementById("demo").outerHTML;                alert(newVar);            }        </script>    </body></html>
 Output:
<p id="demo">This is the text inside</p>
JavaScript-Misc
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program for Bubble Sort

13 Jun, 2022
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Java
Java
// Java program for implementation of Bubble Sortclass BubbleSort{    void bubbleSort(int arr[])    {        int n = arr.length;        for (int i = 0; i < n-1; i++)            for (int j = 0; j < n-i-1; j++)                if (arr[j] > arr[j+1])                {                    // swap temp and arr[i]                    int temp = arr[j];                    arr[j] = arr[j+1];                    arr[j+1] = temp;                }    }     /* Prints the array */    void printArray(int arr[])    {        int n = arr.length;        for (int i=0; i<n; ++i)            System.out.print(arr[i] + " ");        System.out.println();    }     // Driver method to test above    public static void main(String args[])    {        BubbleSort ob = new BubbleSort();        int arr[] = {64, 34, 25, 12, 22, 11, 90};        ob.bubbleSort(arr);        System.out.println("Sorted array");        ob.printArray(arr);    }}/* This code is contributed by Rajat Mishra */
Time Complexity: O(n2)Auxiliary Space: O(1)
Please refer complete article on Bubble Sort for more details!
amankr0211
BubbleSort
Java Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Java program to count the occurrence of each character in a string using Hashmap
Iterate through List in Java
How to Iterate HashMap in Java?
Merge Sort
QuickSort
Insertion Sort
Selection Sort Algorithm
std::sort() in C++ STL
How to use JSONobject to parse JSON in Android?

This example demonstrates how do I use JSONObject to parse JSON in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      android:textStyle="bold"
      android:textSize="24sp"
      android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
   public static final String JSON_STRING="{\"Employee\":{\"Name\":\"Niyaz\",\"Salary\":56000}}";
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      try {
         JSONObject emp = (new JSONObject(JSON_STRING)).getJSONObject("Employee");
         String empName = emp.getString("Name");
         int empSalary = emp.getInt("Salary");
         String string = "Employee Name: "+empName+"\n"+"Employee Salary: "+empSalary;
         textView.setText(string);
      } catch (JSONException e) {
         e.printStackTrace();
      }
   }
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Differences between static and non-static methods in Java

A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.
A static method is also called a class method and is common across the objects of the class and this method can be accessed using class name as well.
Any method of a class which is not static is called non-static method or an instance method.
Following are the important differences between static and non-static method.
JavaTester.java
public class JavaTester {
   public static void main(String args[]) {
      Tiger.roar();
      Tiger tiger = new Tiger();
      tiger.eat();
   }
}
class Tiger {
   public void eat(){
      System.out.println("Tiger eats");
   }
   public static void roar(){
      System.out.println("Tiger roars");
   }
}
Output
Tiger roars
Tiger eats
Python | Pandas Series.to_json()

05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.to_json() function is used to convert the object to a JSON string. Also note that NaN’s and None will be converted to null and datetime objects will be converted to UNIX timestamps.
Syntax: Series.to_json(path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit=’ms’, default_handler=None, lines=False, compression=’infer’, index=True)
Parameter :path_or_buf : File path or object. If not specified, the result is returned as a string.orient : Indication of expected JSON string format.date_format : None, ‘epoch’, ‘iso’}double_precision : The number of decimal places to use when encoding floating point values.force_ascii : Force encoded string to be ASCII.date_unit : string, default ‘ms’ (milliseconds)default_handler : callable, default Nonelines : bool, default Falsecompression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}
Returns : Json string
Example #1: Use Series.to_json() function to convert the given series object to JSON string.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe/Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.to_json() function to convert the given series object to JSON string.
# convert to JSON stringsr.to_json()
Output :
As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string.
Example #2: Use Series.to_json() function to convert the given series object to JSON string.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])  # Print the seriesprint(sr)
Output :
Now we will use Series.to_json() function to convert the given series object to JSON string.
# convert to JSON stringsr.to_json()
Output :
As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to search the max value of an attribute in an array object ?

10 Jun, 2022
Maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method is by using the Math.max.apply() method.
Example 1: In this example, the array is traversed and the required values of the object are compared for each index of the array.
javascript
// Array of objectvar arr = [    {      a: 10,      b: 25    },    {        a: 30,        b: 5    },    {        a: 20,        b: 15    },    {        a: 50,        b: 35    },    {        a: 40,        b: 45    },  ];     // Returns max value of  // attribute 'a' in array  function fun(arr){    var maxValue = Number.MIN_VALUE;     for(var i=0;i<arr.length;i++){        if(arr[i].a>maxValue){        maxValue = arr[i].a;       }    }    return maxValue;  }   var maxValue = fun(arr);  console.log(maxValue);
Output:
50
Example 2: In this example, we find the max value of an attribute by using Math.max.apply() function. It has two parameters:
thisarray-like object
this
array-like object
Syntax:
Math.max.apply(thisArg, [ argsArray])
More information can be found at https://developer.mozilla.org/
javascript
var arr = [    {      a: 10,      b: 25    },    {        a: 30,        b: 5    },    {        a: 20,        b: 15    },    {        a: 50,        b: 35    },    {        a: 40,        b: 45    },  ];   var maxValue = Math.max.apply(null,    arr.map(function(o) { return o.a; }));   console.log(maxValue);
Output:
50
Example-3: In this example we will using reduce() method with which all the values will be compared and then at last the final value will be stored which further will be stored in a variable which will be output over console.
Javascript
let array = [  { a: 1, b: 2 },  { a: 2, b: 4 },  { a: 3, b: 6 },  { a: 4, b: 8 },  { a: 5, b: 10 },  { a: 6, b: 12 },]; let maxValue = array.reduce((acc, value) => {  return (acc = acc > value.b ? acc : value.b);}, 0); console.log(maxValue); // This code is contributed by Aman Singla...
Output:
 12
amansingla
javascript-array
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Index.nunique()

18 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.nunique() function return number of unique elements in the object. It returns a scalar value which is the count of all the unique values in the Index. By default the NaN values are not included in the count. If dropna parameter is set to be False then it includes NaN value in the count.
Syntax: Index.nunique(dropna=True)
Parameters :dropna : Don’t include NaN in the count.
Returns : nunique : int
Example #1: Use Index.nunique()() function to find the count of unique values in the Index. Do not include NaN values in the count.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug',                        'Mastiff', None, 'Beagle'])  # Print the Indexidx
Output :
Let’s find the count of unique values in the Index.
# to find the count of unique values.idx.nunique(dropna = True)
Output :As we can see in the output, the function has returned 4 indicating that there are only 4 unique values in the Index. Example #2: Use Index.nunique() function find out all the unique values in the Index. Also include the missing values i.e. NaN values in the count.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug',                        'Mastiff', None, 'Beagle'])  # Print the Indexidx
Output :
Let’s find the count of unique values in the Index.
# to find the count of unique values.idx.nunique(dropna = False)
Output :As we can see in the output, the function has returned 5 indicating that there are only 5 unique values in the Index. We have also included the missing values in the count.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check if a set contains an element in Python?

28 Nov, 2021
In this article, we will discuss how to check if a set contains an element in python.
This is an membership operator used to check whether the given value is present in set or not. It will return True if the given element is present in set , otherwise False.
Syntax:
element in set
where
set is an input set
element is the value to be checked
Example: Check if an element is present in a set
Python3
# import random moduleimport random  # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076}    # check 7058print(7058 in data)  # check 7059print(7059 in data)  # check 7071print(7071 in data)
Output:
True
True
False
This is an membership operator used to check whether the given value is present in set or not. It will return True if the given element is not present in set, otherwise False
Syntax:
element not in set
where,
set is an input set
element is the value to be checked
Example: Check if an element is present in a set
Python3
# import random moduleimport random  # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076}    # check 7058print(7058 not in data)  # check 7059print(7059 not in data)  # check 7071print(7071 not in data)
Output:
False
False
True
Picked
Python set-programs
python-set
Python
Python Programs
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.