code-rag-bench/online-tutorials huggingface dataset:
Operating Systems | Set 10

13 Apr, 2018
Following questions have been asked in GATE 2008 CS exam.
1) The data blocks of a very large file in the Unix file system are allocated using(A) contiguous allocation(B) linked allocation(C) indexed allocation(D) an extension of indexed allocation
Answer (D)The Unix file system uses an extension of indexed allocation. It uses direct blocks, single indirect blocks, double indirect blocks and triple indirect blocks. Following diagram shows implementation of Unix file system.
2) The P and V operations on counting semaphores, where s is a counting semaphore, are defined as follows:
P(s) : s =  s - 1;
  if (s  < 0) then wait;
V(s) : s = s + 1;
  if (s <= 0) then wakeup a process waiting on s;

Assume that Pb and Vb the wait and signal operations on binary semaphores are provided. Two binary semaphores Xb and Yb are used to implement the semaphore operations P(s) and V(s) as follows:
P(s) : Pb(Xb);
  s = s - 1;
  if (s < 0) {
   Vb(Xb) ;
   Pb(Yb) ;
  }
  else Vb(Xb); 


V(s) : Pb(Xb) ;
  s = s + 1;
  if (s <= 0) Vb(Yb) ;
  Vb(Xb) ;

The initial values of Xb and Yb are respectively(A) 0 and 0(B) 0 and 1(C) 1 and 0(D) 1 and 1
Answer (C)Both P(s) and V(s) operations are perform Pb(xb) as first step. If Xb is 0, then all processes executing these operations will be blocked. Therefore, Xb must be 1.If Yb is 1, it may become possible that two processes can execute P(s) one after other (implying 2 processes in critical section). Consider the case when s = 1, y = 1. So Yb must be 0.
3) Which of the following statements about synchronous and asynchronous I/O is NOT true?(A) An ISR is invoked on completion of I/O in synchronous I/O but not in asynchronous I/O(B) In both synchronous and asynchronous I/O, an ISR (Interrupt Service Routine) is invoked after completion of the I/O(C) A process making a synchronous I/O call waits until I/O is complete, but a process making an asynchronous I/O call does not wait for completion of the I/O(D) In the case of synchronous I/O, the process waiting for the completion of I/O is woken up by the ISR that is invoked after the completion of I/O
Answer (B)An interrupt service routine will be invoked after the completion of I/O operation and it will place process from block state to ready state, because process performing I/O operation was placed in blocked state till the I/O operation was completed in Synchronous I/O.
However, process performing I/O will not be placed in the block state and process continues to execute the remaining instructions in Asynchronous I/O, because handler function will be registered while performing the I/O operation, when the I/O operation completed signal mechanism is used to notify the process that data is available.
So, option (B) is false.
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
GATE-CS-2008
GATE CS
MCQ
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Swift Programming Language

20 Oct, 2021
Swift is a general-purpose, multi-paradigm, object-oriented, functional, imperative and block-structured language. Swift is the result of the latest research on programming languages and is built using a modern approach to safety, software design patterns by Apple Inc. for iOS applications, macOS applications, watchOS applications, tvOS applications. Swift is easy to learn, easy to implement, safe, fast and expressive. Developing Swift in the open has its exciting aspects as it is now free to be ported across a wide range of platforms, devices, and use cases.The features of Swift are designed to work together to create a powerful language. Additional features of Swift include:  
Closures unified with function pointers
Tuples and multiple return values
Generics
Concise and fast iteration over a range or collection
Structs that support methods, extensions, and protocols
Functional programming patterns, e.g., map and filter
Powerful error handling built-in
Advanced control flow with do, guard, defer, and repeat keywords
Memory Management – Swift uses Automatic Reference Counting (ARC) to manage memory. Earlier, Apple used to require manual memory management in Objective-C, but after introducing ARC in 2011 memory allocation and de-allocation became easier.Swift is managed as a collection of projects, each with its repositories. The current list of projects include:  
The Swift compiler command-line tool
The standard library bundled as part of the language
Core libraries that provide higher-level functionality
The Swift REPL included LLDB debugger
Xcode playground support to enable playgrounds in Xcode.
The Swift package manager for distributing and building Swift source code
Example:  
Swift
var str1 = "Hello geeks!"var str2 = "How are you?"print (str1)print (str2)
Output:  
Hello geeks!
How are you?
Run: Code can be tested on Online IDE for Swift Note: Import statement is used to import any objective-C framework or library directly into Swift program. var keyword is used for variable and let keyword is used for constant. There is no need for”;” for termination, in case the programmer uses it compiler won’t show an error. Advantages – 
Swift is open-sourced and easy to learn.
Swift is fast, safe and expressive.
Swift is approachable and familiar (C and C++ code can be added by Swift programmers into Swift applications.)
Swift is the future of Apple development.
Swift is enterprise-ready.
Disadvantages –
The language is still quite young and the talent pool is limited.
Swift is considered a “moving target” as it is a new language and the number of swift programmers is few.
Poor interoperability with third-party tools and IDEs
Lack of support for earlier iOS versions.
 
iamabhijha
Misc
Programming Language
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | rotate() function

22 Apr, 2019
The rotate() function in p5.js is used to rotate a shape or the object using p5.js to a specified axis over a specified angle.
Syntax:
rotate(angle, [axis])

Parameters: The function accepts single parameter as mentioned above and described below:
angle: The angle of rotation which specified in radians or degrees.
axis: the axis to rotate around
Below program illustrates the rotate() function in p5.js:Example-1:
function setup() {        // Create Canvas of given size    createCanvas(380, 170);}  function draw() {        // Set the background color    background(220);        strokeWeight(12);        //set strokeJoin function    strokeJoin(ROUND);        // rotation function    rotate(PI / 10.0);    line(20, 30, 200, 30);    line(200, 30, 200, 100);    line(200, 100, 20, 30);}
Output:
Example-2:
function setup() {        // Create Canvas of given size    createCanvas(380, 170);}  function draw() {        // Set the background color    background(220);        strokeWeight(12);        // rotation function    rotate(PI / 7.0);    textSize(30);    text("GeeksForGeeks", 50, 50);}
Output:
Reference: https://p5js.org/reference/#/p5/rotate
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Map put() Method in Java with Examples

02 Jan, 2019
This method is used to associate the specified value with the specified key in this map.
Syntax:
V put(K key,
    V value)
Parameters: This method has two arguments, key and value where key is the left argument and value is the corresponding value of the key in the map.
Returns: This method returns returns previous value associated with the key if present, else return -1.
Below programs show the implementation of int put() method.
Program 1:
// Java code to show the implementation of// put method in Map interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a Map of type HashMap        Map<Integer, String> map = new HashMap<>();        map.put(1, "One");        map.put(3, "Three");        map.put(5, "Five");        map.put(7, "Seven");        map.put(9, "Ninde");        System.out.println(map);    }}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Ninde}

Program 2: Below is the code to show implementation of put().
// Java code to show the implementation of// put method in Map interfaceimport java.util.*;public class GfG {      // Driver code    public static void main(String[] args)    {          // Initializing a Map of type HashMap        Map<String, String> map = new HashMap<>();        map.put("1", "One");        map.put("3", "Three");        map.put("5", "Five");        map.put("7", "Seven");        map.put("9", "Ninde");        System.out.println(map);    }}
{1=One, 3=Three, 5=Five, 7=Seven, 9=Ninde}

Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2017 (Set 2) | Question 60

28 Jun, 2021
In a B+ tree, if the search-key value is 8 bytes long, the block size is 512 bytes and the block pointer is 2 bytes, then the maximum order of the B+ tree is ____.
Note: This question appeared as Numerical Answer Type.(A) 51(B) 52(C) 53(D) 54Answer: (B)Explanation:
Order of a B+ tree node is maximum number of children 
in an internal node

Let the order be x. Number of keys in a node is equal to
number children minus 1.
So a full node has (x-1) keys and x children.

(x-1)*(search key) + x * block ptr <= block size
==> (x-1)*8 + x*2 <= 512
==> 10x <= 520
==> x <= 52
Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2001 | Question 50
GATE | Gate IT 2005 | Question 52
Explain BCNF with an example in DBMS

BCNF (Boyce Codd Normal Form) is the advanced version of 3NF. A table is in BCNF if every functional dependency X->Y, X is the super key of the table. For BCNF, the table should be in 3NF, and for every FD. LHS is super key.
Consider a relation R with attributes (student, subject, teacher).
F: { (student, Teacher) -> subject
(student, subject) -> Teacher
Teacher -> subject}
Candidate keys are (student, teacher) and (student, subject).
The above relation is in 3NF [since there is no transitive dependency]. A relation R is in BCNF if for every non-trivial FD X->Y, X must be a key.
The above relation is not in BCNF, because in the FD (teacher->subject), teacher is not a key. This relation suffers with anomalies −
For example, if we try to delete the student Subbu, we will lose the information that R. Prasad teaches C. These difficulties are caused by the fact the teacher is determinant but not a candidate key.
Teacher-> subject violates BCNF [since teacher is not a candidate key].
If X->Y violates BCNF then divide R into R1(X, Y) and R2(R-Y).
So R is divided into two relations R1(Teacher, subject) and R2(student, Teacher).
R1
R2
All the anomalies which were present in R, now removed in the above two relations.
BCNF decomposition does not always satisfy dependency preserving property. After BCNF decomposition if dependency is not preserved then we have to decide whether we want to remain in BCNF or rollback to 3NF. This process of rollback is called denormalization.
Composite Key in SQL

26 Apr, 2021
To know what a composite key is we need to have the knowledge of what a primary key is, a primary key is a column that has a unique and not null value in an SQL table. 
Now a composite key is also a primary key, but the difference is that it is made by the combination of more than one column to identify the particular row in the table.
Composite Key:
A composite key is made by the combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness of a row is guaranteed, but when it is taken individually it does not guarantee uniqueness, or it can also be understood as a primary key made by the combination of two or more attributes to uniquely identify every row in a table. 
Note: 
 A composite key can also be made by the combination of more than one candidate key.
A composite key cannot be null.
Example:
Creating a database:
CREATE School;
Using database:
USE School;
Creating table with a composite key:
CREATE TABLE student
(rollNumber INT, 
name VARCHAR(30), 
class VARCHAR(30), 
section VARCHAR(1), 
mobile VARCHAR(10),
PRIMARY KEY (rollNumber, mobile));
In this example, we have made the composite key as the combination of two columns i.e. rollNumber and mobile because all the rows of the table student can be uniquely identified by this composite key.
Inserting records in the table:
INSERT INTO student (rollNumber, name, class, section, mobile) 
VALUES (1, "AMAN","FOURTH", "B", "9988774455");
INSERT INTO student (rollNumber, name, class, section, mobile) 
VALUES (2, "JOHN","FIRST", "A", "9988112233");
INSERT INTO student (rollNumber, name, class, section, mobile) 
VALUES (3, "TOM","FOURTH", "B", "9988777755");
INSERT INTO student (rollNumber, name, class, section, mobile) 
VALUES (4, "RICHARD","SECOND", "C", "9955663322");
Querying the records:
SELECT * FROM student;
OUTPUT: 
DBMS-SQL
Picked
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL | Views
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
std::lcm in C++17

24 Jul, 2017
Competitive programming often involves computation of Least Common Multiple (LCM) of two numbers. One way of doing that is using boost::math::lcm(), which we discussed in the post – Inbuilt function for calculating LCM in C++ .But, recently, C++ in its latest version C++17 has also included another in-built function for computation of LCM, std::lcm(). This function is defined inside the header file .
Syntax:
std::lcm (m, n)
Arguments: m, n
Returns: 0, if either of m or n are 0
         else, returns lcm of mod(m) and mod(n)

Remember, since this feature has been defined in latest version of C++, so using this function in compilers not supporting C++17, will throw an error.
// CPP program to illustrate// std::lcm function of C++#include <iostream>#include <numeric>  using namespace std;  int main(){    cout << "LCM(10, 20) = " << std::lcm(10, 20)         << endl;    return 0;}
Output:
20

Important Points:
This function works on positive numbers, and if any argument is negative, it is firstly converted to its modulus, and then calculates the LCM.Also, it works only on integer data type , and if any other data type like char, double, is provided in its argument, then it will throw an error.
This function works on positive numbers, and if any argument is negative, it is firstly converted to its modulus, and then calculates the LCM.
Also, it works only on integer data type , and if any other data type like char, double, is provided in its argument, then it will throw an error.
Reference:
C++ Weekly – Ep 67 – C++17’s std::gcd and std::lcm
C++ Weekly – Ep 67 – C++17’s std::gcd and std::lcm
This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-numerics-library
LCM
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript ReferenceError – Invalid assignment left-hand side

24 Jul, 2020
Basic Example of ReferenceError – Invalid assignment left-hand side, run the code and check the console
Example:
Javascript
<script>    if (Math.PI = 10 || Math.PI = 5) {         document.write("Inside Loop");    }</script>
Output:
ReferenceError: Invalid left-hand side in assignment
This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single “=” sign instead of “==” or “===” is an Invalid assignment.
Message:
ReferenceError: invalid assignment left-hand side

Error Type:
ReferenceError

Cause of the error: There may be a misunderstanding between the assignment operator and a comparison operator.
Example 1: In this example, “=” operator is misused as “==”, So the error occurred.
HTML
<!DOCTYPE html><html>    <head> </head>    <body style="text-align: center;">        <h1 style="color: green;">            GeeksforGeeks        </h1>        <p>            JavaScript ReferenceError -             Invalid assignment left-hand side        </p>          <button onclick="Geeks();">            click here        </button>        <p id="GFG_DOWN"></p>          <script>            var el_down = document.getElementById("GFG_DOWN");            function Geeks() {                try {                    if ((Math.PI = 10 || Math.PI = 5)) {                        document.write("Inside Loop");                    }                    el_down.innerHTML =                       "'Invalid assignment left-hand side'" +                       " error has not occurred";                } catch (e) {                    el_down.innerHTML =                       "'Invalid assignment left-hand side'" +                       "error has occurred";                }            }        </script>    </body></html>
Output:
Example 2: In this example, the + operator is used with the declaration, So the error has not occurred.
HTML
<!DOCTYPE HTML><html>  <head>     </head>   <body style="text-align:center;">     <h1 style="color:green;">          GeeksforGeeks      </h1>     <p>        JavaScript ReferenceError -        Invalid assignment left-hand side    </p>         <button onclick = "Geeks();">        click here    </button>    <p id="GFG_DOWN">     </p>             <script>         var el_down = document.getElementById("GFG_DOWN");        function Geeks() {             try {                var str = 'Hello, '                + 'Geeks'; // Error Here                el_down.innerHTML =                 "'Invalid assignment left-hand side'"+                "error has not occurred";            } catch(e) {                el_down.innerHTML =                 "'Invalid assignment left-hand side'"+                "error has occurred";            }        }     </script> </body>   </html>
Output: 
JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Converting an Image into Grayscale using cvtColor()

04 Nov, 2019
To convert a color image to Grayscale image using OpenCV, we read the image into BufferedImage and convert it into Mat Object.
Syntax:
File input = new File("digital_image_processing.jpg");
BufferedImage image = ImageIO.read(input);

To transform the image from RGB to Grayscale format by using method cvtColor() in the Imgproc class.
Syntax:Imgproc.cvtColor(source mat, destination mat1, Imgproc.COLOR_RGB2GRAY);Parameters: The method cvtColor() takes three parameters which are the source image matrix, the destination image matrix, and the color conversion type.
// Java program to convert a color image to gray scaleimport org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc;  public class GeeksforGeeks {    public static void main(String args[]) throws Exception    {          // To load  OpenCV core library        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);        String input = "C:/opencv/GeeksforGeeks.jpg";          // To Read the image        Mat source = Imgcodecs.imread(input);          // Creating the empty destination matrix        Mat destination = new Mat();          // Converting the image to gray scale and         // saving it in the dst matrix        Imgproc.cvtColor(source, destination, Imgproc.COLOR_RGB2GRAY);          // Writing the image        Imgcodecs.imwrite("C:/opencv/GeeksforGeeks.jpg", destination);        System.out.println("The image is successfully to Grayscale");    }}
Input : 


Output :



nidhi_biet
Image-Processing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Decrement Dictionary value by K

17 Dec, 2019
Sometimes, while working with dictionaries, we can have a use-case in which we require to decrement a particular key’s value by K in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using get()The get function can be used to initialize a non-existing key with 0 and then the decrement is possible. By this way the problem of non-existing key can be avoided.
# Python3 code to demonstrate working of# Decrement Dictionary value by K# Using get()  # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'for' : 4, 'CS' : 5}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Initialize K K = 5  # Using get()# Decrement Dictionary value by Ktest_dict['best'] = test_dict.get('best', 0) - K      # printing result print("Dictionary after the decrement of key : " + str(test_dict))
The original dictionary : {‘for’: 4, ‘CS’: 5, ‘is’: 2, ‘gfg’: 1}Dictionary after the decrement of key : {‘best’: -5, ‘for’: 4, ‘CS’: 5, ‘is’: 2, ‘gfg’: 1}
 
Method #2 : Using defaultdict()This problem can also be solved by using a defaultdict method, which initializes the potential keys and doesn’t throw an exception in case of non-existence of keys.
# Python3 code to demonstrate working of# Decrement Dictionary value by K# Using defaultdict()from collections import defaultdict  # Initialize dictionarytest_dict = defaultdict(int)  # printing original dictionaryprint("The original dictionary : " + str(dict(test_dict)))  # Initialize K K = 5  # Using defaultdict()# Decrement Dictionary value by Ktest_dict['best'] -= K      # printing result print("Dictionary after the decrement of key : " + str(dict(test_dict)))
The original dictionary : {}Dictionary after the decrement of key : {‘best’: -5}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.select()

07 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.select() function return data corresponding to axis labels matching criteria. We pass the name of the function as an argument to this function which is applied on all the index labels. The index labels satisfying the criteria are selected.
Syntax: Series.select(crit, axis=0)
Parameter :crit : called on each index (label). Should return True or Falseaxis : int value
Returns : selection : same type as caller
Example #1: Use Series.select() function to select the names of all those cities from the given Series object for which it’s index labels has even ending.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.select() function to select the names of all those cities, whose index label ends with even integer value.
# Define a function to  Select those cities whose index# label's last character is an even integerdef city_even(city):    # if last character is even    if int(city[-1]) % 2 == 0:        return True    else:        return False  # Call the function and select the valuesselected_cities = sr.select(city_even, axis = 0)  # Print the returned Series objectprint(selected_cities)
Output :
As we can see in the output, the Series.select() function has successfully returned all those cities which satisfies the given criteria.
Example #2: Use Series.select() function to select the sales of the ‘Coca Cola’ and ‘Sprite’ from the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.select() function to select the sales of the listed beverages from the given Series object.
# Function to select the sales of # Coca Cola and Spritedef show_sales(x):    if x == 'Sprite' or x == 'Coca Cola':        return True    else:        return False  # Call the function and select the valuesselected_cities = sr.select(show_sales, axis = 0)  # Print the returned Series objectprint(selected_cities)
Output :
As we can see in the output, the Series.select() function has successfully returned the sales data of the desired beverages from the given Series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Counting the number of groups Java regular expression

You can treat multiple characters as a single unit by capturing them as groups. You just need to place these characters inside a set of parentheses.
You can count the number of groups in the current match using the groupCount() method of the Matcher class. This method calculates the number of capturing groups in the current match and returns it.
 Live Demo
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      String str1 = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> where <b>ever</b> alternative <b>word</b> is <b>bold</b></p>.";
      //Regular expression to match contents of the bold tags
      String regex = "(t(\\S+)t)(\\s)";
      String str = "the words tit tat tweet tostff tact that tilt text. start and end with the letter       t    ";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
         System.out.println(matcher.group(0));
      }
      System.out.println("Total capturing groups: "+matcher.groupCount());
   }
}
tit
tat
tweet
tact
that
tilt
text
tart
Total capturing groups: 3
Sets in C#

Sets in C# is a HashSet. HashSet in C# eliminates duplicate strings or elements in an array. In C#, it is an optimized set collection
To declare HashSet −
var h = new HashSet<string>(arr1);
Above, we have set the already declared array arr1 in the HashSet.
Now set it on the array to remove the duplicate words −
string[] arr2 = h.ToArray();
Let us see an example to remove duplicate strings using C# HashSet.
Here, we have duplicate elements −
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      string[] arr1 = {"Table","Chair","Pen","Clip","Table"};
      Console.WriteLine(string.Join(",", arr1));

      // HashSet
      var h = new HashSet<string>(arr1);

      // eliminates duplicate words
      string[] arr2 = h.ToArray();
      Console.WriteLine(string.Join(",", arr2));
   }
}
Default Arguments in C++

In this tutorial, we will be discussing a program to understand default arguments in C++.
Default arguments are those which are provided to the called function in case the caller statement does provide any value for them.
 Live Demo
#include<iostream>
using namespace std;
//function defined with default arguments
int sum(int x, int y, int z=0, int w=0){
   return (x + y + z + w);
}
int main(){
   cout << sum(10, 15) << endl;
   cout << sum(10, 15, 25) << endl;
   cout << sum(10, 15, 25, 30) << endl;
   return 0;
}
25
50
80
Count Number of Cars in Less Than 10 Lines of Code Using Python | by Sabina Pokhrel | Towards Data Science

When travelling in a car as a kid, did you ever play a game where you counted the number of cars that passed by?
That used to be my favourite game as a kid.
In this post, I will teach you how to build your own car counter program in just 10 lines of code using Python.
You will need to install the following python libraries if it is not already installed:
opencv-pythoncvlibmatplotlibtensorflowkeras
Here is the code to import the required python libraries, read an image from storage, perform object detection on the image, display the image with a bounding box and label about the detected objects, count the number of cars in the image and print it.
import cv2import matplotlib.pyplot as pltimport cvlib as cvfrom cvlib.object_detection import draw_bboxim = cv2.imread('cars_4.jpeg')bbox, label, conf = cv.detect_common_objects(im)output_image = draw_bbox(im, bbox, label, conf)plt.imshow(output_image)plt.show()print('Number of cars in the image is '+ str(label.count('car')))
Output for this image:
Number of cars in the image is 29
Output for this image:
Number of cars in the image is 22
Output for this image:
Number of cars in the image is 25
Your car counter program is now ready. You can use it for fun experiments such as counting the number of cars that pass your driveway each day.
Python version 3.6.9 was used for running this code.
Versions of the most important packages that were installed when this code was run as follows:
cvlib: 0.2.2opencv-python: 4.1.1.26tensorflow: 1.14.0matplotlib: 3.1.1Keras: 2.2.5
Here is a GitHub link for the Jupyter Notebook for this program:
github.com
Found this post helpful? Leave your thoughts as comments below.
Looking to implement face detection. Check out my post on how to implement face detection in less than 3 minutes using python.
Looking to implement object detection. Check out my post on object detection using just 10 lines of code in python.
Click here to read my other posts on AI/Machine Learning.
To know more about cvlib library, you can visit the link below.
Modular multiplicative inverse in java

The java.math.BigInteger.modInverse(BigInteger m) returns a BigInteger whose value is (this-1 mod m). Using this method you can calculate Modular multiplicative inverse for a given number.
Live Demo
import java.math.*;
public class BigIntegerDemo {
   public static void main(String[] args) {
      // create 3 BigInteger objects
      BigInteger bi1, bi2, bi3;
     
      // create a BigInteger exponent
      BigInteger exponent = new BigInteger("2");
      bi1 = new BigInteger("7");
      bi2 = new BigInteger("20");
     
      // perform modPow operation on bi1 using bi2 and exp
      bi3 = bi1.modPow(exponent, bi2);
      String str = bi1 + "^" +exponent+ " mod " + bi2 + " is " +bi3;
     
      // print bi3 value
      System.out.println( str );
   }
}
7^2 mod 20 is 9
How to get userAgent information in Selenium Web driver?

We can get the user Agent information with Selenium webdriver. This is done with the help of the JavaScript Executor. Selenium executes JavaScript commands with the help of the execute_script method.
To obtain the user Agent information, we have to pass the return navigator.userAgent parameter to the execute_script method. Selenium does have a direct method the to get or modify user Agent.
a= driver.execute_script("return navigator.userAgent")
print(a)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options class
op = webdriver.ChromeOptions()
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",
options=op)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.seleniumhq.org/download/");
#get user Agent with execute_script
a= driver.execute_script("return navigator.userAgent")
print("User agent:")
print(a)
#close browser session
driver.quit()
Plotting Graphs using Two Dimensional List in R Programming - GeeksforGeeks

01 Jun, 2020
List is a type of an object in R programming. Lists can contain heterogeneous elements like strings, numeric, matrices, or even lists. A list is a generic vector containing other objects. Two-dimensional list can be created in R programming by creating more lists in a list or simply, we can say nested lists. The list() function in R programming is used to create a list. In this article, we’ll learn to create plot graph using Two Dimensional List in R programming.
A Two Dimensional list can be created with the use of list() function.
Syntax: list(x)
Parameter:x: represents objects to be inserted in list
Example:
# Defining objectsx <- c(1, 2, 3, 4)  y <- LETTERS[1:4]  # Adding lists into a listls <- list(  list(x),   list(y))  # Print listprint(ls)
Output:
[[1]]
[[1]][[1]]
[1] 1 2 3 4


[[2]]
[[2]][[1]]
[1] "A" "B" "C" "D"


To create plot graphs, lists have to be passed as vectors to the plot() function as coordinate values. The unlist() function converts the list into an atomic type of vector.
Example:
# Creating nested lists with random valuesls <- list(  list(rnorm(20, mean = 10, sd = 2)),  list(rnorm(20, mean = 100, sd = 10)))  # Output to be present as PNG filepng(file = "2DListGraph.png")  # Plotting listplot(unlist(ls[[1]]), unlist(ls[[2]]))  # Saving the filedev.off()
Output:
Picked
R-List
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Convert a Vector to an array in Java

A Vector can be converted into an Array using the java.util.Vector.toArray() method. This method requires no parameters and it returns an Array that contains all the elements of the Vector in the correct order.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector();
      vec.add(7);
      vec.add(3);
      vec.add(5);
      vec.add(2);
      vec.add(8);
      Object[] arr = vec.toArray();
      System.out.println("The Array elements are: ");
      for (int i = 0; i < arr.length; i++) {
         System.out.println(arr[i]);
      }
   }
}
The output of the above program is as follows −
The Array elements are:
7
3
5
2
8
Now let us understand the above program.
The Vector is created. Then Vector.add() is used to add the elements to the Vector. The method Vector.toArray() is used to convert the Vector into an Array. Then the Array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −
Vector vec = new Vector();
vec.add(7);
vec.add(3);
vec.add(5);
vec.add(2);
vec.add(8);
Object[] arr = vec.toArray();
System.out.println("The Array elements are: ");
for (int i = 0; i < arr.length; i++) {
   System.out.println(arr[i]);
}
How to get Geolocation in Python?

29 Dec, 2021
In this article, we will discuss on how to get Geolocation when you enter any location name and its gives all the useful information such as postal code, city, state, country etc. with the latitudes and the longitudes (the specific coordinates) and vice-versa in which we provide the coordinates to get the location name.
This can be done using the GeoPy library in python. This library isn’t built into python and hence needs to be installed explicitly.
In your terminal, simply run the given command:
pip install geopy
With provided location, it is possible using geopy to extract the coordinates meaning its latitude and longitude. Therefore, it can be used to express the location in terms of coordinates.
Approach
Import module
Import Nominatim from geopy- Nominatim is a free service or tool or can be called an API with no keys that provide you with the data after providing it with name and address and vice versa.
On calling the Nomination tool which accepts an argument of user_agent you can give any name as it considers it to be the name of the app to which it is providing its services.
The geocode() function accepts the location name and returns a geodataframe that has all the details and since it’s a dataframe we can get the address, latitude and longitude by simply calling it with the given syntax
Syntax:
variablename.address 
variablename.latitude 
variablename.longitude.
Example:
Python3
# importing geopy libraryfrom geopy.geocoders import Nominatim # calling the Nominatim toolloc = Nominatim(user_agent="GetLoc") # entering the location namegetLoc = loc.geocode("Gosainganj Lucknow") # printing addressprint(getLoc.address) # printing latitude and longitudeprint("Latitude = ", getLoc.latitude, "\n")print("Longitude = ", getLoc.longitude)
Output:
In this method all the things are same as the above, the only difference is instead of using the geocode function we will now use the reverse() method which accepts the coordinates (latitude and longitude) as the argument, this method gives the address after providing it with the coordinates.
Syntax:
reverse(latitude,longitude)
Approach
Import module
Call nominatim tool
Pass latitude and longitude to reverse()
Print location name
Example:
Python3
# importing modulesfrom geopy.geocoders import Nominatim # calling the nominatim toolgeoLoc = Nominatim(user_agent="GetLoc") # passing the coordinateslocname = geoLoc.reverse("26.7674446, 81.109758") # printing the address/location nameprint(locname.address)
Output:
agmalayeb19
Picked
python-modules
python-utility
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Menu-Driven program using Switch-case in C

16 Jul, 2019
Prerequisite : Switch Case in C
Problem Statement:Write a menu-driven program using Switch case to calculate the following:1. Area of circle2. Area of square3. Area of sphere
Also use functions input() and output() to input and display respective values.
// C program to illustrate// Menu-Driven program// using Switch-case  #include <stdio.h>int input();void output(float);int main(){    float result;    int choice, num;    printf("Press 1 to calculate area of circle\n");    printf("Press 2 to calculate area of square\n");    printf("Press 3 to calculate area of sphere\n");    printf("Enter your choice:\n");    choice = input();          switch (choice) {    case 1: {        printf("Enter radius:\n");        num = input();        result = 3.14 * num * num;        printf("Area of sphere=");        output(result);        break;    }    case 2: {        printf("Enter side of square:\n");        num = input();        result = num * num;        printf("Area of square=");        output(result);        break;    }    case 3: {        printf("Enter radius:\n");        num = input();        result = 4 * (3.14 * num * num);        printf("Area of sphere=");        output(result);        break;    }    default:        printf("wrong Input\n");    }    return 0;}int input(){    int number;    scanf("%d", &number);    return (number);}  void output(float number){    printf("%f", number);}
Output:
Press 1 to calculate area of circle
Press 2 to calculate area of square
Press 3 to calculate area of sphere
Enter your choice:
1
Enter radius:
5
Area of circle=78.5

Related Articles:
Interesting facts about switch statement in C
Output of C programs | Set 30 (Switch Case)
Using range in switch case in C/C++
cpp-switch
Menu driven programs
C Programs
C++ Programs
School Programming
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining
Shallow Copy and Deep Copy in C++
map find() function in C++ STL

06 Jul, 2022
The map::find() is a built-in function in C++ STL which returns an iterator or a constant iterator that refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.end()
. Syntax: 
iterator=map_name.find(key)
        or 
constant iterator=map_name.find(key)
Parameters: The function accepts one mandatory parameter key, which specifies the key to be searched in the map container. 
Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.end(). 
Time Complexity for Searching element : The time complexity for searching elements in std::map is O(log n). Even in the worst case, it will be O(log n) because elements are stored internally as Balanced Binary Search tree (BST) whereas, in std::unordered_map best case time complexity for searching is O(1).
Below is the illustration of the above function: 
CPP
// C++ program for illustration// of map::find() function#include <bits/stdc++.h>using namespace std;  int main(){      // Initialize container    map<int, int> mp;      // Insert elements in random order    mp.insert({ 2, 30 });    mp.insert({ 1, 40 });    mp.insert({ 3, 20 });    mp.insert({ 4, 50 });      cout << "Elements from position of 3 in the map are : \n";    cout << "KEY\tELEMENT\n";      // find() function finds the position    // at which 3 is present    for (auto itr = mp.find(3); itr != mp.end(); itr++) {                cout << itr->first << '\t' << itr->second << '\n';    }      return 0;}
The elements from position 3 in map are : 
KEY    ELEMENT
3    20
4    50
Time Complexity: O(log n)Auxiliary Space: O(n)
cheesy
privatehandle
abhijitgeeksforgeeks
jayanth_mkv
CPP-Functions
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program To Find Longest Common Prefix Using Sorting

10 Jan, 2022
Problem Statement: Given a set of strings, find the longest common prefix.Examples:  
Input: {"geeksforgeeks", "geeks", "geek", "geezer"}
Output: "gee"

Input: {"apple", "ape", "april"}
Output: "ap"
 
The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not share any starting characters. We have discussed five different approaches in below posts.  
Word by Word MatchingCharacter by Character MatchingDivide and ConquerBinary Search.Using Trie)
Word by Word Matching
Character by Character Matching
Divide and Conquer
Binary Search.
Using Trie)
 
In this post a new method based on sorting is discussed. The idea is to sort the array of strings and find the common prefix of the first and last string of the sorted array. 
Python 3
# Python 3 program to find longest # common prefix of given array of words.def longestCommonPrefix( a):          size = len(a)      # if size is 0, return empty string     if (size == 0):        return ""      if (size == 1):        return a[0]      # sort the array of strings     a.sort()          # find the minimum length from     # first and last string     end = min(len(a[0]), len(a[size - 1]))      # find the common prefix between     # the first and last string     i = 0    while (i < end and            a[0][i] == a[size - 1][i]):        i += 1      pre = a[0][0: i]    return pre  # Driver Codeif __name__ == "__main__":      input = ["geeksforgeeks", "geeks",                      "geek", "geezer"]    print("The longest Common Prefix is :" ,                 longestCommonPrefix(input))  # This code is contributed by ita_c
Output:  
The longest common prefix is : gee
Time Complexity: O(MAX * n * log n ) where n is the number of strings in the array and MAX is maximum number of characters in any string. Please note that comparison of two strings would take at most O(MAX) time and for sorting n strings, we would need O(MAX * n * log n ) time.Please refer complete article on Longest Common Prefix using Sorting for more details!
Longest Common Prefix
Python Programs
Sorting
Strings
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java String contentEquals() Method

❮ String Methods

Find out if a string contains a sequence of characters:
String myStr = "Hello";
System.out.println(myStr.contentEquals("Hello"));  // true
System.out.println(myStr.contentEquals("e"));      // false
System.out.println(myStr.contentEquals("Hi"));     // false

Try it Yourself »

The contentEquals() method searches a string to find out if it contains the exact same sequence of characters in the specified string or StringBuffer.
Returns true if the characters exist and false if not.
There are 2 contentEquals() methods:
public boolean contentEquals(StringBuffer chars)
public boolean contentEquals(CharSequence chars)

The StringBuffer class is like a String, only it can be modified, found in the java.lang package.
The CharSequence interface is a readable sequence of char values, found in the java.lang package.
true - sequence of characters exists
false - sequence of characters do not exist
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.