code-rag-bench/online-tutorials huggingface dataset:
AWK - Environment

This chapter describes how to set up the AWK environment on your GNU/Linux system.
Generally, AWK is available by default on most GNU/Linux distributions. You can use which command to check whether it is present on your system or not. In case you don’t have AWK, then install it on Debian based GNU/Linux using Advance Package Tool (APT) package manager as follows −
[jeryy]$ sudo apt-get update
[jeryy]$ sudo apt-get install gawk
Similarly, to install AWK on RPM based GNU/Linux, use Yellowdog Updator Modifier yum package manager as follows −
[root]# yum install gawk
After installation, ensure that AWK is accessible via command line.
[jerry]$ which awk
On executing the above code, you get the following result −
/usr/bin/awk

As GNU AWK is a part of the GNU project, its source code is available for free download. We have already seen how to install AWK using package manager. Let us now understand how to install AWK from its source code.
The following installation is applicable to any GNU/Linux software, and for most other freely-available programs as well. Here are the installation steps −
Step 1 − Download the source code from an authentic place. The command-line utility wget serves this purpose.
[jerry]$ wget http://ftp.gnu.org/gnu/gawk/gawk-4.1.1.tar.xz
Step 2 − Decompress and extract the downloaded source code.
[jerry]$ tar xvf gawk-4.1.1.tar.xz
Step 3 − Change into the directory and run configure.
[jerry]$ ./configure
Step 4 − Upon successful completion, the configure generates Makefile. To compile the source code, issue a make command.
[jerry]$ make
Step 5 − You can run the test suite to ensure the build is clean. This is an optional step.
[jerry]$ make check
Step 6 − Finally, install AWK. Make sure you have super-user privileges.
[jerry]$ sudo make install
That is it! You have successfully compiled and installed AWK. Verify it by executing the awk command as follows −
[jerry]$ which awk
On executing this code, you get the following result −
/usr/bin/awk

 Print
 Add Notes
 Bookmark this page
How to select only numeric strings in MongoDB?

Let us create a collection with documents −
> db.selectOnlyNumericDemo.insertOne({"UserId":"User101"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdb711de8cc557214c0e16")
}
> db.selectOnlyNumericDemo.insertOne({"UserId":"102"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdb716de8cc557214c0e17")
}
> db.selectOnlyNumericDemo.insertOne({"UserId":"User103"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdb71dde8cc557214c0e18")
}
> db.selectOnlyNumericDemo.insertOne({"UserId":"104"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdb725de8cc557214c0e19")
}
Display all documents from a collection with the help of find() method −
> db.selectOnlyNumericDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cbdb711de8cc557214c0e16"), "UserId" : "User101" }
{ "_id" : ObjectId("5cbdb716de8cc557214c0e17"), "UserId" : "102" }
{ "_id" : ObjectId("5cbdb71dde8cc557214c0e18"), "UserId" : "User103" }
{ "_id" : ObjectId("5cbdb725de8cc557214c0e19"), "UserId" : "104" }
Following is the query to select only numeric strings or check whether string is numeric in MongoDB −
> db.selectOnlyNumericDemo.find({'UserId': /^\d+$/});
This will produce the following output −
{ "_id" : ObjectId("5cbdb716de8cc557214c0e17"), "UserId" : "102" }
{ "_id" : ObjectId("5cbdb725de8cc557214c0e19"), "UserId" : "104" }
Regular Expression "$" (dollar) Metacharacter in Java

The subexpression/metacharacter “$” matches the end of a line.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EndWith {
   public static void main( String args[] ) {
      String regex = "Tutorialspoint$";
      String input = "Hi how are you welcome to Tutorialspoint";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
         System.out.println("Number of matches: "+count);
      }
   }
}
Number of matches: 1
The following Java program accepts 5 strings from the user and prints the strings ending with a digit.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EndingwithDigit {
   public static void main( String args[] ) {
      String regex = "^.*[0-9]$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      System.out.println("Strings ending with digits: ");
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.matches()) {
            System.out.println(m.group());
         }
      }
   }
}
Enter 5 input strings:
sample string 1
sample string 2
test data
hello
3264533 3546373 7653
Strings ending with digits:
sample string 1
sample string 2
3264533 3546373 7653
Python | Merging two Dictionaries - GeeksforGeeks

16 Nov, 2020
There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Python. In this article, we will discuss a few ways of merging dictionaries. 
By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None.  
Example: 
Python3
# Python code to merge dict using update() methoddef Merge(dict1, dict2):    return(dict2.update(dict1))     # Driver codedict1 = {'a': 10, 'b': 8}dict2 = {'d': 6, 'c': 4} # This return Noneprint(Merge(dict1, dict2)) # changes made in dict2print(dict2)
Output:
None
{'c': 4, 'a': 10, 'b': 8, 'd': 6}


This is generally considered a trick in Python where a single expression is used to merge two dictionaries and stored in a third dictionary. The single expression is **. This does not affect the other two dictionaries. ** implies that an argument is a dictionary. Using ** [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. For more information refer **kwargs in Python. Using this we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.  
Example: 
Python3
# Python code to merge dict using a single# expressiondef Merge(dict1, dict2):    res = {**dict1, **dict2}    return res     # Driver codedict1 = {'a': 10, 'b': 8}dict2 = {'d': 6, 'c': 4}dict3 = Merge(dict1, dict2)print(dict3)
Output:
{'b': 8, 'a': 10, 'c': 4, 'd': 6}


In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.
Example:
Python3
# code# Python code to merge dict using a single # expressiondef Merge(dict1, dict2):    res = dict1 | dict2    return res       # Driver codedict1 = {'x': 10, 'y': 8}dict2 = {'a': 6, 'b': 4}dict3 = Merge(dict1, dict2)print(dict3) # This code is contributed by virentanti16
Output:
{'x': 10, 'a': 6,  'b': 4, 'y': 8}


_sharma_
virentanti16
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
Redis - Configuration

In Redis, there is a configuration file (redis.conf) available at the root directory of Redis. Although you can get and set all Redis configurations by Redis CONFIG command.
Following is the basic syntax of Redis CONFIG command.
redis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME

redis 127.0.0.1:6379> CONFIG GET loglevel  
1) "loglevel" 
2) "notice"

To get all configuration settings, use * in place of CONFIG_SETTING_NAME
redis 127.0.0.1:6379> CONFIG GET *  
  1) "dbfilename" 
  2) "dump.rdb" 
  3) "requirepass" 
  4) "" 
  5) "masterauth" 
  6) "" 
  7) "unixsocket" 
  8) "" 
  9) "logfile" 
 10) "" 
 11) "pidfile" 
 12) "/var/run/redis.pid" 
 13) "maxmemory" 
 14) "0"
 15) "maxmemory-samples" 
 16) "3" 
 17) "timeout" 
 18) "0" 
 19) "tcp-keepalive" 
 20) "0" 
 21) "auto-aof-rewrite-percentage" 
 22) "100" 
 23) "auto-aof-rewrite-min-size" 
 24) "67108864" 
 25) "hash-max-ziplist-entries" 
 26) "512" 
 27) "hash-max-ziplist-value" 
 28) "64" 
 29) "list-max-ziplist-entries" 
 30) "512" 
 31) "list-max-ziplist-value" 
 32) "64" 
 33) "set-max-intset-entries" 
 34) "512" 
 35) "zset-max-ziplist-entries" 
 36) "128" 
 37) "zset-max-ziplist-value" 
 38) "64" 
 39) "hll-sparse-max-bytes" 
 40) "3000" 
 41) "lua-time-limit" 
 42) "5000" 
 43) "slowlog-log-slower-than" 
 44) "10000" 
 45) "latency-monitor-threshold" 
 46) "0" 
 47) "slowlog-max-len" 
 48) "128" 
 49) "port" 
 50) "6379" 
 51) "tcp-backlog" 
 52) "511" 
 53) "databases" 
 54) "16" 
 55) "repl-ping-slave-period" 
 56) "10" 
 57) "repl-timeout" 
 58) "60" 
 59) "repl-backlog-size" 
 60) "1048576" 
 61) "repl-backlog-ttl" 
 62) "3600" 
 63) "maxclients" 
 64) "4064" 
 65) "watchdog-period" 
 66) "0" 
 67) "slave-priority" 
 68) "100" 
 69) "min-slaves-to-write" 
 70) "0" 
 71) "min-slaves-max-lag" 
 72) "10" 
 73) "hz" 
 74) "10" 
 75) "no-appendfsync-on-rewrite" 
 76) "no" 
 77) "slave-serve-stale-data" 
 78) "yes" 
 79) "slave-read-only" 
 80) "yes" 
 81) "stop-writes-on-bgsave-error" 
 82) "yes" 
 83) "daemonize" 
 84) "no" 
 85) "rdbcompression" 
 86) "yes"
 87) "rdbchecksum" 
 88) "yes" 
 89) "activerehashing" 
 90) "yes" 
 91) "repl-disable-tcp-nodelay" 
 92) "no" 
 93) "aof-rewrite-incremental-fsync" 
 94) "yes" 
 95) "appendonly" 
 96) "no" 
 97) "dir" 
 98) "/home/deepak/Downloads/redis-2.8.13/src" 
 99) "maxmemory-policy" 
100) "volatile-lru" 
101) "appendfsync" 
102) "everysec" 
103) "save" 
104) "3600 1 300 100 60 10000" 
105) "loglevel" 
106) "notice" 
107) "client-output-buffer-limit" 
108) "normal 0 0 0 slave 268435456 67108864 60 pubsub 33554432 8388608 60" 
109) "unixsocketperm" 
110) "0" 
111) "slaveof" 
112) "" 
113) "notify-keyspace-events" 
114) "" 
115) "bind" 
116) "" 

To update configuration, you can edit redis.conf file directly or you can update configurations via CONFIG set command.
Following is the basic syntax of CONFIG SET command.
redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE

redis 127.0.0.1:6379> CONFIG SET loglevel "notice" 
OK 
redis 127.0.0.1:6379> CONFIG GET loglevel  
1) "loglevel" 
2) "notice" 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Calculation in parent and child process using fork()

13 Sep, 2021
Write a program to find sum of even numbers in parent process and sum of odd numbers in child process.
Examples: 
Input : 1, 2, 3, 4, 5 

Output :
Parent process 
Sum of even no. is 6
Child process 
Sum of odd no. is 9 
Explanation: Here, we had used fork() function to create two processes one child and one parent process. 
For child process fork() returns 0 so we can calculate sum of all odd numbers in child process. 
fork() returns value greater than 0 for parent process so we can calculate sum 
for all even numbers there by just simply checking the value returned by fork(). 
C++
// C++ program to demonstrate calculation in parent and// child processes using fork()#include <iostream>#include <unistd.h>using namespace std; // Driver codeint main(){    int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };    int sumOdd = 0, sumEven = 0, n, i;    n = fork();     // Checking if n is not 0    if (n > 0) {        for (i = 0; i < 10; i++) {            if (a[i] % 2 == 0)                sumEven = sumEven + a[i];        }        cout << "Parent process \n";        cout << "Sum of even no. is " << sumEven << endl;    }     // If n is 0 i.e. we are in child process    else {        for (i = 0; i < 10; i++) {            if (a[i] % 2 != 0)                sumOdd = sumOdd + a[i];        }        cout << "Child process \n";        cout << "\nSum of odd no. is " << sumOdd << endl;    }    return 0;}
Output: 
Parent process 
Sum of even no. is 30
Child process 
Sum of odd no. is 25
This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
amanmalakar007
system-programming
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
$this keyword in PHP

09 Jul, 2020
$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.
Example 1: A simple program to show the use of $this in PHP.
<?phpclass simple{      public $k = 9;      public function display(){        return $this->k;    }}  $obj = new simple();echo $obj->display();  ?>
Output:
9
$this – a pseudo-variable: Unlike other reserved keywords used in the context of class like the static, parent, etc does not need to be declared with the dollar sign (‘$’). This is because in PHP $this is treated as a pseudo-variable.In PHP, this is declared like a variable declaration (with the ‘$’ sign) even though it is a reserved keyword. More specifically, $this is a special read-only variable that is not declared anywhere in the code and which represents a value that changes depending on the context of program execution.
Example 2: A program that updates the value of a variable of a specific object using $this keyword.
<?phpclass simple {      public $k = 9;      public function change($val){        $this->k = $val;    }      public function display(){        return $this->k;    }}  $obj = new simple();print("value of before update: ");echo $obj->display();  $obj->change(8);print("value of after update: ");echo $obj->display();?>
Output:
value of before update: 9
value of after update: 8

As of PHP 7.0.0, calling a non-static method statically from an incompatible context results in $this being “undefined” to the method. Calling a non-static method statically from an incompatible context has been deprecated as of PHP 5.6.0. As of PHP 7.0.0 calling a non-static method statically has been deprecated (even if called from a compatible context). Before PHP 5.6.0, such calls already triggered a strict notice.
Example 3: In this example, $this keyword becomes “not defined” when a non-static method is called in the context of a static one.
<?php  class A {      function foo() {          if (isset($this)) {            echo '$this is defined (';            echo get_class($this);            echo ")\n";        } else {            echo "\$this is not defined.\n";        }    }}  class B {      function bar() {        A::foo();    }}  $a = new A();$a->foo();  A::foo();  $b = new B();$b->bar();  B::bar();?>
Output:
$this is defined (A) 
$this is not defined. 
$this is not defined. 
$this is not defined.

PHP-basics
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Concatenate consecutive elements in Tuple

29 Dec, 2019
Sometimes, while working with data, we can have a problem in which we need to find cumulative result. This can be of any type, product or summation. Here we are gonna discuss about adjacent element concatenation. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using zip() + generator expression + tuple()The combination of above functionalities can be used to perform this task. In this, we use generator expression to provide concatenation logic and simultaneous element pairing is done by zip(). The result is converted to tuple form using tuple().
# Python3 code to demonstrate working of# Consecutive element concatenation in Tuple# using zip() + generator expression + tuple  # initialize tupletest_tup = ("GFG ", "IS ", "BEST ", "FOR ", "ALL ", "GEEKS")  # printing original tupleprint("The original tuple : " + str(test_tup))  # Consecutive element concatenation in Tuple# using zip() + generator expression + tupleres = tuple(i + j for i, j in zip(test_tup, test_tup[1:]))  # printing resultprint("Resultant tuple after consecutive concatenation : " + str(res))
The original tuple : ('GFG ', 'IS ', 'BEST ', 'FOR ', 'ALL ', 'GEEKS')
Resultant tuple after consecutive concatenation : ('GFG IS ', 'IS BEST ', 'BEST FOR ', 'FOR ALL ', 'ALL GEEKS')

 
Method #2 : Using tuple() + map() + lambdaThe combination of above functions can also help to perform this task. In this, we perform concatenation and binding logic using lambda function. The map() is used to iterate to each element and at end result is converted by tuple().
# Python3 code to demonstrate working of# Consecutive element concatenation in Tuple# using tuple() + map() + lambda  # initialize tupletest_tup = ("GFG ", "IS ", "BEST ", "FOR ", "ALL ", "GEEKS")  # printing original tupleprint("The original tuple : " + str(test_tup))  # Consecutive element concatenation in Tuple# using tuple() + map() + lambdares = tuple(map(lambda i, j : i + j, test_tup[: -1], test_tup[1: ]))  # printing resultprint("Resultant tuple after consecutive concatenation : " + str(res))
The original tuple : ('GFG ', 'IS ', 'BEST ', 'FOR ', 'ALL ', 'GEEKS')
Resultant tuple after consecutive concatenation : ('GFG IS ', 'IS BEST ', 'BEST FOR ', 'FOR ALL ', 'ALL GEEKS')

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Logical OR assignment (||=) Operator

25 Feb, 2021
This operator is represented by x ||= y  and it is called logical OR assignment operator. If the value of x is falsy then the value of y will be assigned to x.
When we divide it into two parts it becomes x || ( x = y ).
It checks if x is true or false, if the value of x is falsy then it runs the ( x = y ) block and the value of y gets stored into x and if the value of x is truthy then the value of the next block ( x = y ) does not execute.
Syntax :
x ||= y
is equivalent to 
x || (x = y)
Example 1:
Javascript
<script>  let name = {    firstName: "Ram",    lastName: "",  };    console.log(name.firstName);    // Changing the value using logical  // OR assignment operator  name.firstName ||= "Shyam";    // But value does not change because  // name.firstName is truthy  console.log(name.firstName);    console.log(name.lastName);    // Changing the value using logical  // OR assignment operator  name.lastName ||= "Kumar";    // The value changes because name.lastName is falsy  console.log(name.lastName);</script>
Output :
"Ram"
"Ram"
""
"Kumar"
Example 2 :
HTML
<!DOCTYPE html><html><body>  <h1>Hello Geeksforgeeks</h1>  <p id="print_arr"></p>    <script>            let arr = [1, 2, "apple", null, undefined, []]      // Replace each falsy values with "gfg"      arr.forEach((item, index)=>{        arr[index] ||= "gfg"    })      document.getElementById("print_arr").innerText = arr.toString();        </script>    </body></html>
Output :
Supported browsers:
Chrome 85
Edge 85
Firefox 79
Safari 14
javascript-operators
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
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
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 ?
Format Number as Percentage in R

23 May, 2021
In this article, we are going to see how to format numbers as percentages in R programming language.
Method 1: Using formattable package
The “formattable” package provides methods to create formattable vectors and data frame objects. This package in R can be installed and loaded into the working space using the command :
install.packages("formattable")
The percent() method in this package is used to represent the numerical vectors to percentage format. 
Syntax: percent(vec, digits, format = “f”, ...)
Arguments : 
vec – The vector to convert to percentage format
digits – The digits to have after decimal point. By default, the number of digits is equivalent to 2.
format – format type string passed to the method format.
Code:
R
# loading the required librarieslibrary("formattable")  # creating a vectorvec <- c(0.76485, 1.34, -0.6, 1)  print ("Percentage conversion : 2 digits")percent (vec)  print ("Percentage conversion : 4 digits")percent (vec, 4)
Output:
[1] "Percentage conversion : 2 digits"
[1] "76.48%"  "134.00%" "-60.00%" "100.00%"
[1] "Percentage conversion : 4 digits"
[1] "76.4850%"  "134.0000%" "-60.0000%" "100.0000%"
Method 2: Using scales package
The “scales” package in R can be installed and loaded into the working space using the command : 
install.packages("scales")
The percent() method in this package is used to represent the numerical vectors to percentage format.
Syntax: percent(vec)
Arguments : vec – The vector to convert to percentage format
Code:
R
# loading the required librarieslibrary("scales")  # creating a vectorvec <- c(0.76485, 1.34, -0.6, 1)  print ("Percentage conversion")percent (vec)
Output:
[1] "Percentage conversion" 
[1] "76%"  "134%" "-60%" "100%"
Method 3: Using user-defined function
A user-defined method can be used to convert a numerical to a percentage format. The format specifier used in this function is “f” and the number of digits can also be taken as an input to specify the number of integers after the decimal point. The integer number is multiplied by 100 and then the formatC method is applied until the number of digits. In the end, using the paste0() method, the “%” sign is appended at the end out output.
R
# creating a function to compute percentagepercent <- function(num, digits = 2, ...) {        percentage <-formatC(num * 100, format = "f", digits = digits, ...)      # appending "%" symbol at the end of  # calculate percentage value  paste0(percentage, "%")}  # defining a vectorvec <- c(0.76485, 1.34, -0.6, 1, 0.0284)print ("Percentage conversion to three decimal places")  # rounding off the numbers to 3 places# of decimalpercent(vec, 3)  print ("Percentage conversion to two decimal places")  # rounding off the numbers to 2 places # of decimalpercent(vec)
Output
[1] "Percentage conversion to three decimal places" 
[1] "76.485%"  "134.000%" "-60.000%" "100.000%" "2.840%"   
[1] "Percentage conversion to two decimal places"
[1] "76.48%"  "134.00%" "-60.00%" "100.00%" "2.84%"  
Picked
R-Packages
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
BinaryOperator Interface in Java

30 Sep, 2021
The BinaryOperator Interface<T> is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a binary operator which takes two operands and operates on them to produce a result. However, what distinguishes it from a normal BiFunciton is that both of its arguments and its return type are same.
This functional interface which takes in one generic namely:- 
T: denotes the type of the input arguments and the return value of the operation
The BinaryOperator<T> extends the BiFunction<T, T, T> type. So it inherits the following methods from the BiFunction Interface:  
apply(T t, T u)
andThen(Function<? super R, ? extends V> after)
The lambda expression assigned to an object of BiaryOperator type is used to define its apply() which eventually applies the given operation on its arguments.  
The BinaryOperator interface consists of the following functions: 
This methods return a BinaryOperator which returns the greater of the two elements based on a given comparator
Syntax:  
static <T> BinaryOperator<T> 
    maxBy(Comparator<? super T> comparator)
Parameters: It takes in only one parameter namely, comparator which is an object of the Comparator class.
Returns: This method returns a BinaryOperator which returns the maximum of the two objects passed while calling it based on the given comparator.
Below is the code to illustrate maxBy() method:
Program:  
Java
import java.util.function.BinaryOperator; public class GFG {    public static void main(String args[])    {        BinaryOperator<Integer>            op = BinaryOperator                     .maxBy(                         (a, b) -> (a > b) ? 1 : ((a == b) ? 0 : -1));         System.out.println(op.apply(98, 11));    }}
98
 
This method returns a BinaryOperator which returns the lesser of the two elements based on a given comparator
Syntax: 
static <T> BinaryOperator<T> 
    minBy(Comparator<? super T> comparator)
Parameters: It takes in only one parameter namely, comparator which is an object of the Comparator class.
Returns: This method returns a BinaryOperator which return the minimum of the two objects passed while calling it based on the given comparator.
Below is the code to illustrate minBy() method:
Program: 
Java
import java.util.function.BinaryOperator; public class GFG {    public static void main(String args[])    {        BinaryOperator<Integer>            op = BinaryOperator                     .minBy(                         (a, b) -> (a > b) ? 1 : ((a == b) ? 0 : -1));         System.out.println(op.apply(98, 11));    }}
11
 
saurabh1990aror
Java - util package
Java 8
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2020 | Question 33

11 Aug, 2021
Consider a double hashing scheme in which the primary hash function is h1(k) = k mod 23, and the secondary hash function is h2(k) = 1+(k mod 19). Assume that the table size is 23. Then the address returned by probe 1 in the probe sequence (assume that the probe sequence begins at probe 0) for key value k = 90 is ________ .
Note – This question was Numerical Type.(A) 13(B) 15(C) 21(D) 23Answer: (A)Explanation: Given,  
Table size = 23,
key value k = 90,
And, probe i = 1 (probe 1 in the probe sequence) 
According to double hashing, we use the formula as,  
(h1(k) + i*h2(k)) mod (table size) 
where ‘i’ denotes probe value. 
Now,  
h1(k) = k mod 23 = 90 mod 23 = 21

And,
h2(k) = 1+(k mod 19) = 1+(90 mod 19) = 15 
Using double hashing,  
= (h1(k) + i*h2(k)) mod (table size)
= (21 + 15) mod 23
= 36 mod 23
= 13 
Option (A) is correct.
GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.6K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0059:59 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
sanjeevbengeri3
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.matshow() in Python

03 Sep, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
matplotlib.pyplot.matshow() function is used to represent an array as a matrix in a new figure window. the upper left-hand corner is set as the origin and the rows (first dimension of the array) are displayed in a horizontal form. The aspect ratio of the figure window is set according to the array to avoid short and narrow figures. The x-axis Tick labels are placed at the top. 
Syntax: matplotlib.pyplot.matshow(A, fignum=None, **kwargs)Parameters: 
A:: It is an array like object that represents the matrix. It is a required parameter.fignum: It accepts three values namely ‘None’, ‘False’ or an integer value. If the value is set to None it would create a new window of the figure with automated numbering. If the value is a non-zero integer then it is drawn into the figure respective to the given number or it creates it if it doesn’t exist. If the ‘0’ is set as the value of this parameter then it uses the current axes or it creates one if it doesn’t exist. 
A:: It is an array like object that represents the matrix. It is a required parameter.
fignum: It accepts three values namely ‘None’, ‘False’ or an integer value. If the value is set to None it would create a new window of the figure with automated numbering. If the value is a non-zero integer then it is drawn into the figure respective to the given number or it creates it if it doesn’t exist. If the ‘0’ is set as the value of this parameter then it uses the current axes or it creates one if it doesn’t exist. 
Returns: It returns an image of Axesimage class.Other parameters: It also accepts the imshow argument for showing image.
Example 1:  
Python3
import matplotlib.pyplot as plotimport numpy as np # an array with linearly increasing valuesarray = np.diag(range(20)) plot.matshow(array) plot.show()
Output: 
Example 2: 
Python3
import numpy as npimport matplotlib.pyplot as plt alphabets = ['A', 'B', 'C', 'D', 'E'] # randomly generated arrayrandom_array = np.random.random((5, 5)) figure = plt.figure()axes = figure.add_subplot(111) # using the matshow() functioncaxes = axes.matshow(random_array, interpolation ='nearest')figure.colorbar(caxes) axes.set_xticklabels(['']+alphabets)axes.set_yticklabels(['']+alphabets) plt.show()
Output: 
 
singghakshay
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 80 - GeeksforGeeks

28 Jun, 2021
In a data link protocol, the frame delimiter flag is given by 0111. Assuming that bit stuffing is employed, the transmitter sends the data sequence 01110110 as
 (A) 01101011(B) 011010110(C) 011101100(D) 0110101100Answer: (D)Explanation:
In the above question, if, in the data link layer bits stuffing is employed 
then bit stuffing is done using the flag delimiter. If there is a flag 
of n bits then we will compare the data sequence with the flag and for every 
n-1 bits matched found, a bit 0 is stuffed in the data sequence after the matched
sequence.

Thus using the above logic
Delimiter flag: 0111
Data sequence: 01110110
So, for a flag of 4 bits we will compare data sequence with pattern of 
3 bits i.e. 011.
0 1 1 0 1 0 1 1 0 0
In the above pattern the underlined bits are found matched, hence, 0 in italics 
is stuffed. Thus resulting in the data sequence as 0110101100 which is option D

This Explanation is contributed by Namita Singh.Quiz of this Question
GATE IT 2004
GATE-GATE IT 2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
C program to sort an array in ascending order - GeeksforGeeks

31 May, 2021
Given an array arr[] of size N, the task is to sort this array in ascending order in C.Examples: 
Input: arr[] = {0, 23, 14, 12, 9}
Output: {0, 9, 12, 14, 23}

Input: arr[] = {7, 0, 2}
Output: {0, 2, 7}
Approach: There are many ways by which the array can be sorted in ascending order, like:  
Selection Sort
Bubble Sort
Merge Sort
Radix Sort
Insertion Sort, etc
For simplicity, we will be using Selection Sort in this article.The array can be sorted in ascending order by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 
The subarray which is already sorted.Remaining subarray which is unsorted.
The subarray which is already sorted.
Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.Below is the implementation of the above approach: 
C
// C program to sort the array in an// ascending order using selection sort #include <stdio.h> void swap(int* xp, int* yp){    int temp = *xp;    *xp = *yp;    *yp = temp;} // Function to perform Selection Sortvoid selectionSort(int arr[], int n){    int i, j, min_idx;     // One by one move boundary of unsorted subarray    for (i = 0; i < n - 1; i++) {         // Find the minimum element in unsorted array        min_idx = i;        for (j = i + 1; j < n; j++)            if (arr[j] < arr[min_idx])                min_idx = j;         // Swap the found minimum element        // with the first element        swap(&arr[min_idx], &arr[i]);    }} // Function to print an arrayvoid printArray(int arr[], int size){    int i;    for (i = 0; i < size; i++)        printf("%d ", arr[i]);    printf("\n");} // Driver codeint main(){    int arr[] = { 0, 23, 14, 12, 9 };    int n = sizeof(arr) / sizeof(arr[0]);    printf("Original array: \n");    printArray(arr, n);     selectionSort(arr, n);    printf("\nSorted array in Ascending order: \n");    printArray(arr, n);     return 0;}
Original array: 
0 23 14 12 9 

Sorted array in Ascending order: 
0 9 12 14 23
 
Time Complexity: O(N2)
Auxiliary Space: O(1)
subhammahato348
doubler4rahulandranjanv12
C-Arrays
C Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
How to Append a Character to a String in C
time() function in C
C Program to Swap two Numbers
Producer Consumer Problem in C
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Python | Convert None to empty string - GeeksforGeeks

25 Jun, 2019
Sometimes, while working with Machine Learning, we can encounter None values and we wish to convert to the empty string for data consistency. This and many other utilities can require the solution to this problem. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using lambdaThis task can be performed using the lambda function. In this we check for string for None or empty string using the or operator and replace the None values with empty string.
# Python3 code to demonstrate working of# Converting None to empty string# Using lambda  # initializing list of stringstest_list = ["Geeks", None, "CS", None, None]  # printing original list print("The original list is : " + str(test_list))  # using lambda# Converting None to empty stringconv = lambda i : i or ''res = [conv(i) for i in test_list]  # printing result print("The list after conversion of None values : " + str(res))
The original list is : ['Geeks', None, 'CS', None, None]
The list after conversion of None values : ['Geeks', '', 'CS', '', '']

 
Method #2 : Using str()Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which evaluates to empty string is returned.
# Python3 code to demonstrate working of# Converting None to empty string# Using str()  # initializing list of stringstest_list = ["Geeks", None, "CS", None, None]  # printing original list print("The original list is : " + str(test_list))  # using str()# Converting None to empty stringres = [str(i or '') for i in test_list]  # printing result print("The list after conversion of None values : " + str(res))
The original list is : ['Geeks', None, 'CS', None, None]
The list after conversion of None values : ['Geeks', '', 'CS', '', '']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Java BitSet | cardinality() - GeeksforGeeks

31 Jul, 2021
BitSet is a class defined in the java.util package. It creates an array of bits represented by 0s and 1s.
Syntax 
public int cardinality()
Explanation: 
The method returns the number of 1s in this BitSet.
Examples:  
Input : 
set1 : {1, 2, 4}
set2 : {}

Output : 
3
0
Java
// Java program illustrating Bitset Class functions.import java.util.*;public class GFG {    public static void main(String[] args)    {        // Constructors of BitSet class        BitSet bs1 = new BitSet();        BitSet bs2 = new BitSet();        BitSet bs3 = new BitSet();         /* set is BitSet class method        explained in next articles */        bs1.set(0);        bs1.set(1);        bs1.set(2);        bs1.set(4);         // assign values to bs2        bs2.set(4);        bs2.set(6);        bs2.set(5);        bs2.set(1);        bs2.set(2);        bs2.set(3);         // Printing the 2 Bitsets        System.out.println("bs1 : " + bs1);        System.out.println("bs2 : " + bs2);        System.out.println("bs3 : " + bs3);         // Performing logical AND        // on bs2 set with bs1        System.out.println(bs1.cardinality());        System.out.println(bs2.cardinality());        System.out.println(bs3.cardinality());    }}
bs1 : {0, 1, 2, 4}
bs2 : {1, 2, 3, 4, 5, 6}
bs3 : {}
4
6
0
 
Related Articles : 
Bitset Class Examples Set 1Bitset Class Examples Set 2Bitset Class Examples Set 3
Bitset Class Examples Set 1
Bitset Class Examples Set 2
Bitset Class Examples Set 3
 
sumitgumber28
Java - util package
Java-BitSet
Java-Functions
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 create a 3D groove border using CSS? - GeeksforGeeks

07 Apr, 2021
In CSS border-style property is used to set the line style of the border of an element. 
The border-style property may have one, two, three, or four values. When the specified value is one, the same style is applied to all four sides. When the specified value is two, the first style is applied to the top and bottom and the second style is applied to left and right. When the specified value is three, the first style is applied to the top, and the second style is applied to the left and right and the third one is applied to the bottom. When the specified value is four, the first style is applied to the top, and the second style is applied to the right, the third one is applied to the bottom and the fourth value is applied to the left.
Groove: Groove is border style which displays a border with an extruded appearance. It is the opposite of the ridge.
In this article, we will see how to create a 3D groove border using CSS. We can assign a 3D groove border to an element using the following syntax.
Syntax:
border-style: groove;
Approach: In this example, we will give the grooved border to the heading h1. You can see that in the style section we have assigned a border-style value groove which will provide a 3D groove border to the heading h1.
Example:
HTML
<!DOCTYPE html><html>  <head>    <title>How to create a 3D groove border</title>    <style type="text/css">        h1.groove {            color: green;            text-align: center;            border-width: 20px;            border-style: groove;            Border-color: #05a100        }    </style></head>  <body>    <h1 style="text-align: center;color: green;">        Welcome To GeeksforGeeks    </h1>    <h1 class="groove">Groove Border Style</h1>    <h2><strong>Note-:</strong>        This effect depend on the border-color value.</h2></body>  </html>
Output:
CSS-Basics
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to iterate through a nested List in Python? - GeeksforGeeks

08 Dec, 2020
In this article, we are going to see how to iterate through a nested List. A list can be used to store multiple Data types such as Integers, Strings, Objects, and also another List within itself. This sub-list which is within the list is what is commonly known as the Nested List.
Lets us see how a typical nested list looks like :
There are multiple ways to iterate through a Nested List:
Method 1: Use of the index to iterate through the list
Use of Positive Index:
Python3
# codelist = [10, 20, 30, 40, [80, 60, 70]]  # Printing sublist at index 4print(list[4])  # Printing 1st element of the sublistprint(list[4][0])  # Printing 2nd element of the sublistprint(list[4][1])  # Printing 3rd element of the sublistprint(list[4][2])
Output:
[80, 60, 70]
80
60
70
Use of Negative Index
Python3
# codelist = [10, 20, 30, 40, [80, 60, 70]]  # Printing sublist at index 4print(list[-1])  # Printing 1st element of the sublistprint(list[-1][-3])  # Printing 2nd element of the sublistprint(list[-1][-2])  # Printing 3rd element of the sublistprint(list[-1][-1])
Output:
[80, 60, 70]
80
60
70
Method 2: Use of loop to iterate through the list
Python3
# code# LISTlist = [["Rohan", 60], ["Aviral", 21],         ["Harsh", 30], ["Rahul", 40],        ["Raj", 20]]  # looping through nested list using indexesfor names in list:    print(names[0], "is", names[1],          "years old.")
Output:
Rohan is 60 years old.
Aviral is 21 years old.
Harsh is 30 years old.
Rahul is 40 years old.
Raj is 20 years old.
Use of Temporary Variables inside a loop.
Python3
# code# LISTlist = [["Rohan", 60], ["Aviral", 21],         ["Harsh", 30], ["Rahul", 40],        ["Raj", 20]]  # looping through nested list using multiple # temporary variablesfor name, age in list:    print(name, "is",          age, "years old.")
Output:
Rohan is 60 years old.
Aviral is 21 years old.
Harsh is 30 years old.
Rahul is 40 years old.
Raj is 20 years old.
Method 3: Use of Slicing
Python3
# code# listlist = [10, 20, 30, 40,        [80, 60, 70]]  # print the entire Sublist at index 4print(list[4][:])  # printing first two elementprint(list[4][0 : 2])
Output:
[80, 60, 70]
[80, 60]
python-list
Python-list-of-lists
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python
Initialization of a multidimensional arrays in C/C++ - GeeksforGeeks

08 Oct, 2020
In C/C++, initialization of a multidimensional arrays can have left most dimension as optional. Except the left most dimension, all other dimensions must be specified. For example, following program fails in compilation because two dimensions are not specified.  
C
C++
#include<stdio.h>int main(){  int a[][][2] = { {{1, 2}, {3, 4}},                   {{5, 6}, {7, 8}}                 };  // error  printf("%d", sizeof(a));  getchar();  return 0;}
#include<bits/stdc++.h>using namespace std;int main(){  int a[][][2] = { {{1, 2}, {3, 4}},                   {{5, 6}, {7, 8}} };  // error  cout << sizeof(a);  getchar();  return 0;} // This code is contributed by Mayank Tyagi
Following 2 programs work without any error. 
C
C++
// Program 1#include<stdio.h>int main(){  int a[][2] = {{1,2},{3,4}}; // Works  printf("%lu", sizeof(a)); // prints 4*sizeof(int)  getchar();  return 0;}
// Program 1#include<bits/stdc++.h>using namespace std;int main(){  int a[][2] = {{1, 2}, {3, 4}}; // Works  cout << sizeof(a); // prints 4*sizeof(int)  return 0;} // This code is contributed by Mayank Tyagi
C
C++
// Program 2#include<stdio.h>int main(){  int a[][2][2] = { {{1, 2}, {3, 4}},                     {{5, 6}, {7, 8}}                   }; // Works  printf("%lu", sizeof(a)); // prints 8*sizeof(int)  getchar();  return 0;}
// Program 2#include<bits/stdc++.h>using namespace std;int main(){  int a[][2][2] = { {{1, 2}, {3, 4}},                     {{5, 6}, {7, 8}} }; // Works  cout << sizeof(a); // prints 8*sizeof(int)  return 0;} // This code is contributed by Mayank Tyagi
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
HassanAli
cheto96
mayanktyagi1709
C Array and String
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Substring in C++
rand() and srand() in C/C++
Converting Strings to Numbers in C/C++
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++
TreeSet add() Method in Java - GeeksforGeeks

26 Nov, 2018
The Java.util.TreeSet.add() method in Java TreeSet is used to add a specific element into a TreeSet. The function adds the element only if the specified element is not already present in the set else the function return False if the element is not present in the TreeSet.
Syntax:
Tree_Set.add(Object element)
Parameters: The parameter element is of the type of TreeSet and it refers to the element to be added to the Set.
Return Value: The function returns True if the element is not present in the set and is new, else it returns False if the element is already present in the set.
Below program illustrates the use of Java.util.TreeSet.add() method:
// Java code to illustrate add()import java.io.*;import java.util.TreeSet;  public class TreeSetDemo {    public static void main(String args[])    {        // Creating an empty TreeSet        TreeSet<String> tree = new TreeSet<String>();          // Use add() method to add elements into the Set        tree.add("Welcome");        tree.add("To");        tree.add("Geeks");        tree.add("4");        tree.add("Geeks");        tree.add("TreeSet");          // Displaying the TreeSet        System.out.println("TreeSet: " + tree);    }}
TreeSet: [4, Geeks, To, TreeSet, Welcome]

Java - util package
Java-Collections
Java-Functions
java-treeset
Java
Java
Java-Collections
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
Internal Working of HashMap in Java
Comparator Interface in Java with Examples
Strings in Java