code-rag-bench/online-tutorials huggingface dataset:
PostgreSQL – NUMERIC Data Type

28 Aug, 2020
PostgreSQL supports the NUMERIC type for storing numbers with a very large number of digits. Generally NUMERIC type are used for the monetary or amounts storage where precision is required.
Syntax: NUMERIC(precision, scale)

Where,
     Precision: Total number of digits.
     Scale: Number of digits in terms of a fraction.
The NUMERIC value can have up to 131, 072 digits before the decimal point of 16, 383 digits after the decimal point.It is allowed to have a zero or positive scale, as the syntax defined below for a NUMERIC column with the scale of zero:
Syntax: NUMERIC(precision)
If you eliminate both precision and scale, there is no limit to the precision or the scale and the syntax will be as below:
Syntax: NUMERIC
The NUMERIC and DECIMAL types are equivalent in PostgreSQL and upto the SQL standard.It is recommended to not use the NUMERIC type, if precision is not required as the calculation on NUMERIC values is slower than integers, floats, and double precision.
Example 1:Create a new table named products with the below commands:
CREATE TABLE IF NOT EXISTS products (
    id serial PRIMARY KEY,
    name VARCHAR NOT NULL,
    price NUMERIC (5, 2)
);
Now insert some products with the prices whose scales exceed the scale declared in the price column:
INSERT INTO products (name, price)
VALUES
    ('Phone', 100.2157), 
    ('Tablet', 300.2149);
As the scale of the price column is 2, PostgreSQL rounds the value 100.2157 up to 100.22 and rounds the value 300.2149 down to 300.21The below query returns all rows of the products table:
SELECT
    *
FROM
    products;
Output:
Example 2:Create a new table named products with the below commands:
CREATE TABLE IF NOT EXISTS employee_salary(
    id serial PRIMARY KEY,
    name VARCHAR NOT NULL,
    salary NUMERIC (10, 2)
);
Now insert some products with the prices whose scales exceed the scale declared in the price column:
INSERT INTO employee_salary(name, salary)
VALUES
    ('Raju', 57896.2277),
    ('Abhishek', 84561.3657),
    ('Nikhil', 55100.11957), 
    ('Ravi', 49300.21425849);
As the scale of the price column is 2, PostgreSQL rounds the value 57896.2277 up to 57896.22 for Raju, the value 84561.3657 down to 84561.36 for Abhishek, the value 55100.11957 to 55100.12 for Nikhil and the value 49300.21425849 to 49300.21 for Ravi.The below query returns all rows of the products table:
SELECT
    *
FROM
    employee_salary;
Output:
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
Stream mapToDouble() in Java with examples

06 Dec, 2018
Stream mapToDouble (ToDoubleFunction mapper) returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
Stream mapToDouble (ToDoubleFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)

Where, A sequence of primitive double-valued
elements and T is the type of stream elements. 
mapper is a stateless function which is applied
to each element and the function returns the new stream.

Example 1 : mapToDouble() with operation of selecting elements satisfying given function.
// Java code for Stream mapToDouble// (ToDoubleFunction mapper) to get a// DoubleStream by applying the given function// to the elements of this stream.import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a list of Strings        List<String> list = Arrays.asList("10", "6.548", "9.12",                                                    "11", "15");          // Using Stream mapToDouble(ToDoubleFunction mapper)        // and displaying the corresponding DoubleStream        list.stream().mapToDouble(num -> Double.parseDouble(num))                    .filter(num -> (num * num) * 2 == 450)                    .forEach(System.out::println);    }}
Output :
15.0

Example 2 : mapToDouble() with operation of returning a stream with square of string length.
// Java code for Stream mapToDouble// (ToDoubleFunction mapper) to get a// DoubleStream by applying the given function// to the elements of this stream.import java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating a list of Strings        List<String> list = Arrays.asList("CSE", "JAVA", "gfg",                                                    "C++", "C");          // Using Stream mapToDouble(ToDoubleFunction mapper)        // and displaying the corresponding DoubleStream        // which contains square of length of each element in        // given Stream        list.stream().mapToDouble(str -> str.length() * str.length())                     .forEach(System.out::println);    }}
Output :
9.0
16.0
9.0
9.0
1.0

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Extract CSS tag from a given HTML using Python

24 Oct, 2020
Prerequisite: Implementing Web Scraping in Python with BeautifulSoup
In this article, we are going to see how to extract CSS from an HTML document or URL using python.
 Module Needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4

requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests

Approach:
Import module
Create an HTML document and specify the CSS tag into the code
Pass the HTML document into the Beautifulsoup() function
Now traverse the tag with the select() method.
Implementation:
Python3
# import modulefrom bs4 import BeautifulSoup  # Html dochtml_doc = """<html><head><title>Geeks</title></head><body><h2>paragraphs</h2>  <p>Welcome geeks.</p>    <p>Hello geeks.</p>  <a class="example" href="www.geeksforgeeks.com" id="dsx_23">java</a><a class="example" href="www.geeksforgeeks.com/python"  id="sdcsdsdf">python</a></body></html>"""soup = BeautifulSoup(html_doc, "lxml")  # traverse CSS from soupprint("display by CSS class:")print(soup.select(".example"))
Output:
display by CSS class:
[<a class="example" href="www.geeksforgeeks.com" id="dsx_23">java</a>, 
<a class="example" href="www.geeksforgeeks.com/python" id="sdcsdsdf">python</a>]

Now let’s get the CSS tag with URL:
Python3
# import modulefrom bs4 import BeautifulSoupimport requests  # link for extract html data# Making a GET request       def getdata(url):    r=requests.get(url)    return r.texthtml_doc = getdata('https://www.geeksforgeeks.org/')soup = BeautifulSoup(html_doc,"lxml")  # traverse CSS from soup  print("\nTags by CSS class:")print(soup.select(".header-main__wrapper"))
Output:
python-utility
Web-scraping
Python
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
How to deallocate memory without using free() in C?

28 May, 2017
Question: How to deallocate dynamically allocate memory without using “free()” function.
Solution: Standard library function realloc() can be used to deallocate previously allocated memory. Below is function declaration of “realloc()” from “stdlib.h”
void *realloc(void *ptr, size_t size);
If “size” is zero, then call to realloc is equivalent to “free(ptr)”. And if “ptr” is NULL and size is non-zero then call to realloc is equivalent to “malloc(size)”.
Let us check with simple example.
/* code with memory leak */#include <stdio.h>#include <stdlib.h>  int main(void){    int *ptr = (int*)malloc(10);      return 0;}
Check the leak summary with valgrind tool. It shows memory leak of 10 bytes, which is highlighed in red colour.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
  [narendra@ubuntu]$ valgrind –leak-check=full ./free
  ==1238== LEAK SUMMARY:
  ==1238==    definitely lost: 10 bytes in 1 blocks.
  ==1238==      possibly lost: 0 bytes in 0 blocks.
  ==1238==    still reachable: 0 bytes in 0 blocks.
  ==1238==         suppressed: 0 bytes in 0 blocks.
[narendra@ubuntu]$

Let us modify the above code.
#include <stdio.h>#include <stdlib.h>  int main(void){    int *ptr = (int*) malloc(10);      /* we are calling realloc with size = 0 */    realloc(ptr, 0);           return 0;}
Check the valgrind’s output. It shows no memory leaks are possible, highlighted in red color.
  [narendra@ubuntu]$ valgrind –leak-check=full ./a.out
  ==1435== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
  ==1435== malloc/free: in use at exit: 0 bytes in 0 blocks.
  ==1435== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.
  ==1435== For counts of detected errors, rerun with: -v
  ==1435== All heap blocks were freed — no leaks are possible.
  [narendra@ubuntu]$

This article is compiled by “Narendra Kangralkar“ and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Dynamic Memory Allocation
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Enumeration (or enum) in C
C Language Introduction
Power Function in C/C++
INT_MAX and INT_MIN in C/C++ and Applications
Operators in C / C++
Python Program to convert Kilometers to Miles

19 Dec, 2017
Kilometer is a unit of length in the metric system equivalent to 1000 meters.
Miles is also the unit of length equal to 1760 yards.
Example:
Input: 5.5 
Output: 3.418 

Input: 6.5
Output: 4.039

Formula:
1 kilometer equals 0.62137 miles.
Miles = kilometer * 0.62137   
Kilometer = Miles / 0.62137

# Python3 program to convert# kilometers to miles  # driver codekilometers = 5.5  # conversion factorconv = 0.621371  # calculate milesmiles = kilometers * convprint('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))  kilometers = 6.5  # calculate milesmiles = kilometers * convprint('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))
Output:
5.500 kilometers is equal to 3.418 miles
6.500 kilometers is equal to 4.039 miles

Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
HTML | <table> summary Attribute

29 May, 2019
The HTML <table> summary Attribute is used to specify the summary of the table content.
Syntax:
<table summary="text">
Attribute Values:
text: It holds the summary of the table content.
Note: The <table> summary Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML table summary Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML table summary Attribute</h2>      <table border="1"            summary="It describes the author details.">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>        <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <table> summary Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
How to Insert Form Data into Database using PHP ?
HTTP headers | Content-Type
How to position a div at the bottom of its container using CSS?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Positional-only Parameter in Python3.8

03 Jul, 2020
Python introduces the new function syntax in Python3.8.2 Version, Where we can introduce the / forward slash to compare the positional only parameter which comes before the / slash and parameters that comes after * is keyword only arguments. Rest of the arguments that are come between / and * can be either positional or keyword type of argument.That means we can combine positional arguments and regular arguments in such a way all the non-positional argument comes after / slash.
Syntax:
def function(a, b, /, c, d, *, e, f):
     # Function Body
     pass 

Where a and b are positional argument, c and d can be either positional or keyword or e and f are strictly keyword type argument.
In the image given below, we can see that power function is a builtin function in Python’s math library and this function uses / slash to enable the positional only argument and now we can implement the same functionality with the help of this version.
Example #1 :In this example we can see that by using positional only argument we can implement the function with the fixed position as we can say only in built-in functions before this python version. With the help of this, we are able to make our program more robust.
# Positional-Only argument def function(a, b, /, c, d, *, e, f):    print (a, b, c, d, e, f)  function(1, 2, 3, d = 4, e = 5, f = 6) # It works finefunction(1, 2, 3, d = 4, 5, f = 6) # Error occurred
Output :
Example #2 :
# Positional-Only argument def function(a, b, /, **kwargs):    print (a, b, kwargs)  function(1, 2, a = 4, b = 5, c = 6) # It works finefunction(a = 1, 2, a = 4, b = 5, c = 6) # Error occurred
Output :
python-basics
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TypeScript - Array unshift()

unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
array.unshift( element1, ..., elementN );

element1, ..., elementN − The elements to add to the front of the array.
Returns the length of the new array. It returns undefined in IE browser.
var arr = new Array("orange", "mango", "banana", "sugar"); 
var length = arr.unshift("water"); 
console.log("Returned array is : " + arr );
console.log("Length of the array is : " + length );

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Returned array is : water,orange,mango,banana,sugar 
Length of the array is : 5


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
GATE-CS-2006 - GeeksforGeeks

02 Dec, 2021

p = a3 X x    ------------ (1)

q = (a2 + p) X x  ---------(2)

r = (a1 + q) X x  ---------(3)

result = a0 + r 
S -> S * E
S -> E
E -> F + E
E -> F
F -> id
(i) S -> S * .E
(ii) E -> F. + E
(iii) E -> F + .E 
Here, size of instruction  =  24/8 = 3 bytes.

Program Counter can shift 3 bytes at a time to jump to next instruction.

So the given options must be divisible by 3. only 600 is satisfied.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Append Pandas DataFrame to Existing CSV File?
How to Replace Values in a List in Python?
Spring - REST Controller
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
What are Inline List Items in CSS

Use Inline List Items to build a horizontal navigation bar. Set the &amp;lt;li&amp;gt; elements as inline.
You can try to run the following code to create horizontal navigation bar:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
         }
         .active {
            background-color: #4CAF50;
            color: white;
         }
         li {
            border-bottom: 1px solid #555;
            display: inline;
         }
      </style>
   </head>
   <body>
      <ul>
         <li><a href = "#home">Home</a></li>
         <li><a href = "#company" class="active">Company</a></li>
         <li><a href = "#product">Product</a></li>
         <li><a href = "#services">Services</a></li>
         <li><a href = "#contact">Contact</a></li>
      </ul>
   </body>
</html>
Get Enumeration over Java HashSet - GeeksforGeeks

03 Mar, 2021
The HashSet class implements the Set interface, backed by a hash table which is a HashMap instance. There is no assurance as to the iteration order of the set, which implies that over time, the class does not guarantee the constant order of elements. The null element is allowed by this class. The java.util.Collections class enumeration method is used to return an enumeration of the specified collection. 
To return enumeration over HashSet:
Syntax:
public static Enumeration enumeration(Collection c)
Method Used: hasMoreElements() Method.
An object that implements the Enumeration interface creates one at a time, a set of objects. hasMoreElements() method of enumeration used to tests if this enumeration contains more elements. If enumeration contains more elements, then it will return true else false.
Syntax:
boolean hasMoreElements()
Return value: This method returns true if there is at least one additional element to be given in this enumeration object, otherwise return false.
Below is the full implementation of the above approach:
Java
// Getting Enumeration over Java HashSetimport java.util.*;import java.util.Enumeration;  // Classpublic class GFG {      // Main driver method    public static void main(String[] args)    {        // Creating object of HashSet        // String type here- name        HashSet<String> name = new HashSet<>();          // Adding element to HashSet        // Custom inputs        name.add("Nikhil");        name.add("Akshay");        name.add("Bina");        name.add("Chintu");        name.add("Dhruv");          // Creating object of type Enumeration<String>        Enumeration e = Collections.enumeration(name);          // Condition check using hasMoreElements() method        while (e.hasMoreElements())              // print the enumeration            System.out.println(e.nextElement());    }}
Dhruv
Akshay
Chintu
Bina
Nikhil
Example 2: 
Java
// Getting Enumeration over Java HashSetimport java.util.*;import java.util.Enumeration;  // Classpublic class GFG {      // Main driver method    public static void main(String[] args)    {        // Creating object of HashSet        // String type here- name        HashSet<String> gfg = new HashSet<>();          // Adding element to HashSet        // Custom inputs        gfg.add("Welcome");        gfg.add("On");        gfg.add("GFG");          // Creating object of type Enumeration<String>        Enumeration e = Collections.enumeration(gfg);          // Condition check using hasMoreElements() method        while (e.hasMoreElements())              // print the enumeration            System.out.println(e.nextElement());    }}
GFG
Welcome
On
Java-Enumeration
java-hashset
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
How to Iterate HashMap in Java?
Updating Nested Embedded Documents in MongoDB?

To update bested documents in MongDB, use UPDATE() and positional($) operator. Let us create a collection with documents −
> db.demo643.insertOne({
...    details : [
...       {
...          "CountryName":"US",
...          StudentDetails:[{Name:"Chris"},{SubjectName:"MySQL"}]
...       },
...
...       {
...          "CountryName":"UK",
...          StudentDetails:[{Name:"Bob"},{SubjectName:"Java"}]
...       }
...    ]
... }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c737f6c954c74be91e6e3")
}
Display all documents from a collection with the help of find() method −
> db.demo643.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US", "StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName" : "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" } ] } ] }
Following is the query to update nested embedded documents in MongoDB −
> db.demo643.update({"details.CountryName": "UK"}, {"$push": {"details.$.StudentDetails": {Marks:78}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo643.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e9c737f6c954c74be91e6e3"),
   "details" : [
      {
         "CountryName" : "US",
         "StudentDetails" : [
            {
               "Name" : "Chris"
            },
            {
               "SubjectName" : "MySQL"
            }
         ]
      },
      {
         "CountryName" : "UK",
         "StudentDetails" : [
            {
               "Name" : "Bob"
            },
            {
               "SubjectName" : "Java"
            },
            {
               "Marks" : 78
            }
         ]
      }
   ]
}
Minimum Swaps to Group All 1's Together in Python

Suppose we have a binary array data, we have to find the minimum number of swaps required to group all 1’s stored in the array together in any place in the array. So if the array is like [1,0,1,0,1,0,0,1,1,0,1], then the output will be 3, as possible solution is [0,0,0,0,0,1,1,1,1,1,1]
To solve this, we will follow these steps −
set one := 0, n:= length of data array
make an array summ of size n, and fill this with 0, set summ[0] := data[0]
one := one + data[0]
for i in range 1 to n – 1summ[i] := summ[i - 1] + data[i]one := one + data[i]
summ[i] := summ[i - 1] + data[i]
one := one + data[i]
ans := one
left := 0, right := one – 1
while right < nif left is 0, then temp := summ[right], otherwise temp := summ[right] – summ[left - 1]ans := minimum of ans, one – tempincrease right and left by 1
if left is 0, then temp := summ[right], otherwise temp := summ[right] – summ[left - 1]
ans := minimum of ans, one – temp
increase right and left by 1
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def minSwaps(self, data):
      one = 0
      n = len(data)
      summ=[0 for i in range(n)]
      summ[0] = data[0]
      one += data[0]
      for i in range(1,n):
         summ[i] += summ[i-1]+data[i]
         one += data[i]
      ans = one
      left = 0
      right = one-1
      while right <n:
         if left == 0:
            temp = summ[right]
         else:
            temp = summ[right] - summ[left-1]
         ans = min(ans,one-temp)
         right+=1
         left+=1
      return ans
ob = Solution()
print(ob.minSwaps([1,0,1,0,1,0,0,1,1,0,1]))
[1,0,1,0,1,0,0,1,1,0,1]
3
MATLAB - Concatenating Matrices

You can concatenate two matrices to create a larger matrix. The pair of square brackets '[]' is the concatenation operator.
MATLAB allows two types of concatenations −
Horizontal concatenation
Vertical concatenation
When you concatenate two matrices by separating those using commas, they are just appended horizontally. It is called horizontal concatenation.
Alternatively, if you concatenate two matrices by separating those using semicolons, they are appended vertically. It is called vertical concatenation.
Create a script file with the following code −
a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = [ 12 31 45 ; 8 0 -9; 45 2 11]
c = [a, b]
d = [a; b]
When you run the file, it displays the following result −
a =
      10    12    23
      14     8     6
      27     8     9
b =
      12    31    45
      8     0    -9
      45     2    11
c =
      10    12    23    12    31    45
      14     8     6     8     0    -9
      27     8     9    45     2    11
d =
      10    12    23
      14     8     6
      27     8     9
      12    31    45
      8     0    -9
      45     2    11


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Optional stream() method in Java with examples

30 Jul, 2019
The stream() method of java.util.Optional class in Java is used to get the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns returns an empty Stream.
Syntax:
public Stream<T> stream()

Parameters: This method do not accept any parameter.
Return value: This method returns the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns an empty Stream.
Below programs illustrate stream() method:
Note: Below programs require JDK 9 and above to execute.
Program 1:
// Java program to demonstrate// Optional.stream() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print value        System.out.println("Optional: "                           + op);          // get the Stream        System.out.println("Getting the Stream:");        op.stream().forEach(System.out::println);    }}
Output:
Optional: Optional[9455]
Getting the Stream:
9455

Program 2:
// Java program to demonstrate// Optional.stream() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print value        System.out.println("Optional: "                           + op);          try {              // get the Stream            System.out.println("Getting the Stream:");            op.stream().forEach(System.out::println);        }        catch (Exception e) {            System.out.println(e);        }    }}
Output:
Optional: Optional.empty
Getting the Stream:


Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#stream–
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python program to find sum of elements in list

14 Jun, 2022
Given a list of numbers, write a Python program to find the sum of all the elements in the list.Example:  
Input: [12, 15, 3, 10]
Output: 40

Input: [17, 5, 3, 5]
Output: 30
Example #1:  
Python3
# Python program to find sum of elements in listtotal = 0 # creating a listlist1 = [11, 5, 17, 18, 23] # Iterate each element in list# and add them in variable totalfor ele in range(0, len(list1)):    total = total + list1[ele] # printing total valueprint("Sum of all elements in given list: ", total)
Output:  
Sum of all elements in given list:  74
  Example #2 : Using while() loop  
Python3
# Python program to find sum of elements in listtotal = 0ele = 0 # creating a listlist1 = [11, 5, 17, 18, 23] # Iterate each element in list# and add them in variable totalwhile(ele < len(list1)):    total = total + list1[ele]    ele += 1     # printing total valueprint("Sum of all elements in given list: ", total)
Output:  
Sum of all elements in given list:  74
  Example #3: Recursive way  
Python3
# Python program to find sum of all# elements in list using recursion # creating a listlist1 = [11, 5, 17, 18, 23] # creating sum_list functiondef sumOfList(list, size):   if (size == 0):     return 0   else:     return list[size - 1] + sumOfList(list, size - 1)  # Driver code    total = sumOfList(list1, len(list1)) print("Sum of all elements in given list: ", total)
Output:  
Sum of all elements in given list:  74
 Example #4: Using sum() method  
Python3
# Python program to find sum of elements in list # creating a listlist1 = [11, 5, 17, 18, 23] # using sum() functiontotal = sum(list1) # printing total valueprint("Sum of all elements in given list: ", total)
Output:  
Sum of all elements in given list:  74
Example 5: Using add() function of operator module.  
First we have to import the operator module then using the add() function of operator module adding the all values in the list. 
Python3
# Python 3 program to find the sum of all elements in the# list using add function of operator module from operator import*list1 = [12, 15, 3, 10]result = 0for i in list1:  # Adding elements in the list using  # add function of operator module    result = add(i, 0)+result# printing the resultprint(result)
40
 
sasankgandla
surindertarika1234
laxmigangarajula03
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP headers | ETag

06 Sep, 2021
ETag or Entity Tag is a response-type header that works as a validator to let client make conditional requests. It makes re-validation requests more efficient by triggering request headers which help with web cache validation that makes economical use of network bandwidth. 
ETag is generated as identification for specific browser resources. Each time the user opens the same resource, the browser sends a small token to verify if this version of the resource already present in the browser’s HTTP cache matches with the current version on the webserver. If the resource matches then web server need not send a full response. This makes process faster and saves data. 
Syntax:
ETag : "etag-value"   (strong validation)
ETag : W/"etag-value"  (weak validation)   
Directives : This header accepts two directive as mentioned above and described below:
“etag-value”: It is a string of ASCII characters in double-quotes. A new value is generated every time the browser resource changes and it is unique. There is no HTTP specification about the order of value generated. Therefore , the method of value generation is completely dependent on the webserver.
W/ : This is symbolic of weak validation. They are very easy to generate compared to strong validator tags but differ in performing a comparison process. A weak comparison considers two tags equivalent if their opaque-tags match character-by-character, irrespective either or both being tagged as “weak”. While a strong comparison considers two tags equivalent only if both match character by character and both tags are not weak.
Working of ETag with Request Headers : 
If-Match Header : This is primarily used when multiple agents might be working on the same resource , thereby to prevent accidental overwrites while using methods such as POST, PUT, DELETE etc. Here, a ETag header value for a particular resource is contained within an If-Match header to check if while performing the specified action the resource undergoes any change or not. 412 Precondition Failed error is shown if the match does not occur. It can also be used to abort a request if the current representation does not match the prior request completely or partially.
ETag : "21e92a357b3434b5aa"
If-Match : "21e92a357b3434b5aa"
If-None-Match Header : This header is used when the already stored response of a specific website previously visited by the user has expired. Here , server generates If-None-Match value for the current version and compares it with the ETag value stored in user’s browser. A 304 Not Modified status code is shown if both values match. Weak comparison must be used in this scenario while comparing entity tags.
If-None-Match : "21e92a357b3434b5aa"
Examples : 
ETag: "21e92a357b3434b5aa"  (strong validation)
ETag: W/"21e92a457b3434b5aa"  (weak validation)
Supported Browsers : The browsers are supported by HTTP header | ETag header are listed below:
Microsoft Edge
Google Chrome
Mozilla Firefox
Safari
Opera
Internet Explorer
sumitgumber28
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <video> controls Attribute

28 Jun, 2019
The HTML <video> controls Attribute is used to specify the control to play video. It is the Boolean value. This attribute is new in HTML5.
The video control should include:
Play
Pause
Volume
Full-screen Mode
Seeking
Captions/Subtitles(if available)
Track(if available)
Syntax:
<video controls>
Example:
<!DOCTYPE html><html>  <head>    <title>HTML video controls Attribute</title></head>  <body>    <center>        <h1 style="color:green;">GeeksforGeeks</h1>          <h3>HTML video controls Attribute</h3>          <video width="400" height="200" controls>            <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4"                                 type="video/mp4">            <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg"                                 type="video/ogg">        </video>    </center></body>  </html>
Output:
Note: Always specify the width and the height of the video else web page will be confused that how much space that video will be required due to that reason web page become slow down.
Supported Browsers: The browser supported by HTML <video> controls Attribute are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Safari 4.0
Opera 10.5
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AIML - <set>, <get> Tags

<set> and <get> tags are used to work with variables in AIML. Variables can be predefined variables or programmer created variables.
<set> tag is used to set value in a variable.
<set name = "variable-name"> variable-value </set>

<get> tag is used to get value from a variable.
<get name = "variable-name"></get>

For example, consider the following conversation.
Human: I am Mahesh
Robot: Hello Mahesh!
Human: Good Night
Robot: Good Night Mahesh! Thanks for the conversation!

Create setget.aiml inside C > ab > bots > test > aiml and setget.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
   <category>
      <pattern>I am *</pattern>
      <template>
         Hello <set name = "username"> <star/>! </set>
      </template>  
   </category>  
   
   <category>
      <pattern>Good Night</pattern>
      <template>
         Hi <get name = "username"/> Thanks for the conversation!
      </template>  
   </category>  
   
</aiml>
0,I am *,*,*, Hello <set name = "username"> <star/>! </set>,setget.aiml
0,Good Night,*,*, Hi <get name = "username"/> Thanks for the conversation!,setget.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false

You will see the following output −
Human: I am Mahesh
Robot: Hello Mahesh!
Human: Good Night
Robot: Good Night Mahesh! Thanks for the conversation!

 Print
 Add Notes
 Bookmark this page
How to Specify the Path to save Newman report on Jenkins using Postman?

We can specify the path to save Newman's report on Jenkins. Jenkins reports are available in various formats and can be managed by appending flags in the build commands. Besides, we can mention the path of the directory where the reports shall get saved with the help of these build commands.
The steps to specify the path to save Newman reports on Jenkins are listed below −
As a pre-condition, Jenkins should be established in the system. The steps to work with Jenkins are available in the link − https://www.tutorialspoint.com/jenkins/index.htm. Moreover, the Newman should be installed in the system and a Collection with requests should be created.
Step1 − Click on the arrow to the right of the name of the Collection in the sidebar. Then click on Share.
Step2 − The pop-up - SHARE COLLECTION1 opens up. Navigate to Get public link and copy the link which marked in the below image.
Step3 − Open Jenkins and navigate to the Jenkins Job below the Build section. Enter the below command to generate CLI and JUNIT reports in a specific path −
newman run "<link in Step2>" --reporters cli, junit --reporter-junit-export "reportGenerate/report_newman.xml"
In the above command, reportGenerate/report_newman.xml is the path of the file where the report shall be saved. If it is non-existent, the report is generated inside the Jenkins Workspace directory automatically.
How to get selected option using Selenium WebDriver with Python?

We can obtain the option selected in a dropdown with Selenium webdriver. The first_selected_option method fetches the option selected in the dropdown. Once the option is returned we need to apply a text method to get option text.
Let us consider the select dropdown Continents and fetch its selected item −
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
# identify dropdown
s = Select(driver.find_element_by_xpath("//select[@name='continents']"))
#select by option index
s.select_by_index(4)
#get selected item with method first_selected_option
o= s.first_selected_option
#text method for selected option text
print("Selected option is: "+ o.text)
driver.close()
Super Prime in c programming

A super-prime number is A number that occupies prime number position in the sequence of all prime numbers. also known as high order primes, These numbers occupy the position in the sequence of prime number which is equal to Prime number. some super prime numbers are 3,5,11,1 7...
For Example let us Find all super prime numbers less than 13 -
Input 
13
Output
3, 5, 11.
Explanation − to find the super prime number less than 13 we will find all prime numbers that are less than 13. So, show all prime numbers less than 13 are 2,3,5,7,11,13. Now, 2 is a prime number, so we will consider the prime number at position to as a super prime number. this means three is a prime number. Similarly, 5 at position 3 , and 11 at position 5 are super prime numbers.
to find all super-prime numbers that are less than a given prime number the will first find all prime numbers that are are less than that number and Store then in an array. from this array will print only those numbers whose position is equal to any of the prime numbers. For example, the prime number at 2nd 3rd 5th 7th 11th 13th.... are considered.
#include<iostream>
using namespace std;
bool SieveOfEratosthenes(int n, bool isPrime[]) {
   isPrime[0] = isPrime[1] = false;
   for (int i=2; i<=n; i++)
      isPrime[i] = true;
   for (int p=2; p*p<=n; p++) {
      if (isPrime[p] == true) {
         for (int i=p*2; i<=n; i += p)
            isPrime[i] = false;
      }
   }
}
void superPrimes(int n) {
   bool isPrime[n+1];
   SieveOfEratosthenes(n, isPrime);
   int primes[n+1], j = 0;
   for (int p=2; p<=n; p++)
      if (isPrime[p])
   primes[j++] = p;
   for (int k=0; k<j; k++)
      if (isPrime[k+1])
   cout << primes[k] << " ";
}
int main() {
   int n = 343;
   cout << "Super-Primes less than "<< n << " are :"<<endl;
   superPrimes(n);
   return 0;
}
Super-Primes less than 343 are :
3 5 11 17 31 41 59 67 83 109 127 157 179 191 211 241 277 283 331
Table Variable in SQL Server

24 Sep, 2020
Table variable is a type of local variable that used to store data temporarily, similar to the temp table in SQL Server. Tempdb database is used to store table variables.
To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server.
Syntax :
DECLARE @TABLEVARIABLE TABLE
(column1 datatype,  
column2 datatype,  
columnN datatype
)
Example-1 :DECLARE @WeekDays TABLE (Number INT, Day VARCHAR(40), Name VARCHAR(40))
INSERT INTO @WeekDays
VALUES

(1, 'Mon', 'Monday'),
(2, 'Tue', 'Tuesday'),
(3, 'Wed', 'Wednesday'),
(4, 'Thu', 'Thursday'),
(5, 'Fri', 'Friday'),
(6, 'Sat', 'Saturday'),
(7, 'Sun', 'Sunday')

SELECT * FROM @WeekDays;
Update and delete statement usage for table variable in SQL Server
Here we will update and delete the data in the table variables.
Example-2 :
DELETE @WeekDays WHERE Number=7;

UPDATE @WeekDays SET Name='Saturday is a holiday' WHERE Number=6 ;
SELECT * FROM @WeekDays;

DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove Trailing Zeros From string in C++

31 May, 2017
Given a string of digits, remove trailing zeros from it.
Examples:
Input : 00000123569
Output : 123569

Input : 000012356090
Output : 12356090

1) Count trailing zeros.2) Use string erase function to remove characters equal to above count.
Below is C++ implementation.
// C++ program to remove trailing/preceding zeros// from a given string#include<iostream>using namespace std;  string removeZero(string str){    // Count trailing zeros    int i = 0;    while (str[i] == '0')       i++;      // The erase function removes i characters    // from given index (0 here)    str.erase(0, i);      return str;}  // Driver codeint main(){    string str;    str = "00000123569";    str = removeZero(str);    cout << str << endl;    return 0;}
Output :
123569
This article is contributed by Prakhar Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-string
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
GATE | GATE CS 2008 | Question 41

28 Jun, 2021
A B-tree of order 4 is built from scratch by 10 successive insertions. What is the maximum number of node splitting operations that may take place?(A) 3(B) 4(C) 5(D) 6Answer: (C)Explanation:
Insertion of 3 keys
10 20 30

Insertion of 4th key (1st split)
     30
   /   \
10*20   40


Insertion of 5th key no split 
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 5
      30
   /     \
5*10*20   40


Insertion of 6th key (2nd Split)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 6
      8*30
   /   |   \
5    10*20   40 


Insertion of 7th key
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 15
        8*30
   /     |    \
5    10*15*20   40 



Insertion of 8th key (3rd Split)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 12
      8*12*30
   /   /   \  \
 5   10 15*20  40 


Insertion of 9th key 
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 17
      8*12*30
   /  /   \   \
5  10 15*17*20 40 

Insertion of 10th key (4th and 5th Splits)
To maximize splits, let us insert a value in a node that has
key in access. Let us insert 13
          12
       /      \
      8       15*30
   /   \     /  |  \  
  5    10  13 17*20   40 

Quiz of this Question
GATE-CS-2008
GATE-GATE CS 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the path of current script in R ?

30 May, 2021
In this article, we will see how to determine the path of the current script in R Programming Language.
If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path of the R script. To change the current working directory we need to use a function called setwd( ). We need to pass the path as a parameter.
syntax : getwd( ) 
Example :
R
getwd()
Output :
To use the functions of rstudioapi we need to install this package first. To install this package type the below command in the terminal.
install.packages(rstudioapi)
From rstudioapi package we need to use getSourceEditorConext(). It’s like a list. We need to retrieve the path from it. So we need to use $ operator along with getSourceEditorConext(). Before executing this we need to save the R script with some name and with .R extension. Then run the below code for getting the current path of R script.
Example : 
R
# importing rstudioapi packagelibrary("rstudioapi")   # retrieving path from getSourceEditorContext() # using $ operator getSourceEditorContext()$path 
Output :
In the here library we are going to use here( ) function. This function determines the path of the current R script. No need to pass any parameters. Just import the library using the library( ) function. If the package is not available, install using install.packages( ) function by passing package name as parameter within quotations. After installing package, call here( ) function. 
Syntax : here( )
Example :
R
library("here")  here()
Output :
Picked
R directory-programs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.