code-rag-bench/online-tutorials huggingface dataset:
How to use ViewBag in ASP .Net MVC C#?

ViewBag uses the dynamic feature that was introduced in to C# 4.0. It allows an
object to have properties dynamically added to it. Internally, it is a dynamic type
property of the ControllerBase class which is the base class of the Controller class.
ViewBag only transfers data from controller to view, not visa-versa. ViewBag values
will be null if redirection occurs. ViewBag is able to set and get value dynamically
and able to add any number of additional fields without converting it to strongly
typed.
Storing data in ViewBag −
ViewBag.Counties = countriesList;
Retrieving data from ViewBag −
string country = ViewBag.Countries;
using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public ViewResult Index(){
         ViewBag.Countries = new List<string>{
            "India",
            "Malaysia",
            "Dubai",
            "USA",
            "UK"
         };
         return View();
      }
   }
}
@{
   ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
<ul>
@foreach(string country in ViewBag.Countries){
   <li>@country</li>
}
</ul>
PHP Class properties

Data members declared inside class are called properties. Property is sometimes referred to as attribute or field. In PHP, a property is qualified by one of the access specifier keywords, public, private or protected. Name of property could be any valid label in PHP. Value of property can be different for each instance of class. That's why it is sometimes referred as instance variable.
Inside any instance method, property can be accessed by calling object's context available as a pesudo-variable $this. If a property is declared as public, it is available to object with the help of -> operator. If a property is defined with static keyword, its value is shared among all objects of the class and is accessed using scope resolution operator (::) and name of class.
This example shows how a property is defined and accessed
 Live Demo
<?php
class myclass{
   private $fname="Kiran";
   public $mname="Pratap";
   static $lname="Singh";
   function dispdata(){
      echo "$this->fname\n";
      echo "$this->mname\n";
      echo myclass::$lname;
   }
}
$obj=new myclass();
$obj->dispdata();
?>
The output of above code is as follows −
Kiran
Pratap
Singh
Outside class, instance properties declared as public are available to object, but private properties are not accessible. In previous versions of PHP, var keyword was available for property declaration. Though it has now been deprecated, it is still available for backward compatibility and is treated as public declaration of property.
PHP 7.4 introduces type declaration of property variables
<?php
class myclass{
   private string $name;
   private int $age;
   function setdata(string $x, int $y){
      $this->name=$x;
      $this->age=$y;
   }
}
$obj=new myclass("Kiran",20);
?>
fork() to execute processes from bottom to up using wait()

11 Jan, 2018
fork() system call is used to create a process generally known as child process and the process that created it is known as parent process. Now, all the processes that are created using fork() runs concurrently. But what if we want the last process created to execute first and in this manner bottom to up execution such that parent process executes last.
This can be done by using wait() system call. The parent process may then issue a wait() system call, which suspends the execution of the parent process while the child executes and when the child finishes execution, it returns exit status to operating system. Now wait() suspend the process until any of its child process finish execution.
NOTE: This is a linux system call, so it must be executed on linux or unix variant system.
// Program to demonstrate bottom to up execution// of processes using fork() and wait()#include <iostream>#include <sys/wait.h> // for wait()#include <unistd.h> // for fork()int main(){    // creating 4 process using 2 fork calls    // 1 parent : 2 child : 1 grand-child    pid_t id1 = fork();    pid_t id2 = fork();      // parent process    if (id1 > 0 && id2 > 0) {        wait(NULL);        wait(NULL);        cout << "Parent Terminated" << endl;    }      // 1st child    else if (id1 == 0 && id2 > 0) {          // sleep the process for 2 seconds        // to ensure 2nd child executes first        sleep(2);        wait(NULL);        cout << "1st child Terminated" << endl;    }      // second child    else if (id1 > 0 && id2 == 0) {        // sleep the process for 1 second        sleep(1);        cout << "2nd Child Terminated" << endl;    }      // grand child    else {        cout << "Grand Child Terminated" << endl;    }      return 0;}
Output:
Grand Child Terminated
2nd Child Terminated
1st child Terminated
Parent Terminated

system-programming
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TimeUnit toSeconds() method in Java with Examples

15 Oct, 2018
The toSeconds() method of TimeUnit Class is used to get the time represented by the TimeUnit object, as the number of Seconds, since midnight UTC on the 1st January 1970.
Syntax:
public long toSeconds(long duration)
Parameters: This method accepts a mandatory parameter duration which is the duration in milliSeconds.
Return Value: This method returns the converted duration as Seconds.
Below programt illustrate the implementation of TimeUnit toSeconds() method:
Program 1:
// Java program to demonstrate// toSeconds() method of TimeUnit Class  import java.util.concurrent.*;import java.util.Date;  class GFG {    public static void main(String args[])    {        // Get current time in milliseconds        long timeInMilliSec = new Date().getTime();          // Create a TimeUnit object        TimeUnit time = TimeUnit.MILLISECONDS;          // Convert milliseconds to Seconds        // using toSeconds() method        System.out.println("Time " + timeInMilliSec                           + " milliSeconds in Seconds = "                           + time.toSeconds(timeInMilliSec));    }}
Time 1539585656193 milliSeconds in Seconds = 1539585656

Program 2:
// Java program to demonstrate// toSeconds() method of TimeUnit Class  import java.util.concurrent.*;import java.util.Calendar;  class GFG {    public static void main(String args[])    {        // Get current time in milliseconds        long timeInMilliSec = Calendar                                  .getInstance()                                  .getTimeInMillis();          // Create a TimeUnit object        TimeUnit time = TimeUnit.MILLISECONDS;          // Convert milliseconds to Seconds        // using toSeconds() method        System.out.println("Time " + timeInMilliSec                           + " milliSeconds in Seconds = "                           + time.toSeconds(timeInMilliSec));    }}
Time 1539585659342 milliSeconds in Seconds = 1539585659

Java - util package
Java-Functions
Java-TimeUnit
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
range() to a list in Python

30 Jan, 2019
Often times we want to create a list containing a continuous value like, in a range of 100-200. Let’s discuss how to create a list using the range() function.
Will this work ?
# Create a list in a range of 10-20My_list = [range(10, 20, 1)]  # Print the listprint(My_list)
Output :As we can see in the output, the result is not exactly what we were expecting because Python does not unpack the result of the range() function.
Code #1: We can use argument-unpacking operator i.e. *.
# Create a list in a range of 10-20My_list = [*range(10, 21, 1)]  # Print the listprint(My_list)
Output :As we can see in the output, the argument-unpacking operator has successfully unpacked the result of the range function. Code #2 : We can use the extend() function to unpack the result of range function.
# Create an empty listMy_list = []  # Value to begin and end withstart, end = 10, 20  # Check if start value is smaller than end valueif start < end:    # unpack the result    My_list.extend(range(start, end))    # Append the last value    My_list.append(end)  # Print the listprint(My_list)
Output :
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python | os.path.join() method
Java Examples - Draw text using GUI

How to draw text using GUI?
Following example demonstrates how to draw text drawString(), setFont() methods of Graphics class.
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel{
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;
      g2.setRenderingHint(
         RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      
      Font font = new Font("Serif", Font.PLAIN, 96);
      g2.setFont(font);
      g2.drawString("Text", 40, 120);
   }
   public static void main(String[] args) {
      JFrame f = new JFrame();
      f.getContentPane().add(new Main());
      f.setSize(300, 200);
      f.setVisible(true);
   }
}
The above code sample will produce the following result.
Text is displayed in a frame.

The following is an example to draw text using GUI.
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Panel extends JPanel {
   public void paint(Graphics gr) {
      Graphics2D g = (Graphics2D)gr;
      g.setRenderingHint(
         RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     
      Font font = new Font("Serif", Font.PLAIN, 96);
      g.setFont(font);
      g.drawString("Tutorialspoint", 40, 120);
   } 
   public static void main(String[] args) {
      JFrame f = new JFrame();
      f.getContentPane().add(new Panel());
      f.setSize(300, 200);
      f.setVisible(true);
   } 
}
The above code sample will produce the following result.
Text is displayed in a frame.
What are the differences between while loop and do-while loop in Java?

The while loop in java executes one or more statements after testing the loop continuation condition at the start of each iteration. The do-while loop, however, tests the loop continuation condition after the first iteration has completed. Therefore, the do-while loop guarantees one execution of the loop logic whereas the while does not.
public class WhileAndDoWhileLoop {
   public static void main(String args[]) {
      int i=5;
      System.out.println("Test while Loop:");
      while(i < 5) {
         System.out.println("Iteration: "+ ++i);
      }
      System.out.println("Test do-while Loop:");
      i=5;
      do {
         System.out.println("Iteration: "+ ++i);
      } while(i < 5);
   }
}
In the above example, The while loop statement will not execute at all. However, one iteration of the do-while loop will execute.
Test while Loop:
Test do-while Loop:
Iteration: 6
Elixir - Maps

Keyword lists are a convenient way to address content stored in lists by key, but underneath, Elixir is still walking through the list. That might be suitable if you have other plans for that list requiring walking through all of it, but it can be an unnecessary overhead if you are planning to use keys as your only approach to the data.
This is where maps come to your rescue. Whenever you need a key-value store, maps are the “go to” data structure in Elixir.
A map is created using the %{} syntax −
map = %{:a => 1, 2 => :b}
Compared to the keyword lists, we can already see two differences −
Maps allow any value as a key.
Maps’ keys do not follow any ordering.
In order to acces value associated with a key, Maps use the same syntax as Keyword lists −
map = %{:a => 1, 2 => :b}
IO.puts(map[:a])
IO.puts(map[2])
When the above program is run, it generates the following result −
1
b

To insert a key in a map, we use the Dict.put_new function which takes the map, new key and new value as arguments −
map = %{:a => 1, 2 => :b}
new_map = Dict.put_new(map, :new_val, "value") 
IO.puts(new_map[:new_val])
This will insert the key-value pair :new_val - "value" in a new map. When the above program is run, it generates the following result −
"value"

To update a value already present in the map, you can use the following syntax −
map = %{:a => 1, 2 => :b}
new_map = %{ map | a: 25}
IO.puts(new_map[:a])
When the above program is run, it generates the following result −
25

In contrast to keyword lists, maps are very useful with pattern matching. When a map is used in a pattern, it will always match on a subset of the given value −
%{:a => a} = %{:a => 1, 2 => :b}
IO.puts(a)
The above program generates the following result −
1

This will match a with 1. And hence, it will generate the output as 1.
As shown above, a map matches as long as the keys in the pattern exist in the given map. Therefore, an empty map matches all maps.
Variables can be used when accessing, matching and adding map keys −
n = 1
map = %{n => :one}
%{^n => :one} = %{1 => :one, 2 => :two, 3 => :three}
The Map module provides a very similar API to the Keyword module with convenience functions to manipulate maps. You can use functions such as the Map.get, Map.delete, to manipulate maps.
Maps come with a few interesting properties. When all the keys in a map are atoms, you can use the keyword syntax for convenience −
map = %{:a => 1, 2 => :b} 
IO.puts(map.a) 
Another interesting property of maps is that they provide their own syntax for updating and accessing atom keys −
map = %{:a => 1, 2 => :b}
IO.puts(map.a)
The above program generates the following result −
1

Note that to access atom keys in this way, it should exist or the program will fail to work.

    35 Lectures 
     3 hours 

 Pranjal Srivastava

    54 Lectures 
     6 hours 

 Pranjal Srivastava, Harshit Srivastava

    80 Lectures 
     9.5 hours 

 Pranjal Srivastava

    43 Lectures 
     4 hours 

 Mohammad Nauman
 Print
 Add Notes
 Bookmark this page
PostgreSQL - PERCENT_RANK Function - GeeksforGeeks

10 Feb, 2021
In PostgreSQL, the PERCENT_RANK() function is used to evaluate the relative ranking of a value within a given set of values.
The syntax of the PERCENT_RANK() function:
Syntax:
PERCENT_RANK() OVER (
    [PARTITION BY partition_expression, ... ]
    ORDER BY sort_expression [ASC | DESC], ...
)

Let’s analyze the above syntax:
The PARTITION BY is an optional clause that is used with the PERCENT_RANK() function to divide rows into multiple partitions. It defaults to a single set.
The ORDER BY clause is used to set the order in which the resultant query is returned.
The PERCENT_RANK() function always returns value that is greater than 0 and less than or equal to 1.
Example 1:
First, create two tables named products and product_groups:
CREATE TABLE product_groups (
    group_id serial PRIMARY KEY,
    group_name VARCHAR (255) NOT NULL
);

CREATE TABLE products (
    product_id serial PRIMARY KEY,
    product_name VARCHAR (255) NOT NULL,
    price DECIMAL (11, 2),
    group_id INT NOT NULL,
    FOREIGN KEY (group_id) REFERENCES product_groups (group_id)
);


Now add some data to it:
INSERT INTO product_groups (group_name)
VALUES
    ('Smartphone'),
    ('Laptop'),
    ('Tablet');

INSERT INTO products (product_name, group_id, price)
VALUES
    ('Microsoft Lumia', 1, 200),
    ('HTC One', 1, 400),
    ('Nexus', 1, 500),
    ('iPhone', 1, 900),
    ('HP Elite', 2, 1200),
    ('Lenovo Thinkpad', 2, 700),
    ('Sony VAIO', 2, 700),
    ('Dell Vostro', 2, 800),
    ('iPad', 3, 700),
    ('Kindle Fire', 3, 150),
    ('Samsung Galaxy Tab', 3, 200);

The following statement uses the PERCENT_RANK() function to calculate the sales percentile of each employee in 2019:
SELECT 
    name,
    amount,
    PERCENT_RANK() OVER (
        ORDER BY amount
    )
FROM 
    sales_stats
WHERE 
    year = 2019;

Output:
Example 2:
The below statement uses the PERCENT_RANK() function to calculate the sales amount percentile by sales employees in both 2018 and 2019:
SELECT 
    name,
    amount,
    PERCENT_RANK() OVER (
        PARTITION BY year
        ORDER BY amount
    )
FROM 
    sales_stats;

Output:
PostgreSQL-function
PostgreSQL-Window-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - ROW_NUMBER Function
PostgreSQL - LEFT JOIN
PostgreSQL - Copy Table
PostgreSQL - Cursor
PostgreSQL - Record type variable
PostgreSQL - SELECT
PostgreSQL - TEXT Data Type
PostgreSQL - Select Into
Simpson's 1/3 Rule for definite integral

Like the Trapezoidal Rule, Simpson’s 1/3rd rule is also used to find the integral value from the range a to b. The main difference between trapezoidal and the Simpson’s 1/3rd rule is, in the trapezoidal rule, the whole sections are divided into some trapezoids, but in this case, each trapezoid are also divided into two parts.
For this rule, we will follow this formula:
Here h is the width of the interval, and n is the number of intervals. We can find the h by using 
Input:
The function f(x): (x+(1/x). The lower and upper limit: 1, 2. The number of intervals: 20.
Output:
The answer is: 2.19315
integrateSimpson(a, b, n)
Input − The lower and upper limit of the integral and number of intervals n.
Output − The result after integration.
Begin
   h := (b - a)/n
   res := f(a) + f(b)
   lim := n/2

   for i := 1 to lim, do
      oddSum := oddSum + f(a + (2i - 1)h)
   done

   oddSum := oddSum * 4
   for i := 1 to lim-1, do
      evenSum := evenSum + f(a + 2ih)
   done

   evenSum := evenSum * 2
   res := res + oddSum + evenSum
   res := res * (h/3)
   return res
End
#include<iostream>
#include<cmath>
using namespace std;

float mathFunc(float x) {
   return (x+(1/x));    //function 1 + 1/x
}

float integrate(float a, float b, int n) {
   float h, res = 0.0, oddSum = 0.0, evenSum = 0.0, lim;
   int i;
   h = (b-a)/n;    //calculate the distance between two interval
   res = (mathFunc(a)+mathFunc(b));    //initial sum using f(a) and f(b)
   lim = n/2;

   for(i = 1; i<=lim; i++)
      oddSum += mathFunc(a+(2*i-1)*h);    //sum of numbers, placed at odd number
   oddSum *= 4;    //odd sum are multiplied by 4

   for(i = 1; i<lim; i++)
      evenSum += mathFunc(a+(2*i)*h);    //sum of numbers, placed at even number
   evenSum *= 2;    //even sum are multiplied by 2
   res += oddSum+evenSum;
   res *= (h/3);
   return res;    //The result of integration
}

main() {
   float result, lowLim, upLim;
   int interval;
   cout << "Enter Lower Limit, Upper Limit and interval: ";
   cin >>lowLim >>upLim >>interval;
   result = integrate(lowLim, upLim, interval);
   cout << "The answer is: " << result;
}
Enter Lower Limit, Upper Limit and interval: 1 2 20
The answer is: 2.19315
C library function - ldexp()

The C library function double ldexp(double x, int exponent) returns x multiplied by 2 raised to the power of exponent.
Following is the declaration for ldexp() function.
double ldexp(double x, int exponent)
x − This is the floating point value representing the significand.
x − This is the floating point value representing the significand.
exponent − This is the value of the exponent.
exponent − This is the value of the exponent.
This function returns x * 2 exp
The following example shows the usage of ldexp() function.
#include <stdio.h>
#include <math.h>

int main () {
   double x, ret;
   int n;

   x = 0.65;
   n = 3;
   ret = ldexp(x ,n);
   printf("%f * 2^%d = %f\n", x, n, ret);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
0.650000 * 2^3 = 5.200000


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
What happens if I will delete a row from MySQL parent table?

While deleting the row from the parent table, if the data of that row is used in the child table then MySQL will throw an error because of the failure of FOREIGN KEY constraint. It can be understood with the example of two tables named ‘customer’ and ‘orders’. Here, ‘customer’ is the parent table and ‘orders’ is the child table. We cannot delete a row, that is used in child table ‘orders’, from the ‘customer’ table. It can be demonstrated by deleting the values from the parent table as follows −
mysql> Select * from Customer;
+----+--------+
| id | name   |
+----+--------+
| 1  | Gaurav |
| 2  | Raman  |
| 3  | Harshit|
| 4  | Aarav  |
+----+--------+
4 rows in set (0.00 sec)

mysql> Select * from orders;
+----------+----------+------+
| order_id | product  | id   |
+----------+----------+------+
| 100      | Notebook | 1    |
| 110      | Pen      | 1    |
| 120      | Book     | 2    |
| 130      | Charts   | 2    |
+----------+----------+------+
4 rows in set (0.00 sec)
Now, suppose if we will try to delete the row having id = 1 or id =2 (because of both the rows used in child table) from parent table ‘customer’, then MySQL throws an error as follows due to the failure of foreign key constraint.
mysql> Delete from customer where id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`)REFERENCES `customer` (`id`))

mysql> Delete from customer where id = 2;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`)REFERENCES `customer` (`id`))
How to Find the Last Used Row and Column in Excel VBA? - GeeksforGeeks

09 Nov, 2021
We use  Range.SpecialCells() method in the below VBA Code to find and return details of last used row, column, and cell in a worksheet.
Sample Data:
Sample Data
Syntax:
expression.SpecialCells (Type, Value)
Eg: To return the last used cell address in an activesheet. ActiveSheet.Range(“A1”).SpecialCells(xlCellTypeLastCell).Address
VBA Code:
Declaring Variables:
'Variable Declaration

Dim LastRow As Long, LastCol As Long, LastCell As String
Use SpecialCells function to find last used row/column/cell 
'Find Last Used Row
LastRow = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Row

'Find Last Used Column
LastCol = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Column

'Find Last Used Cell
LastCell = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Address
Concatenate all three variables (LastRow/LastCol/LastCell), add a new line between variables use Chr(10).   Show the final output in an Excel Message box.
'Display the last used row/column/cell

MsgBox "Last Used Row : " & LastRow & Chr(10) & "Last Used Column : " & LastCol & Chr(10) & "Last Used Cell : " & LastCell
Follow the below steps to find the Last Used Row and Last Used Column in Excel VBA
Step 1: Add a shape (Find Last Row/Column/Cell) on your worksheet.  
Step 2: Right-click on “Find Last Row/Column/Cell” and “Assign Macro..”
Step 3: Select “findLastUsedCell”, you can see a list of macros if available in your workbook
Step 4: Save your excel file as “Excel Macro-Enabled Workbook” *.xlsm
Step 5: Click “Find Last Row/Column/Cell” to execute the VBA code.  Code will popup below output for the above given example (Output).
Output:
Excel-VBA
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Excel Spreadsheet
How to Use Solver in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
Using CHOOSE Function along with VLOOKUP in Excel
How to Remove Duplicates From Array Using VBA in Excel?
How to Get Length of Array in Excel VBA?
Macros in Excel
How to Check if the Number is Prime Number in Excel?
How to Extract the Last Word From a Cell in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
Tokenizing a string in C++

In this section, we will see how to tokenize strings in C++. In C we can use the strtok() function for the character array. Here we have a string class. Now we will see how to cut the string using some delimiter from that string.
To use the C++ feature, we have to convert a string to a string stream. Then using getline() function we can do the task. The getline() function takes the string stream, another string to send the output, and the delimiter to stop the stream from scanning.
Let us see the following example to understand how the function is working.
 Live Demo
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

int main() {
   string my_string = "Hello,World,India,Earth,London";
   stringstream ss(my_string); //convert my_string into string stream

   vector<string> tokens;
   string temp_str;

   while(getline(ss, temp_str, ',')){ //use comma as delim for cutting string
      tokens.push_back(temp_str);
   }
   for(int i = 0; i < tokens.size(); i++) {
      cout << tokens[i] << endl;
   }
}
Hello
World
India
Earth
London
std::multiplies in C++ - GeeksforGeeks

02 Aug, 2017
Function object for performing multiplication. Effectively calls operator* on two instances of type T.
Syntax :
template  struct multiplies : binary_function  
{
    T operator() (const T& x, const T& y) const {return x*y;}
};

Template Parameters :
T - Type of the arguments and return type of the functional call.
    The type shall support the operation (operator*).

Member types :
x : Type of the first argument in member operator()
y : Type of the second argument in member operator()
result_type : Type returned by member operator()

Example :
// C++ program to illustrate std::multiplies// by multiplying the respective elements of 2 arrays#include <iostream> // std::cout#include <functional> // std::multiplies#include <algorithm> // std::transform  int main(){    // First array    int first[] = { 1, 2, 3, 4, 5 };      // Second array    int second[] = { 10, 20, 30, 40, 50 };      // Result array    int results[5];      // std::transform applies std::multiplies to the whole array    std::transform(first, first + 5, second, results, std::multiplies<int>());      // Printing the result array    for (int i = 0; i < 5; i++)        std::cout << results[i] << " ";      return 0;}
Output:
10 40 90 160 250 

Another Example :
// C++ program to illustrate std::multiplies// by multiplying all array elements with a number#include <bits/stdc++.h>  int main(){    // Array with elements to be multiplying    int arr[] = { 10, 20, 30 };      // size of array    int size = sizeof(arr) / sizeof(arr[0]);      // Variable with which array is to be multiplied    int num = 10;      // Variable to store result    int result;      // using std::accumulate to perform multiplication on array with num    // using std::multiplies    result = std::accumulate(arr, arr + size, num, std::multiplies<int>());      // Printing the result    std::cout << "The result of 10 * 10 * 20 * 30 is " << result;      return 0;}
Output:
60000

This article is contributed by Rohit Thapliyal. 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.
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
new and delete operators in C++ for dynamic memory
Destructors in C++
C Program for Extended Euclidean algorithms?

Here we will see the extended Euclidean algorithm implemented using C. The extended Euclidean algorithm is also used to get the GCD. This finds integer coefficients of x and y like below −
ax+by = gcd(a,b)
Here in this algorithm it updates the value of gcd(a, b) using the recursive call like this − gcd(b mod a, a). Let us see the algorithm to get the idea
begin
   if a is 0, then
      x := 0
      y := 1
      return b
   end if
   gcd := EuclideanExtended(b mod a, a, x1, y1)
   x := y1 – (b/a)*x1
   y := x1
   return gcd
end
 Live Demo
#include <stdio.h>
int EuclideanExtended(int a, int b, int* x, int* y) {
   if (a == 0) {
      *x = 0;
      *y = 1;
      return b;
   }
   int xtemp, ytemp; // To store results of recursive call
   int res = EuclideanExtended(b % a, a, &xtemp, &ytemp);
   *x = ytemp - (b / a) * xtemp;
   *y = xtemp;
   return res;
}
int main() {
   int x, y;
   int a = 60, b = 25;
   int res = EuclideanExtended(a, b, &x, &y);
   printf("gcd(%d, %d) = %d", a, b, res);
}
gcd(60, 25) = 5
C++ program to Convert a Decimal Number to Binary Number using Stacks

In this problem, we will see how to convert a decimal number to binary numbers using stacks. As we know that the decimal numbers can be converted using binary after dividing it by 2 and taking the remainder. We take the remainder from last to first, so we can easily use the stack data structure to do that.
Input: Decimal number 13
Output: Binary number 1101
Step 1: Take a number in decimal
Step 2: while the number is greater than 0:
Step 2.1: Push the remainder after dividing the number by 2 into stack.
Step 2.2: set the number as number / 2.
Step 3: Pop elements from stack and print the binary number
 Live Demo
#include<iostream>
#include<stack>
using namespace std;
void dec_to_bin(int number) {
   stack<int> stk;
   while(number > 0) {
      int rem = number % 2; //take remainder
      number = number / 2;
      stk.push(rem);
   }
   while(!stk.empty()) {
      int item;
      item = stk.top();
      stk.pop();
      cout << item;
   }
}
main() {
   int num;
   cout << "Enter a number: ";
   cin >> num;
   dec_to_bin(num);
}
Enter a number: 18
10010
Copy constructor vs assignment operator in C++

The Copy constructor and the assignment operators are used to initializing one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space. It uses the reference variable to point to the previous memory block.
classname (const classname &obj) {
   // body of constructor
}
classname Ob1, Ob2;
Ob2 = Ob1;
Let us see the detailed differences between Copy constructor and Assignment Operator.
How can I close a specific window using Selenium WebDriver with Java?

We can close a specific window with Selenium webdriver. The getWindowHandles and getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure.
The getWindowHandle method is used to store the window handle of the browser window in focus. We have to add import java.util.Set and import java.util.List statements to accommodate Set data structure in our code.
By default, the driver object can only access the elements of the parent window. In order to switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
public class CloseSpecificWindow {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://secure.indeed.com/account/login");
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //window handle of parent window
      String m = driver.getWindowHandle();
      driver.findElement(By.id("login-google-button")).click();
      // store window handles in Set
      Set w = driver.getWindowHandles();
      // iterate window handles
      for (String h: w){
         // switching to each window
         driver.switchTo().window(h);
         String s= driver.getTitle();
         // checking specific window title
         if(s.equalsIgnoreCase("Sign in - Google Accounts")){
            System.out.println("Window title to be closed: "+ driver.getTitle());
            driver.close();
         }
      }
      // switching parent window
      driver.switchTo().window(m);
      driver.quit();
   }
}
p5.js | play() Function - GeeksforGeeks

17 Jan, 2020
The play() function is an inbuilt function in p5.js library. This function is used to play the loaded audio on the web. The play function should call after the loadSound() function. If you call before that it has nothing to play so it will show loading nothing else will happen ever.
Syntax:
play( startTime, rate, amp, cueStart, duration )
Parameter: This function accepts five parameters as mentioned above and described below:
startTime: This parameter holds an integer number as seconds that defines the scheduled playback and it is an optional parameter.
rate: This parameter holds an integer number that defines playback rate and it is an optional parameter.
amp: This parameter holds an integer number that defines the amplitude of the playback and it is an optional parameter.
cueStart: This parameter holds an integer number as seconds that defines the cue start time in seconds and it is an optional parameter.
duration: This parameter holds an integer number that defines duration of playback in seconds and it is an optional parameter.
Below given example illustrate the p5.js play() function in JavaScript:Example:
var sound;   function preload() {       // Initialize sound     sound = loadSound("pfivesound.mp3"); }   function setup() {       // Playing the preloaded sound     sound.play(); } 
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Supported Browsers: The browsers are supported by p5.js play() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
C++ Program to Check if a Given Set of Three Points Lie on a Single Line or Not

This is a C++ program to check if a given set of three points lie on a single line or not. Three points lie on a single line if the area of the triangle formed by this points is equal to zero.
The area of the triangle is −
0.5 * (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)).
Begin
   Generate the points randomly.
   Calculate the area by using above formula.
   If area > 0
      Then the points don't lie on the straight line.
   else if area < 0
      Then the points don't lie on the straight line.
   else
      The points lie on the straight line.
End
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
static int L = 1;
static int U= 20;
int main(int argc, char **argv) {
   int x3, y3, x1, x2, y1, y2;
   time_t seconds;
   time(&seconds);
   srand((unsigned int) seconds);
   //Generate the points randomly using rand().
   x1 = rand() % ( U- L+ 1) + L;
   y1 = rand() % (U - L+ 1) + L;
   x2 = rand() % (U - L + 1) + L;
   y2 = rand() % (U - L+ 1) + L;
   x3 = rand() % (U - L+ 1) + L;
   y3 = rand() % (U - L+ 1) + L;
   cout << "The points are: (" << x1 << ", " << y1 << "), (" << x2 << ", " << y2 << "), & (" << x3 << ", " << y3 << ")\n";
   //calculate area
   float a = 0.5 *(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
   if (a < 0)
      cout << "The points don't lie on the straight line";
   else if (a > 0)
      cout << "The points don't lie on the straight line ";
   else
      cout << "The points lie on the straight line";
}
The points are: (20, 9), (6, 13), & (13, 11)
The points lie on the straight line

The points are: (9, 15), (4, 15), & (11, 16)
The points don't lie on the straight line
Python Operators

Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
Assignment operators are used to assign values to variables:
Comparison operators are used to compare two values:
Logical operators are used to combine conditional statements:
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
Membership operators are used to test if a sequence is presented in an object:
Bitwise operators are used to compare (binary) numbers:
Multiply 10 with 5, and print the result.
print(10  5)

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

13 Jan, 2022
The emptyList() method of Java Collections returns the list with no elements. This method is immutable. That is, we can not do any modifications after creating this method.
Syntax:
public static final <T> List<T> emptyList()  
Parameters: It will not accept any parameters
Return: This method will return an empty list
Example 1: 
Java
// Java program to create an empty listimport java.util.*; public class GFG {     public static void main(String[] args)    {        // create a list that is empty        List<String> mylist            = Collections.<String>emptyList();                     // display the list        System.out.println(mylist);    }}
[]
Example 2:
Java
// Java program to show an exception// when adding the elements to the listimport java.util.*; public class GFG {     public static void main(String[] args)    {        // create a list that is empty        List<Integer> mylist            = Collections.<Integer>emptyList();         // add 5 elements to the created list        mylist.add(1);        mylist.add(2);        mylist.add(3);        mylist.add(4);        mylist.add(5);         // display the list        System.out.println(mylist);    }}
Output:
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at GFG.main(GFG.java:11)
adnanirshad158
Java-Collections-Class
Java-Functions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
How to read command line arguments in Node.js ? - GeeksforGeeks

01 Apr, 2022
Command-line arguments (CLI) are strings of text used to pass additional information to a program when an application is running through the command line interface of an operating system. We can easily read these arguments by the global object in node i.e. process object.
Below is the approach with the proper example.
Example 1:
Step 1: Save a file as index.js and paste the below code inside the file.var arguments = process.argv ;  console.log(arguments) ;
var arguments = process.argv ;  console.log(arguments) ;
Step 2: Run index.js file using below command:node index.js
node index.js
Output:
The process.argv contains an array where the 0th index contains the node executable path, 1st index contains the path to your current file and then the rest index contains the passed arguments.
Example 2: Program to add two numbers passed as arguments.
Step 1: Save the file as index1.js and paste the below code inside the file.var arguments = process.argv  function add(a, b) {      // To extract number from string    return parseInt(a)+parseInt(b) }  var sum = add(arguments[2], arguments[3])  console.log("Addition of 2, 3 is ", sum)
var arguments = process.argv  function add(a, b) {      // To extract number from string    return parseInt(a)+parseInt(b) }  var sum = add(arguments[2], arguments[3])  console.log("Addition of 2, 3 is ", sum)
Step 2: Run index1.js file using below command:node index1.js 2 3
node index1.js 2 3
Output:
So this is how we can handle arguments in Node.js. The args module is very popular for handling command-line arguments. It provides various features like adding our own command to work and so on.
bunnyram19
guptaweber
Node.js-Basics
Node.js-Misc
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await 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 ?
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
BigDecimal min() Method in Java - GeeksforGeeks

04 Dec, 2018
The java.math.BigDecimal.min(BigDecimal val) method in Java is used to compare two BigDecimal values and return the minimum of the two.
Syntax:
public BigDecimal min(BigDecimal val)
Parameters: The function accepts a BigDecimal object val as parameter whose value is compared with that of this BigDecimal object and the minimum value is returned.
Return Values: This method returns the BigDecimal whose value is the smaller of this BigDecimal and val. In case if both are equal, this BigDecimal is returned.
Examples:
Input :  a = 17.000041900, b = 17.0000418999
Output : 17.0000418999

Input : a = 235900000146, b = 236000000000
Output : 235900000146

Below programs will illustrate min() function of BigDecimal class:
Program 1:
/*Java program to illustrateuse of BigDecimal min() function in Java      */import java.math.*;  public class GFG {      public static void main(String[] args)    {          // Creating 2 BigDecimal objects        BigDecimal a, b;          a = new BigDecimal("17.000041900");        b = new BigDecimal("17.0000418999");          // print the maximum value        System.out.println("Minimum Value among " + a +                         " and " + b + " is " + a.min(b));    }}
Minimum Value among 17.000041900 and 17.0000418999 is 17.0000418999

Program 2:
/*Java program to illustrateuse of BigDecimal min() to display minimum lengthamong two strings  */import java.math.*;  public class GFG {      public static void main(String[] args)    {          // Create 2 BigDecimal objects        BigDecimal a, b;        String s = "GeeksforGeeks";        String str = "GeeksClasses";          int l1, l2;        l1 = s.length();        l2 = str.length();          a = new BigDecimal(l1);        b = new BigDecimal(l2);          // Print the respective lengths        System.out.println("Length of string " + s + " is " + a);        System.out.println("Length of string " + str + " is " + b);        // Print the maximum value        System.out.println("Minimum length is " + a.min(b));    }}
Length of string GeeksforGeeks is 13
Length of string GeeksClasses is 12
Minimum length is 12

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#min()
Java-BigDecimal
Java-Functions
java-math
Java-math-package
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
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Reverse a number in PL/SQL - GeeksforGeeks

20 Nov, 2019
Prerequisite – PL/SQL introduction
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements.In declare part, we declare variables and between begin and end part, we perform the operations.
Explanation:Consider the example, input = 12345.
Step 1 : mod(12345,10) = 5rev:= 0*10 + 5 = 5num = floor(12345/10) = 1234
Step 2 : mod(1234,10) = 4rev:= 5*10 + 4 = 54num = floor(1234/10) = 123
Step 3 : mod(123,10) = 3rev:= 54*10 + 3 = 543num = floor(123/10) = 12
Step 4 : mod(12,10) = 2rev:= 543*10 + 2 = 5432num = floor(12/10) = 1
Step 5 : mod(1,10) = 1rev:= 5432*10 + 1 = 54321num = floor(1/10) = 0in step 5, num =0 which doesn’t satisfy the while condition and loop terminates.
rev = 54321
More examples:
Input : 123456
Output :654321

Input :87459
Output :95478

Below is the required implementation:
SET SERVEROUTPUT ON;DECLARE-- declare a number 'num' for reading actual input-- declare another number 'rev' that would be reverse of numnum NUMBER;rev NUMBER;  BEGIN-- & is used to read input from keyboardnum:=#-- initialize rev to 0rev:=0;-- the loop runs until num is greater than 0WHILE num>0 LOOP-- mod function is used to find the modulus/ remainder of num when divided by 10  rev:=(rev*10) + mod(num,10);-- floor function is used to obtain a result which is an integernum:=floor(num/10);END LOOP;DBMS_OUTPUT.PUT_LINE('Reverse of the number is: ' || rev);END;/                          -- Program End
Output:
Enter value for num : 157439
Reverse of the number is: 934751


charutory
SQL-PL/SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
Difference between Clustered and Non-clustered index
Data Preprocessing in Data Mining
Difference between SQL and NoSQL
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL Interview Questions
SQL | ALTER (RENAME)
CTE in SQL