code-rag-bench/online-tutorials huggingface dataset:
How to divide an HTML page into four parts using frames ? - GeeksforGeeks

25 Mar, 2021
In this article, we will learn how to divide a page into four parts using HTML frames. This can be used to represent the header, sidebar, footer, and main content. The frames are created using the <frame> tag. We will have to use four HTML files for each of the portions.
Syntax:
<frameset>
    // frame elements
</frameset>
The below example will demonstrate the approach to create the four parts of the page.
index.html
<html><frameset rows="10%,80%,10%">  <frame name="A" src="header.html">    <frameset cols="80%,20%">      <frame name="B" src="home.html">        <frame name="C" src="sidebar.html">    </frameset>    <frame name="B" src="footer.html">      <frameset rows="100%">      </frameset></frameset></html>
Output: The page will now be divided like this.
We will now create the HTML pages of the four sections and the content of the main page separately. 
header.html
<html><body>  <h1 style="color: green;              text-align: center">    GeeksforGeeks  </h1></body></html>
home.html
<html><body>  <h1 style="text-align: center">    Welcome to the home page  </h1></body></html>
sidebar.html
<html><body>  <h3>Sidebar</h3>  <a href="html_content.html" target="B">    HTML  </a><br>  <a href="css_content.html" target="B">    CSS  </a><br>  <a href="js_content.html" target="B">    JS  </a><br>  <a href="php_content.html " target="B">    PHP  </a></body></html>
footer.html
<html><body>  <h4 align="center">    All Rights Reserved  </h4></body></html>
html_content.html
<html><body>  <p style="text-align: center">    Hyper Text Markup Language  </p>  </body></html>
css_content.html
<html><body>  <p style="text-align: center">    Cascading Style Sheets  </p>  </body></html>
js_content.html
<html><body>  <p style="text-align: center">    JavaScript  </p>  </body></html>
php_content.html
<html><body>  <p style="text-align: center">     Hypertext Preprocessor  </p>  </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python - Pytorch permute() method - GeeksforGeeks

18 Aug, 2020
PyTorch torch.permute() rearranges the original tensor according to the desired ordering and returns a new multidimensional rotated tensor. The size of the returned tensor remains the same as that of the original.
Syntax: torch.permute(*dims) 
Parameters:
dims: sequence of indices in desired ordering of dimensions Of the tensor (indexing starts from zero).
Return: tensor with desired ordering of dimensions.
Let’s see this concept with the help of few examples:
Example 1: Create a two-dimensional tensor of size 2 × 4 and then permuted.
Python3
# import pytorch libraryimport torch  # create a tensor of size 2 x 4input_var = torch.randn(2,4)  # print sizeprint(input_var.size())  print(input_var)  # dimensions permutedinput_var = input_var.permute(1, 0)  # print sizeprint(input_var.size())  print(input_var)
Output:
torch.Size([2, 4])
tensor([[ 0.9801,  0.5296,  0.5449, -1.1481],
        [-0.6762, -0.1161,  0.6360, -0.5371]])
torch.Size([4, 2])
tensor([[ 0.9801, -0.6762],
        [ 0.5296, -0.1161],
        [ 0.5449,  0.6360],
        [-1.1481, -0.5371]])
Example 2: Create a Three-dimensional tensor of size 3 × 5 × 2 and then permuted.
Python3
# import pytorch libraryimport torch  # creating a tensor with random # values of dimension 3 X 5 X 2input_var = torch.randn(3, 5, 2)  # print sizeprint(input_var.size())  print(input_var)  # dimensions permutedinput_var = input_var.permute(2, 0, 1)  # print sizeprint(input_var.size())  print(input_var)
Output:
torch.Size([3, 5, 2])
tensor([[[ 0.2059, -0.7165],
         [-1.1305,  0.5886],
         [-0.1247, -0.4969],
         [-0.5788,  0.0159],
         [ 1.4304,  0.6014]],

        [[ 2.4882, -0.3910],
         [-0.5558,  0.6903],
         [-0.4219, -0.5498],
         [-0.5346, -0.0703],
         [ 1.1497, -0.3252]],

        [[-0.5075,  0.5752],
         [ 1.3738, -0.3321],
         [-0.3317, -0.9209],
         [-1.6677, -1.1471],
         [-0.9269, -0.6493]]])
torch.Size([2, 3, 5])
tensor([[[ 0.2059, -1.1305, -0.1247, -0.5788,  1.4304],
         [ 2.4882, -0.5558, -0.4219, -0.5346,  1.1497],
         [-0.5075,  1.3738, -0.3317, -1.6677, -0.9269]],

        [[-0.7165,  0.5886, -0.4969,  0.0159,  0.6014],
         [-0.3910,  0.6903, -0.5498, -0.0703, -0.3252],
         [ 0.5752, -0.3321, -0.9209, -1.1471, -0.6493]]])

Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Optional orElseThrow() method in Java with examples - GeeksforGeeks

30 Jul, 2019
The orElseThrow() method of java.util.Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.
Syntax:
public <X> T
  orElseThrow(Supplier<X> exceptionSupplier)
  throws X extends Throwable

Parameters: This method accepts supplier as a parameter of type X to throws an exception if there is no value present in this Optional instance.
Return supplier: This method returns the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.
Exception: This method throws NullPointerException if there is no value present in this Optional instance.
Below programs illustrate orElseThrow() method:Program 1:
// Java program to demonstrate// Optional.orElseThrow() method  import java.util.*;import java.util.function.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print supplier        System.out.println("Optional: "                           + op);          // orElseThrow supplier        System.out.println(            "Value by orElseThrow("            + "ArithmeticException::new) method: "            + op.orElseThrow(                  ArithmeticException::new));    }}
Optional: Optional[9455]
Value by orElseThrow(ArithmeticException::new) method: 9455

Program 2:
// Java program to demonstrate// Optional.orElseThrow() method  import java.util.*;import java.util.function.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // print supplier        System.out.println("Optional: "                           + op);          try {              // orElseThrow supplier            System.out.println(                "Value by orElseThrow("                + "ArithmeticException::new) method: "                + op.orElseThrow(                      ArithmeticException::new));        }        catch (Exception e) {            System.out.println(e);        }    }}
Optional: Optional.empty
java.lang.ArithmeticException

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#orElseThrow-java.util.function.Supplier-
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
Interfaces in Java
Stack Class in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Initializing a List in Java
LinkedList in Java
numpy.ascontiguousarray() in Python - GeeksforGeeks

16 Nov, 2021
numpy.ascontiguousarray()function is used when we want to return a contiguous array in memory (C order).
Syntax : numpy.ascontiguousarray(arr, dtype=None)
Parameters :arr : [array_like] Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.dtype : [str or dtype object, optional] Data-type of returned array.
Return : ndarray Contiguous array of same shape and content as arr, with type dtype if specified.
Code #1 : List to array
# Python program explaining# numpy.ascontiguousarray() function  import numpy as geekmy_list = [100, 200, 300, 400, 500]  print ("Input  list : ", my_list)       out_arr = geek.ascontiguousarray(my_list, dtype = geek.float32)print ("output array from input list : ", out_arr) 
Output :
Input  list :  [100, 200, 300, 400, 500]
output array from input list :  [ 100.  200.  300.  400.  500.]

 Code #2 : Tuple to array
# Python program explaining# numpy.ascontiguousarray() function  import numpy as geek  my_tuple = ([2, 6, 10], [8, 12, 16])   print ("Input  tuple : ", my_tuple)    out_arr = geek.ascontiguousarray(my_tuple, dtype = geek.int32) print ("output array from input tuple : ", out_arr) 
Output :
Input  tuple :  ([2, 6, 10], [8, 12, 16])
output array from input tuple :  [[ 2  6 10]
 [ 8 12 16]]

 Code #3 : Scalar to array
# Python program explaining# numpy.ascontiguousarray() function  import numpy as geek  my_scalar = 100   print ("Input  scalar : ", my_scalar)    out_arr = geek.ascontiguousarray(my_scalar, dtype = geek.float32) print ("output array from input scalar : ", out_arr) print(type(out_arr))
Output :
Input  scalar :  100
output array from input scalar :  [ 100.]
class 'numpy.ndarray'

gulshankumarar231
Python numpy-arrayCreation
Python-numpy
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Difference between innerText and innerHTML - GeeksforGeeks

19 Jun, 2019
innerText and innerHTML are both properties of JavaScript. However, there are differences in which the text is handled. Let us check the syntax of the two and then take an example to look at the differences.
Syntax:Let us assume that we have a JavaScript variable called x.
var x = document.getElementById('test');
Here’s how we can use innerText and innerHTML on this variable.
innerTextx.innerText
x.innerText
innerHTMLx.innerHTML
x.innerHTML
Example:
<!DOCTYPE html><html>  <head>    <title>        Difference between       InnerHTML and InnerText    </title></head>  <body style="text-align:center;">      <h1 style="color:green">GeeksforGeeks</h1>      <div id="test">        The following element contains some        <codes>code</codes> and        <italic>some text</italic>.    </div>    <p></p>    <button onClick="innerTextFn()">        innerHTML    </button>    <button onClick="innerHTMLFn()">        innerText    </button>    <p id="op"></p>      <script>        function innerTextFn() {            var x = document.getElementById('test');            alert(x.innerText);        }          function innerHTMLFn() {            var x = document.getElementById('test');            alert(x.innerHTML);        }    </script></body>  </html>
OutputBefore click:
After click innerHTML:
After click innerText:
Differences:As we can see from the example above the innerText property sets or returns the text content as plain text of the specified node, and all its descendants whereas the innerHTML property gets and sets the plain text or HTML contents in the elements. Unlike innerText, inner HTML lets you work with HTML rich text and doesn’t automatically encode and decode text.
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to Install Dart on MacOS? - GeeksforGeeks

06 Dec, 2021
The dart is an SDK (Software Development Kit) and SDK as you may observe from its name it is mainly a collection of software development tools that facilitate the creation of different applications, some of the tools include compilers debuggers libraries, and perhaps the software framework aiding towards the development process of creating.
As of November 2021, the following versions are supported:
macOS 10.15 (Catalina)
macOS 11 (Big Sur)
macOS 12 (Monterey)
Step 1: Install Homebrew, If you don’t know how to install it, check out this article. 
Step 2: Now open the terminal and run the following commands
 $ brew tap dart-lang/dart
Output:
Step 3: Now run this command on the terminal to install Dart
$ brew install dart
Output:
Now Dart is on your system.
Upgrade to the new version:
To upgrade when there is a new release of Dart is available:
$ brew upgrade dart
Switch to a specific version:
If you want to switch between locally installed Dart releases or want to go to the previous version then, use brew switch dart <version>. Example:
$ brew switch dart 2.12.4
Note: The brew switch command was removed after the 2.6 release of Homebrew. To continue using brew switch, downgrade Homebrew to a 2.6 version:
$ cd /usr/local/Homebrew && git checkout 2.6.2
you can check which versions of Dart you’ve installed by running the following commands :
$ brew dart --version
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Node.js Bot.onText() API for Telegram Bot - GeeksforGeeks

30 Sep, 2020
The Bot.onText() method is used in the Node.js Telegram Bot API. This Node.js module to interact with the official Telegram Bot API. This method is used to reply when the users interact with the Telegram BOT.
Syntax:
TelegramBot.onText(regexp, callback)
Parameters: This Method accepts two parameters as mentioned above and described below:
regexp: It’s the regular expression, the message must contains /echo.
callback: It is the callback function which is passed as parameter and called when the function call is executed.
Return Type: The return type of the function is void.
Installing Module: Install the module using the following command:
npm i telegram-bot-api
Steps to get the keys:
First get the GET BOT_TOKEN from BOTFATHER in telegram. Just search for BOTFATHER in Telegram and select the verified one as shown below:Type /start and then click on /newbot as shown below:Now type the name of the bot and that must be unique.Now just copy the token From the BotFather. And for deleting the token simply search /delete token in BotFather.
First get the GET BOT_TOKEN from BOTFATHER in telegram. Just search for BOTFATHER in Telegram and select the verified one as shown below:
Type /start and then click on /newbot as shown below:
Now type the name of the bot and that must be unique.
Now just copy the token From the BotFather. And for deleting the token simply search /delete token in BotFather.
Project structure:
Filename: bot.js
var token = 'Enter the token';  const TelegramBot = require('node-telegram-bot-api');  const bot = new TelegramBot(token, {polling: true});  // Matches "/echo [whatever]"bot.onText(/\/echo(.+)/, (msg, match) => {   // The 'msg' is the received Message from Telegram // and 'match' is the result of executing the regexp  // above on the text content of the message   const chatId = msg.chat.id;   // The captured "whatever" const resp = match[1];    // send back the matched "whatever" to the chat bot.sendMessage(chatId,resp);  });
Run bot.js file using the following command:
node bot.js
Output:
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Display the red, green and blue color planes of a color image in MATLAB

28 Mar, 2019
Prerequisite – RGB image representationA colored image can be represented as a 3 order matrix. The first order is for the rows, the second order is for the columns and the third order is for specifying the color of the corresponding pixel. Here we use the RGB color format, so the third order will take 3 values of Red, Green ans Blue respectively. The values of the rows and columns depends on the size of the image.
Approach:
Load the image into a variable J by using imread().
Store the number of rows and columns of the image in variables, r and c.
Create 3 zero matrices R, G and B (one for each of the 3 colors) of size rXc.
Store the corresponding color plane of the image in the corresponding zero matrix.1: Red
2: Green
3: Blue 
1: Red
2: Green
3: Blue 
Display the images by using imshow(), but typecast them into uint8 first.
Implementation:
% MATLAB code to display the red, green and blue% color planes of a color image  % read the imageI = imread('lenna.png');  % rows and columns in the imager = size(I, 1);c = size(I, 2);  % creating zero matricesR = zeros(r, c, 3);G = zeros(r, c, 3);B = zeros(r, c, 3);  % storing the corresponding color plane  % red planeR(:, :, 1) = I(:, :, 1);  % green planeG(:, :, 2) = I(:, :, 2);  % blue planeB(:, :, 3) = I(:, :, 3);  % displaying the imagesfigure, imshow(uint8(R));figure, imshow(uint8(G));figure, imshow(uint8(B));
Input :Output :
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set Database From Single User Mode to Multi User in SQL

16 Dec, 2021
A single-user mode specifies that only one user at a time can access the database. If you set the database to single-user mode then all other connections will be closed without warning. If you get disconnected after setting the database into single-user mode, a different user can connect to database, but only one user.
Where as in multiple-user mode more than one user can connect to the same database at the same time. This mode is generally used in organizations so that multiple users can access it simultaneously. Areas where Multi-user database is used are Banks, supermarket, insurance agencies sector.
Here we will see, how to set database from single user mode to multi user mode. 
There are two ways to perform the given activity:
Using ALTER command
Using Object explorer in SQL Server Management Studio.
For demonstration, follow the steps given below:
Step 1: Create database
Use the following command to create database.
Query:
CREATE TABLE geeks;
Step 2: Set database into single user mode
ALTER command followed by SET keyword is used to set the user mode of database. Before changing the access mode all the open connections must be closed. Use the ROLLBACK IMMEDIATE termination clause after ALTER command along with ‘WITH’ keyword to close open connection.
Syntax:
ALTER DATABASE database_name SET 
SINGLE_USER WITH ROLLBACK IMMEDIATE
Query:
ALTER DATABASE geeks SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
Output:
Here, we can see that ‘single user’ is displayed alongside the geeks database name. 
We can use ALTER command in same way as we used to set the single user access mode. This commands need not connection closure.
Syntax:
ALTER DATABASE database_name 
SET MULTI_USER;
Query:
ALTER DATABASE geeks
SET MULTI_USER;
Output:
Here , ‘single user’ keyword that was displayed earlier alongside geeks database is removed now.
Steps to change access mode:
Select View from menu bar.
Select Object explorer option. Object explorer will be appeared on left side of the screen.
Select Database folder and select your database (geeks we have used here).
Right click on the database and select properties option.
A dialog box will open, select ‘option’ option from left hand side of dialog box screen.
Scroll down to get ‘STATE’ field.
Select Restrict access option from STATE field.
Select MULTI_USER from dropdown menu.
Click ‘OK’.
Step 1: Open Object explorer
Step 2: Select properties
Step 3: Select option keyword from dialog box
Step 4: Select MULTI_USER from dropdown list in Restrict Access field
Step 5: Click on Ok, A dialog box will appear. Now click on Yes button.
Step 6: Again open object explorer
We can see that the ‘single user’ keyword is no longer present with the database name.
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to make sure that Apache service keeps running in Ubuntu

03 Jan, 2019
Majority of world’s websites are hosted on are hosted on Apache Web Servers and the majority of those servers run Apache in Linux. Let’s see how to install Apache in Ubuntu:
Type the following commands in terminal application on your computer:
$ sudo apt-get update
$ sudo apt-get install apache2

Now type localhost on your browser. It will pop up a message “IT WORKS“.
There is also another way to check whether Apache Services running in the browser or not. To check, first find the IP Address using the below command:
$ifconfig
Now, put that IP address on the browser. The same message is being displayed “IT WORKS”. This ensures that Apache service keeps running in Ubuntu.
To find out the active ports then type:
$ netstat -a|more
Here we get all of the ports, our active connections, our virtual ports essentially that our computer is listening. If you need to get the port numbers then type:
$ netstat -an|more
It shows port80, the port for the web server, port for HTTP, it listens to every address available. Our web server is listening.
Characteristics:
To stop the web server then type:$ sudo /etc/init.d/apache2 stopTo check it Type:$ netstat -an|moreNow our web server is no more listening.
$ sudo /etc/init.d/apache2 stop
To check it Type:
$ netstat -an|more
Now our web server is no more listening.
To start our web server, type:$ sudo /etc/init.d/apache2 start
$ sudo /etc/init.d/apache2 start
To Restart our web server, type:$ sudo /etc/init.d/apache2 restartTo check, Type:$ netstat -an|moreNow our server is running.
$ sudo /etc/init.d/apache2 restart
To check, Type:
$ netstat -an|more
Now our server is running.
Now We have to create and edit our Webpage. So type the following command:
$ cd /var/www
Press ENTER to continue.
:/var/www$ ls
Press ENTER to continue.
index.html
This ‘index.html‘ is the default Webpage in the Apache. To edit the Webpage, type the Command:
:/var/www$ sudo nano index.html
<html><head><title>Dans Homepage</title></head><body><h1>Welcome to my webpage!</h1><p>This website is under construction.</p></body></html>
Press CTRL+X to save and exit.
Type localhost or Your IP address on the address bar of a web browser. ‘index.html‘ page will be displayed.
Apache
linux-command
Picked
Technical Scripter 2018
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
Top Programming Languages for Android App Development
How to setup cron jobs in Ubuntu
'dd' command in Linux
How to Add External JAR File to an IntelliJ IDEA Project?
How to Delete Temporary Files in Windows 10?
Creating a Receipt Calculator using Python

17 May, 2022
A receipt calculator is generally a slip in which the total invoice along with their names is mentioned. We will use the class PrettyTable inside the prettytable library for making our receipt calculator.
It is a class present inside prettytable library which help us to make relational tables in Python.  
Installation of library:
pip install prettytable
Generating PrettyTable :
Initialisation :
<table name> = PrettyTable(['<column1>','<column2>',....])

To add a row :
add_row(['<row1>','<row2>',....])
Approach :
There will be two columns: Item Name & Item Price. 
We will keep taking item name and item price (in new line) Until the user enters ‘q’ and store the price in another variable name ‘total’ initialized as 0. When userEnters ‘q’, program will stop taking inputs and return the table along with the total amount specified at the end.
Below is the Implementation:
Python3
from prettytable import PrettyTable    print('--------------WELCOME TO XYZ Shop--------------\n')table = PrettyTable(['Item Name', 'Item Price'])total = 0  while(1):    name = input('Enter Item name:')          # 'q' to exit and print the table    if(name != 'q'):        price = int(input('Enter the Price:'))                  # store all the prices in 'total'        total += price        table.add_row([name, price])        continue          elif(name == 'q'):        break          table.add_row(['TOTAL', total])print(table)print('\nThanks for shopping with us :)')print('Your total bill amount is ', total, '/-')
Output:
Note: You can run this program on any python version except for python2 you just need to change the syntax of print().
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to find Median of Elements where Elements are stored in 2 different arrays

We shall consider a C++ program to find the median of elements where elements are stored in 2 different arrays.
Begin
   Function Median() has Two arrays a1[], a2[] and n = numbers of elements of the array as arguments:
   Initialize i and j by 0, and n1 and n2 by -1
   for c in range 0 to n, do
      if i = n, then
         n1 := n2
         n2 := a2[0]
      break the loop
      else if j = n, then
         n1 := n2
         n2 := a1[0]
      break the loop
      if a1[i] < a2[j], then
         n1 := n2
         n2 := a1[i]
         increase i by 1
      else
         n1 := n2
         n2 := a2[i]
         increase j by 1
      done
      return the average of n1 and n2.
End.
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int Median(int a1[],int a2[], int n) {
   int i = 0;
   int j = 0;
   int c;
   int n1 = -1, n2 = -1;
   for (c = 0; c <= n; c++) {
      if (i == n) {
         n1 = n2;
         n2 = a2[0];
         break;
      }
      else if (j == n) {
         n1 = n2;
         n2 = a1[0];
         break;
      }
      if (a1[i] < a2[j]) {
         n1 = n2;
         n2 = a1[i];
         i++;
      } else {
         n1 = n2;
         n2 = a2[j];
         j++;
      }
   }
   return (n1 + n2)/2;
}
int main() {
   int n1,n2, i;
   cout<<"\nEnter the number of elements for 1st array: ";
   cin>>n1;
   int a1[n1];
   for(i = 0; i < n1; i++) {
      cout<<"Enter element for 1st array"<<i+1<<": ";
      cin>>a1[i];
   }
   cout<<"\nEnter the number of elements for 2nd array: ";
   cin>>n2;
   int a2[n2];
   for(i = 0; i < n2; i++) {
      cout<<"Enter element for 2nd array "<<i+1<<": ";
      cin>>a1[i];
   }
   if (n1 == n2)
      cout << "Median is "
      << Median(a1, a2, n1) ;
   else
      cout << "Doesn't work for arrays"
      << " of unequal size";
   return 0;
}
Enter the number of elements for 1st array: 5
Enter element for 1st array1: 2
Enter element for 1st array2: 4
Enter element for 1st array3: 6
Enter element for 1st array4: 7
Enter element for 1st array5: 9
Enter the number of elements for 2nd array: 5
Enter element for 2nd array 1: 20
Enter element for 2nd array 2: 40
Enter element for 2nd array 3: 60
Enter element for 2nd array 4: 70
Enter element for 2nd array 5: 90
Median is 20
Flip and Invert Matrix in Python

Suppose we have a binary matrix mat. We have to select each row in matrix, then reverse the
row. After that, flip each bit (0 to 1 and 1 to 0).
So, if the input is like
then the output will be
To solve this, we will follow these steps −
track:= 0
for each row in mat, doreverse the rowtracker := 0for each val in row, doif val is 1, thenmat[track, tracker] := 0otherwise,mat[track, tracker] := 1tracker := tracker + 1track := track + 1
reverse the row
tracker := 0
for each val in row, doif val is 1, thenmat[track, tracker] := 0otherwise,mat[track, tracker] := 1tracker := tracker + 1
if val is 1, thenmat[track, tracker] := 0
mat[track, tracker] := 0
otherwise,mat[track, tracker] := 1
mat[track, tracker] := 1
tracker := tracker + 1
track := track + 1
return mat
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, mat):
      track=0
      for row in mat:
         row.reverse()
         tracker = 0
         for val in row:
            if val == 1:
               mat[track][tracker] = 0
            else:
               mat[track][tracker] = 1
            tracker += 1
         track += 1
      return mat
ob = Solution()
mat = [[1,1,0],[0,1,0],[0,0,1]]
print(ob.solve(mat))
[[1,1,0],[0,1,0],[0,0,1]]
[[1, 0, 0], [1, 0, 1], [0, 1, 1]]
Java Program for Counting Sort

13 Jun, 2022
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.
Java
// Java implementation of Counting Sortclass CountingSort {    void sort(char arr[])    {        int n = arr.length;         // The output character array that will have sorted arr        char output[] = new char[n];         // Create a count array to store count of individual        // characters and initialize count array as 0        int count[] = new int[256];        for (int i = 0; i < 256; ++i)            count[i] = 0;         // store count of each character        for (int i = 0; i < n; ++i)            ++count[arr[i]];         // Change count[i] so that count[i] now contains actual        // position of this character in output array        for (int i = 1; i <= 255; ++i)            count[i] += count[i - 1];         // Build the output character array        for (int i = 0; i < n; ++i) {            output[count[arr[i]] - 1] = arr[i];            --count[arr[i]];        }         // Copy the output array to arr, so that arr now        // contains sorted characters        for (int i = 0; i < n; ++i)            arr[i] = output[i];    }     // Driver method    public static void main(String args[])    {        CountingSort ob = new CountingSort();        char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o',                      'r', 'g', 'e', 'e', 'k', 's' };         ob.sort(arr);         System.out.print("Sorted character array is ");        for (int i = 0; i < arr.length; ++i)            System.out.print(arr[i]);    }}/*This code is contributed by Rajat Mishra */
Sorted character array is eeeefggkkorss
 
Time Complexity: O(n+k) where n is the number of elements in the input array and k is the range of input. Auxiliary Space: O(n+k)
Please refer complete article on Counting Sort for more details! 
surindertarika1234
amankr0211
counting-sort
Java Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Hide/Show BottomNavigationView on Scroll in Android?

23 Dec, 2020
BottomNavigationView is the best option for navigation in android. It makes life easier for a user to switch between multiple activities and fragments. It’s really a pain in the butt to use an android app without having proper navigation. At GFG, we have already shared an article with you on BottomNavigationView. If you are new or don’t know that what is BottomNavigationView or want to implement it in your app then please refer to this BottomNavigationView in Android.
We all are using android apps in our daily life. If you will observe carefully, you will found that an application with a better user-interface gets a heart from the user. He will love using that application and will come again and again. For creating better and professional user interfaces you have to take care of these small things. When a BottomNavigationView will show and hide on scrolling it will look much more professional and practical. You have also seen in LinkedIn, that how it’s BottomNavigationView shows and hide on scrolling. Do you also not want to implement it in BottomNavigationView of your own app. In this article, we are going to discuss how to implement this type of behavior in our android app. After going through this article, and understanding the logic you will be able to use it everywhere.
A sample GIF is given below to get an idea about what we are going to do in this article. This is a language-independent tutorial, the steps will be the same for Java and Kotlin. 
Step 1: Open an existing project which has BottomNavigationView and you want to work on it. If you haven’t created it yet then you can always refer to this BottomNavigationView in Android and create it. You may also clone this GitHub project for implementation. And we have used this project as an example in this article.
Note: Please refer to this article to clone Android Project from GitHub in Android Studio.
Step 2: Then navigate to the Layout resource File on which you have used the BottomNavigationView. For Example, we have used it in the activity_home.xml file with RecyclerView.
Step 3: Now make sure that the parent layout for that layout resource file is CordinatorLayout because this behavior will not work in any other type of layout. It will only work in CordinatorLayout.
Note: CordinatorLayout is an advanced layout in android, It has much more interesting functionalities. While you will be dealing with the complex UI’s in android, then you can do it more efficiently in CordinatorLayout. You can read more about the CordinatorLayout from here.
Step 4: Now, In BottomNavigationView add an attribute like this. 
XML
app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"/>.
Step 5: Try running your application on an emulator or a physical device. In this sample project, we have used a RecyclerView with BottomNavigationView. You can do the same with ScrollView or any other object in android.
android
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scanner toString() method in Java with Examples

11 Oct, 2018
The toString() method of java.util.Scanner class returns the string representation of this Scanner. The exact format is unspecified.
Syntax:
public String toString()
Return Value: This function returns the string representation of this scanner.
Below program illustrates the above function:
Program 1:
// Java program to illustrate the// toString() method of Scanner class in Java  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {          String s = "GeeksForGeeks - "                   + "A Computer Science Portal for Geeks";          // create a new scanner        // with the specified String Object        Scanner scanner = new Scanner(s);          // print a line of the scanner        System.out.println("Scanner String: \n"                           + scanner.nextLine());          // display information about this scanner        System.out.println("\nString representation "                           + "of this Scanner:\n"                           + scanner.toString());          // close the scanner        scanner.close();    }}
Scanner String: 
GeeksForGeeks - A Computer Science Portal for Geeks

String representation of this Scanner:
java.util.Scanner[delimiters=\p{javaWhitespace}+]
[position=51][match valid=true][need input=false]
[skipped=false][group separator=\,]
[decimal separator=\.][positive prefix=]
[negative prefix=\Q-\E][positive suffix=]
[negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#toString()
Java - util package
Java-Library
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
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
Compute the outer product of two given vectors using NumPy in Python

29 Aug, 2020
In Python, we can use the outer() function of the NumPy package to find the outer product of two matrices. 
Syntax : numpy.outer(a, b, out = None)
Parameters :
a : [array_like] First input vector. Input is flattened if not already 1-dimensional.
b : [array_like] Second input vector. Input is flattened if not already 1-dimensional.
out : [ndarray, optional] A location where the result is stored.
Return : [ndarray] Returns the outer product of two vectors. out[i, j] = a[i] * b[j]
Example 1: Outer Product of 1-D array
Python3
# Importing libraryimport numpy as np  # Creating two 1-D arraysarray1 = np.array([6,2])array2 = np.array([2,5])print("Original 1-D arrays:")print(array1)print(array2)  # Outputprint("Outer Product of the two array is:")result = np.outer(array1, array2)print(result)
Output:
Original 1-D arrays:
[6 2]
[2 5]
Outer Product of the two array is:
[[12 30]
 [ 4 10]]

Example 2: Outer Product of 2X2 matrix
Python3
# Importing libraryimport numpy as np  # Creating two 2-D matrixmatrix1 = np.array([[1, 3], [2, 6]])matrix2 = np.array([[0, 1], [1, 9]])print("Original 2-D matrix:")print(matrix1)print(matrix2)  # Outputprint("Outer Product of the two matrix is:")result = np.outer(matrix1, matrix2)print(result)
Output:
Original 2-D matrix:
[[1 3]
 [2 6]]
[[0 1]
 [1 9]]
Outer Product of the two matrix is:
[[ 0  1  1  9]
 [ 0  3  3 27]
 [ 0  2  2 18]
 [ 0  6  6 54]]

Example 3: Outer Product of 3X3 matrix
Python3
# Importing libraryimport numpy as np  # Creating two 3-D matrixmatrix1 = np.array([[2, 8, 2], [3, 4, 8], [0, 2, 1]])matrix2 = np.array([[2, 1, 1], [0, 1, 0], [2, 3, 0]])print("Original 3-D matrix:")print(matrix1)print(matrix2)  # Outputprint("Outer Product of the two matrix is:")result = np.outer(matrix1, matrix2)print(result)
Output:
Original 3-D matrix:
[[2 8 2]
 [3 4 8]
 [0 2 1]]
[[2 1 1]
 [0 1 0]
 [2 3 0]]
Outer Product of the two matrix is:
[[ 4  2  2  0  2  0  4  6  0]
 [16  8  8  0  8  0 16 24  0]
 [ 4  2  2  0  2  0  4  6  0]
 [ 6  3  3  0  3  0  6  9  0]
 [ 8  4  4  0  4  0  8 12  0]
 [16  8  8  0  8  0 16 24  0]
 [ 0  0  0  0  0  0  0  0  0]
 [ 4  2  2  0  2  0  4  6  0]
 [ 2  1  1  0  1  0  2  3  0]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js texture() Function

04 Mar, 2021
The texture() function in p5.js is used to provide a texture for geometry objects. This texture can be an p5.Image, p5.MediaElement or p5.Graphics object.
Syntax:
texture( tex )
Parameters: This function accepts a single parameter as mentioned above and described below.
tex: It is a p5.Image, p5.MediaElement or p5.Graphics object that specifies the 2D texture that has to be used on a model.
The program below illustrate the texture() function in p5.js:
Example 1:
let cubeObj;let newFont;  // Load all the models in preload()function preload() {  newFont = loadFont("fonts/Montserrat.otf");  cubeObj = loadModel("models/cube.obj", true);    textureImg = loadImage("blue_texture.jpg");}  function setup() {  createCanvas(400, 300, WEBGL);  textFont(newFont, 14);}  function draw() {  background("green");  text("The model below is using an"+       " image texture", -185, -125);    scale(0.60);  lights();  rotateX(frameCount * 0.005);  rotateY(frameCount * 0.005);  noStroke();    texture(textureImg);    // Load the given model  model(cubeObj);}
Output:
Example 2:
let newFont;let newTexture;  function preload() {  newFont = loadFont("fonts/Montserrat.otf");}  function setup() {  createCanvas(400, 300, WEBGL);  textFont(newFont, 14);    newTexture = createGraphics(400, 200);  newTexture.textSize(75);}  function draw() {  background("green");  text("Use the dropdown to select the"+       " model to display", -185, -125);    newTexture.background("yellow");  newTexture.text("Hello World!", 0, 100);    // Use the created texture  texture(newTexture);  rotateX(frameCount * 0.01);  rotateY(frameCount * 0.01);      box(100);}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/texture
JavaScript-p5.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the use of the VALUE function in a DB2? Explain with the help of an example

The purpose of VALUE function in DB2 is to check for NULL values and it can be used in place of NULL indicator or COALESCE function. The VALUE function replaces the column value with the given argument if it contains a NULL value.
For example, if we have an ORDER table and we have to extract ORDER_ID and ORDER_DESCRIPTION from this table. The ORDER_DECRIPTION column can have NULL values.
If this is the case, we have to replace ORDER_DESCRIPTION with SPACES, then we can use the below query:
EXEC SQL
   SELECT ORDER_ID, VALUE(ORDER_DESCRIPTION, ‘ ‘)
   INTO :ORDER-ID, :ORDER-DESCRIPTION
   FROM ORDERS
END-EXEC
In this case, the VALUE function will take two arguments. The first one is the name of the column and second one is the expected value if the column contains NULL values.
How to create a link to send email with a subject in HTML?

To create a link to send email, use <a> tag, with href attribute. The mail to link is added inside the <a> tag. To add a subject, you need to add ? and then include the subject. All this comes inside the <a> tag.
Just keep in mind to add the email address where you want to receive the email in the mail to link. Also, the spaces between words for the subject shouldn’t be space, instead include %20. This is to ensure the browser displays the text properly.
You can try to run the following code to create a link to send an email with a subject in HTML.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Email with subject</title>
   </head>

   <body>
      <h1>Contact</h1>
      <p>For any queries:<a href="mailto:demo@example.com?Subject=My%20Query">Contact us</a></p>
   </body>
</html>
Array findIndex() function in JavaScript

The findIndex() function in JavaScript returns the index of the first element value that satisfy a given condition in an array.
Following is the code for the array find() function −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .findIndex {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Array FindIndex() example</h1>
<div class="findIndex"></div>
<button class="findArr">CLICK HERE</button>
<h3>Click on the above button to get the index of lion in the array</h3>
<script>
   function findLion(animal) {
      return animal === "lion";
   }
   let fillEle = document.querySelector(".findIndex");
   let arr = ["cow", "lion", "bull", "tiger"];
   fillEle.innerHTML = arr;
   document.querySelector(".findArr").addEventListener("click", () => {
      fillEle.innerHTML = arr.findIndex(findLion);
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button the index of lion will be returned as follows −
Java program to calculate student grades

The following program accepts average from the user, calculates the grade and prints it.
public class CalculateStudentGrades {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter average of your marks (less than 100)::");
      int average = sc.nextInt();
      char grade;

      if(average>=80){
         grade = 'A';
      }else if(average>=60 && average<80){
         grade = 'B';
      }
      else if(average>=40 && average<60){
         grade = 'C';
      }
      else {
         grade = 'D';
      }

      switch(grade) {
         case 'A' :
            System.out.println("Excellent!");
            break;
         case 'B' :
         case 'C' :
            System.out.println("Well done");
            break;
         case 'D' :
            System.out.println("You passed");
         case 'F' :
            System.out.println("Better try again");
            break;
         default :
         System.out.println("Invalid grade");
      }
      System.out.println("Your grade is " + grade);
   }
}
Enter average of your marks (less than 100)::
59
Well done
Your grade is C