code-rag-bench/online-tutorials huggingface dataset:
How we can perform sort on ObjectId column in MongoDB?

To perform sort on ObjectId column, use sort(). Let us create a collection with document.
> db.demo403.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f89b0fac4d418a017858e")
}
> db.demo403.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f89b2fac4d418a017858f")
}
> db.demo403.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f89b5fac4d418a0178590")
}
> db.demo403.insertOne({"Name":"Adam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f89b8fac4d418a0178591")
}
Display all documents from a collection with the help of find() method −
> db.demo403.find();
This will produce the following output −
{ "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" }
{ "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" }
{ "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" }
{ "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" }
Following is the query to perform sort on ObjectId column in MongoDB −
> db.demo403.find().sort({_id:-1});
This will produce the following output −
{ "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" }
{ "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" }
{ "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" }
{ "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" }
DoubleStream of() in Java

06 Dec, 2018
DoubleStream of(double t) returns a sequential DoubleStream containing a single element.Syntax :
static DoubleStream of(double t)

Parameters :
DoubleStream : A sequence of primitive double-valued elements.t : Represents the single element in the DoubleStream.
DoubleStream : A sequence of primitive double-valued elements.
t : Represents the single element in the DoubleStream.
Return Value : DoubleStream of(double t) returns a sequential DoubleStream containing the single specified element.
Example :
// Java code for DoubleStream of(double t)// to get a sequential DoubleStream// containing a single element.import java.util.*;import java.util.stream.DoubleStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating a DoubleStream having single        // element only        DoubleStream stream = DoubleStream.of(8.2);          // Displaying the DoubleStream having         // single element        stream.forEach(System.out::println);    }}
Output :
8.2

DoubleStream of(double... values) returns a sequential ordered stream whose elements are the specified values.Syntax :
static DoubleStream of(double... values)

Parameters :
DoubleStream : A sequence of primitive double-valued elements.values : Represents the elements of the new stream.
DoubleStream : A sequence of primitive double-valued elements.
values : Represents the elements of the new stream.
Return Value : DoubleStream of(double... values) returns a sequential ordered stream whose elements are the specified values.
Example 1 :
// Java code for DoubleStream of(double... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.DoubleStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an DoubleStream        DoubleStream stream = DoubleStream.of(8.2, 5.6, 4.1);          // Displaying the sequential ordered stream        stream.forEach(System.out::println);    }}
Output :
8.2
5.6
4.1

Example 2 :
// Java code for DoubleStream of(double... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.DoubleStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an DoubleStream        DoubleStream stream = DoubleStream.of(5.2, 4.2, 6.3);          // Storing the count of elements in DoubleStream        long total = stream.count();          // Displaying the count of elements        System.out.println(total);    }}
Output :
3

Java - util package
java-DoubleStream
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
How to calculate strike rate of a batsman

31 Mar, 2021
Given two integers A and B representing the run scored and ball faced by a batsman in a Cricket match. The task is to calculate the Strike rate of the batsman. 
Batting strike rate is a measure of how quickly a batsman achieves the primary goal of batting. It is mathematically equal to: Strike Rate = (Runs Scored / Balls faced) * 100  
Examples:  
Input: A = 264, B = 173 Output: 152.601 Explanation: Srike rate of batsman is equal to (264 / 173) * 100 = 162.601
Input: A = 0, B = 10 Output: 0.00 
Approach:
Use the formula for the strike rate to calculate the strike rate. Strike Rate = (Runs Scored / Balls faced) * 100Return the strike rate in float data type format.
Use the formula for the strike rate to calculate the strike rate. Strike Rate = (Runs Scored / Balls faced) * 100
Return the strike rate in float data type format.
Here is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to calculate strike// rate of a batsman #include <bits/stdc++.h>using namespace std; // function to calculate strike// rate of a batsmanfloat strikerate(int bowls, int runs){    float z;    z = (float(runs) / bowls) * 100;    return z;} // Driver Codeint main(){    int A, B;    A = 264;    B = 173;     cout << strikerate(B, A)         << endl;    return 0;}
// Java program to calculate strike// rate of a batsmanclass GFG{     // function to calculate strike// rate of a batsmanstatic float strikerate(float bowls, float runs){    float z;    z = (runs / bowls) * 100;    return z;} // Driver Codepublic static void main(String[] args){    int A, B;    A = 264;    B = 173;     System.out.println(strikerate(B, A));}} // This code is contributed by rock_cool
# Python3 program to calculate strike# rate of a batsman # function to calculate strike# rate of a batsmandef strikerate(bowls, runs):     z = (float(runs) / bowls) * 100;    return z; # Driver CodeA = 264;B = 173;print(strikerate(B, A)); # This code is contributed by Code_Mech
// C# program to calculate strike// rate of a batsmanusing System;class GFG{     // function to calculate strike// rate of a batsmanstatic float strikerate(float bowls,                        float runs){    float z;    z = (runs / bowls) * 100;    return z;} // Driver Codepublic static void Main(){    int A, B;    A = 264;    B = 173;     Console.Write(strikerate(B, A));}} // This code is contributed by Code_Mech
<script> // Javascript program to calculate strike// rate of a batsman // function to calculate strike// rate of a batsmanfunction strikerate(bowls, runs){    let z;    z = (runs / bowls) * 100;    return z.toFixed(3);} // Driver code   let A, B;A = 264;B = 173; document.write(strikerate(B, A)); // This code is contributed by divyesh072019 </script>
152.601
 
Time Complexity: O (1) Auxiliary Space: O (1) 
Akanksha_Rai
rock_cool
Code_Mech
divyesh072019
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList listIterator() Method in Java

10 Dec, 2018
The Java.util.LinkedList.listIterator() method is used to return a list-iterator containing the same elements as that of the LinkedList in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method.
Syntax:
ListIterator new_list = LinkedList.listIterator(int index);

Parameters: The parameter index is an integer type value that specifies the position of the element from where ListIterator starts operating and returning values.
Return Value: The method returns the list created using ListIterator, starting from the specified index.
Below program illustrate the Java.util.LinkedList.listIterator() method:
// Java code to illustrate listIterator()import java.io.*;import java.util.LinkedList;import java.util.ListIterator;  public class LinkedListDemo {    public static void main(String args[])    {        // Creating an empty LinkedList        LinkedList<String> list = new LinkedList<String>();          // Use add() method to add elements in the list        list.add("Geeks");        list.add("for");        list.add("Geeks");        list.add("10");        list.add("20");          // Displaying the linkedlist        System.out.println("LinkedList:" + list);                  // Setting the ListIterator at a specified position        ListIterator list_Iter = list.listIterator(2);          // Iterating through the created list from the position        System.out.println("The list is as follows:");        while(list_Iter.hasNext()){           System.out.println(list_Iter.next());        }    }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The list is as follows:
Geeks
10
20

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
response.links – Python requests

01 Mar, 2020
response.links returns the header links. To know more about Http Headers, visit – Http Headers. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.links out of a response object.
To illustrate use of response.links, let’s ping api.github.com. To run this script, you need to have Python and requests installed on your PC.
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
response.links
# import requests moduleimport requests  # Making a get requestresponse = requests.get('https://api.github.com/')  # print responseprint(response)  # print linksprint(response.links)
Save above file as request.py and run using
Python request.py

Check that {} at the start of the output, it shows the header links JSON.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
What is Nikto and it’s usages ?

19 Nov, 2021
Nikto is an Open Source software written in Perl language that is used to scan a web-server for the vulnerability that can be exploited and can compromise the server. It can also check for outdated version details of 1200 server and can detect problems with specific version details of over 200 servers. It can also fingerprint server using favicon.ico files present in the server. It is not designed to be a particularly a stealth tool rather than it is designed to be fast and time-efficient to achieve the task in very little time. Because of this, a web admin can easily detect that its server is being scanned by looking into the log files. It can also show some items that do not have security problem but are info only which shows how to take full use of it to secure the web-server more properly. 
Features:  
Full support for SSL
Finds sub-domain
Supports full HTTP Proxy
Outdated component report
Result saved in multiple format (xml, csv etc)
Username guessing
Gives details of installed software
Takes Nmap file as input to scan port in a web-server.
Able to perform dictionary attack.
Updated easily
How to install Nikto in Linux:  
Step 1: root@kali:~# git clone https://github.com/sullo/nikto.git
Step 2: root@kali:~# cd nikto/program
Step 3: root@kali:~/nikto/program# perl nikto.pl 
Usages:-  
Help menu: root@kali:~/nikto/program# perl nikto.pl -H  
Scan a website: root@kali:~/nikto/program# perl nikto.pl -host https://www.webscantest.com/  
 
rajeev0719singh
Software Testing
GBlog
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
How to Learn Data Science in 10 weeks?
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Installation of Node.js on Linux
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 ?
Differences between Functional Components and Class Components in React
Lodash _.isUndefined() Method

06 Sep, 2020
The _.isUndefined() method is used to find whether the given value is undefined or not. It returns True if the given value is undefined. Otherwise, it returns false.
Syntax:
_.isUndefined(value)
Parameters: This method accepts a single parameter as mentioned above and described below.
value: This parameter holds the value to check.
value: This parameter holds the value to check.
Return Value: This method returns true if the value is undefined, else false.
Example 1: In the following example, const _ = require(“lodash”) is used to import the lodash library into the file.
Javascript
// The lodash library is included const _ = require("lodash");        // Use of _.isUndefined() method console.log(_.isUndefined(null)); console.log(_.isUndefined(void 0)); console.log(_.isUndefined('gfg')); 
Output:
false
true
false

Example 2:
Javascript
// The lodash library is includedconst _ = require("lodash");        // Use of _.isUndefined() method console.log(_.isUndefined(window.missingVariable)); console.log(_.isUndefined(10)); console.log(_.isUndefined(undefined)); 
Output:
true
false
true

JavaScript-Lodash
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
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
Ways of iterating over a array in JavaScript.

22 Nov, 2021
Arrays in Javascripts, are single variables used to store different kind of elements.For example, a simple array accesses may something like this:  
javascript
<script>array = [ 'geeks', '4', 'geeks' ]; // Accessing array elements one by oneconsole.log(array[0]);console.log(array[1]);console.log(array[2]);</script>
Output:  
geeks
4
geeks
There are multiple ways one can iterate over an array in Javascript. The most useful ones are mentioned below.Using for loop. This is similar to for loops in other languages like C/C++, Java, etc  
javascript
<script>array = [ 1, 2, 3, 4, 5, 6 ];for (index = 0; index < array.length; index++) {    console.log(array[index]);}</script>
Output:  
1
2
3
4
5
6
Using while loop. This is again similar to other languages.  
javascript
<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; while (index < array.length) {    console.log(array[index]);    index++;}</script>
Output:  
1
2
3
4
5
6
using forEach method. The forEach method calls the provided function once for every array element in the order.  
javascript
<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; array.forEach(myFunction);function myFunction(item, index){    console.log(item);}</script>
Output:  
1
2
3
4
5
6
Using every method. The every() method checks if all elements in an array pass a test (provided as a function).  
javascript
<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; const under_five = x => x < 5; if (array.every(under_five)) {    console.log('All are less than 5');}else {    console.log('At least one element is not less than 5');}</script>
Output:  
At least one element is not less than 5.
Using map. A map applies a function over every element and then returns the new array.  
javascript
<script>index = 0;array = [ 1, 2, 3, 4, 5, 6 ]; square = x => Math.pow(x, 2);squares = array.map(square);console.log(array);console.log(squares);</script>
Output:  
1 2 3 4 5 6 
1 4 9 16 25 36
Using Filter
It is used to filter values from an array and return the new filtered array
Javascript
<script> array = [ 1, 2, 3, 4, 5, 6 ]; even = x => x%2 === 0;evens = array.filter(even);console.log(array);console.log(evens); </script>
Output:
[ 1, 2, 3, 4, 5, 6 ]
[ 2, 4, 6 ]
Using Reduce
It is used to reduce the array into one single value using some functional logic
Javascript
<script> array = [ 1, 2, 3, 4, 5, 6 ]; const helperSum = (acc,curr) => acc+currsum = array.reduce(helperSum, 0); console.log(array)console.log(sum); </script>
Output:
[ 1, 2, 3, 4, 5, 6 ]
21
Using Some
It is used to check whether some array values passes a test
Javascript
<script> array = [ 1, 2, 3, 4, 5, 6 ]; const lessthanFourCheck = (element) => element < 4 ;const lessthanFour = array.some(lessthanFourCheck)  console.log(array);if(lessthanFour){    console.log("At least one element is less than 4" )}else{    console.log("All elements are greater than 4 ")}  </script>
Output : 
[ 1, 2, 3, 4, 5, 6 ]
At least one element is less than 4
Pallavi Yadav
prasanna1995
javascript-array
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use complete horizontal line space in HTML ?

13 Jan, 2022
In this article, we will create a complete horizontal line space using HTML. To create the horizontal line space, we will use the <hr> tag.
The <hr> tag stands for horizontal rule and is used to insert a horizontal rule or a thematic break in an HTML page to divide or separate document sections. The <hr> tag is an empty tag, and it does not require an end tag.
Syntax:
<hr>
Attributes:
align: It specifies the alignment of the horizontal rule.
noshade: It specifies the bar without shading effect.
size: It specifies the height of the horizontal rule.
width: It specifies the width of the horizontal rule.
Approach: In the below example, we will create two paragraph elements containing some content and add a <hr> tag between these two paragraph elements to create a horizontal line space.
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>        How to use complete horizontal         line space in HTML?     </title></head>  <body>    <center>        <h1 style="color:green;">            GeeksforGeeks        </h1>        <h3>            How to use complete horizontal             line space in HTML?         </h3>        <p>Welcome to GeeksforGeeks</p>        <hr>        <p>Learning portal</p>    </center></body></html>
Output:
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Make a div horizontally scrollable using CSS
DOM (Document Object Model)
How to get values from html input array using JavaScript ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How do you run JavaScript script through the Terminal?
Node.js fs.readFileSync() Method
How to set space between the flexbox ?
How to convert a DOM nodelist to an array using JavaScript ?

04 Oct, 2021
NodeList objects are the collection of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll(). Although NodeList is not an actual Array but it is possible to iterate over it with the help of forEach() method. NodeList can also be converted into actual array by following methods.
Method 1: By using Array.prototype.slice.call() method.
Syntax: 
const array = Array.prototype.slice.call(nodeList);
Example: 
HTML
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8" />    <meta name="viewport" content=        "width=device-width, initial-scale=1.0" />    <title>Document</title></head> <body>     <p>Hello geeks 1</p>      <p>Hello geeks 2</p>      <p>Hello geeks 3</p>      <p>Hello geeks 4</p>      <script>         // This is nodeList        const nodeList = document.querySelectorAll('p');        console.log(nodeList);         // Converting using Array.prototype.slice.call        const array1 = Array.prototype.slice.call(nodeList);        console.log(array1);    </script></body> </html>
Output:
Method 2: With the help of Array.from() method.
Syntax: 
const array = Array.from(nodeList);
Example: 
HTML
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8" />    <meta name="viewport" content=        "width=device-width, initial-scale=1.0" />    <title>Document</title></head> <body>     <p>Hello geeks 1</p>      <p>Hello geeks 2</p>      <p>Hello geeks 3</p>      <p>Hello geeks 4</p>      <script>         // This is nodeList        const nodeList = document.querySelectorAll('p');        console.log(nodeList);         // Converting to array using Array.from() method        const array = Array.from(nodeList);        console.log(array);    </script></body> </html>
Output:
Method 3: Using ES6 spread syntax, it allows an iterable such as an array expression or string to be expanded in places where zero or more arguments or elements are expected. 
Syntax: 
const array = [ ...nodeList ]
Example: 
HTML
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8" />    <meta name="viewport" content=        "width=device-width, initial-scale=1.0" />    <title>Document</title></head> <body>     <p>Hello geeks 1</p>      <p>Hello geeks 2</p>      <p>Hello geeks 3</p>      <p>Hello geeks 4</p>      <script>         // This is nodeList        const nodeList = document.querySelectorAll('p');        console.log(nodeList);         // Converting using Spread syntax        const array1 = [...nodeList];        console.log(array1);    </script></body> </html>
Output:
Note: Method 2 and Method 3 may not work in older browsers properly but will work fine in all modern browsers. 
akshaysingh98088
HTML-Misc
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use GROUP BY to concatenate strings in MySQL and how to set a separator for the concatenation?

To concatenate strings in MySQL with GROUP BY, you need to use GROUP_CONCAT() with a SEPARATOR parameter which may be comma(‘) or space (‘ ‘) etc.
The syntax is as follows:
SELECT yourColumnName1,GROUP_CONCAT(yourColumnName2 SEPARATOR ‘yourValue’) as anyVariableName FROM yourTableName GROUP BY yourColumnName1;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table GroupConcatenateDemo
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.99 sec)
Insert some records in the table using insert command. The query to insert record is as follows:
mysql> insert into GroupConcatenateDemo values(10,'Larry');
Query OK, 1 row affected (0.41 sec)
mysql> insert into GroupConcatenateDemo values(11,'Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into GroupConcatenateDemo values(12,'John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into GroupConcatenateDemo values(10,'Elon');
Query OK, 1 row affected (0.63 sec)
mysql> insert into GroupConcatenateDemo values(10,'Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into GroupConcatenateDemo values(11,'Sam');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from GroupConcatenateDemo;
The following is the output:
+------+-------+
| Id   | Name  |
+------+-------+
|   10 | Larry |
|   11 | Mike  |
|   12 | John  |
|   10 | Elon  |
|   10 | Bob   |
|   11 | Sam   |
+------+-------+
6 rows in set (0.00 sec)
Here is the query that use GROUP BY to concatenate the strings in MySQL. Perform GROUP BY on the basis of Id and concatenate the strings using GROUP_CONCAT() function in MySQL.
The query is as follows:
mysql> select Id,group_concat(Name SEPARATOR ',') as GroupConcatDemo from GroupConcatenateDemo
   -> group by Id;
The following is the output:
+------+-----------------+
| Id   | GroupConcatDemo |
+------+-----------------+
|   10 | Larry,Elon,Bob  |
|   11 | Mike,Sam        |
|   12 | John            |
+------+-----------------+
3 rows in set (0.00 sec)
What are Partial functions in JavaScript?

Partial functions allow takes a function as an argument and along with it takes arguments of other types too. It then uses some of the arguments passed and returns a function that will take the remaining arguments. The function returned when invoked will call the parent function with the original and its own set of arguments.
Following is the code for partial functions in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Partial function in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to see partial function invocation
</h3>
<script>
   let resultEle = document.querySelector(".result");
   function partialFunction(f) {
      return function (a) {
         return function (b) {
            return f(a, b);
         };
      };
   }
   function multiply(a, b) {
      return a * b;
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML = "partialFunction(multiply) = " + partialFunction(multiply) + "<br>";
      resultEle.innerHTML += "partialFunction(multiply)(22) = " + partialFunction(multiply)(22) +
"<br>";
      resultEle.innerHTML += "partialFunction(multiply)(22)(33) = " + partialFunction(multiply)(22)(33) + "<br>";
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
HashTable forEach() method in Java with Examples - GeeksforGeeks

01 Oct, 2019
The forEach(BiConsumer) method of Hashtable class perform the BiConsumer operation on each entry of hashtable until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until all elements have been processed by the method or an exception occurs. Exceptions thrown by the Operation are passed to the caller.
Syntax:
public void 
    forEach(BiConsumer<? super K, ? super V> action)
Parameters: This method takes a parameter name BiConsumer which represents the action to be performed for each element.
Returns: This method returns nothing.
Exception: This method throws:
NullPointerException: if the specified action is null.
Below programs illustrate the forEach(BiConsumer) method:
Program 1:
// Java program to demonstrate// forEach(BiConsumer) method.  import java.util.*;  public class GFG {      // Main method    public static void main(String[] args)    {          // create a table and add some values        Map<String, Integer>            table = new Hashtable<>();          table.put("Pen", 10);        table.put("Book", 500);        table.put("Clothes", 400);        table.put("Mobile", 5000);        table.put("Booklet", 2500);          // add 100 in each value using forEach()        table.forEach((k, v) -> {              v = v + 100;            table.replace(k, v);        });          // print new mapping using forEcah()        table.forEach(            (k, v) -> System.out.println("Key : " + k + ", Value : " + v));    }}
Key : Booklet, Value : 2600
Key : Clothes, Value : 500
Key : Mobile, Value : 5100
Key : Pen, Value : 110
Key : Book, Value : 600

Program 2: To Show NullPointerException
// Java program to demonstrate// forEach(BiConsumer) method.  import java.util.*;  public class GFG {      // Main method    public static void main(String[] args)    {          // create a table and add some values        Map<Integer, String>            table = new Hashtable<>();          table.put(1, "100RS");        table.put(2, "500RS");        table.put(3, "1000RS");          try {              // add 100 in each value using forEach()            table.forEach((k, v) -> {                  v = v + 100;                table.put(null, v);            });        }        catch (Exception e) {              System.out.println("Exception: " + e);        }    }}
Exception: java.lang.NullPointerException

References: https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html#forEach-java.util.function.BiConsumer-
nidhi_biet
java-basics
Java-Functions
Java-HashTable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
How to Remove repetitive characters from words of the given Pandas DataFrame using Regex? - GeeksforGeeks

29 Oct, 2021
Prerequisite: Regular Expression in Python
In this article, we will see how to remove continuously repeating characters from the words of the given column of the given Pandas Dataframe using Regex.
Here, we are actually looking for continuously occurring repetitively coming characters for that we have created a pattern that contains this regular expression (\w)\1+ here \w is for character, 1+ is for the characters that come more than once. 
We are passing our pattern in the re.sub() function of re library. 
Syntax: re.sub(pattern, repl, string, count=0, flags=0)
The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in the given string(3rd parameter), and upon finding the substring pattern is replaced by repl(2nd parameter), count checks and maintains the number of times this occurs. 
Now, Let’s create a Dataframe:
Python3
# importing required librariesimport pandas as pdimport re # creating Dataframe with column# as name and common_commentsdf = pd.DataFrame(  {    'name' : ['Akash', 'Ayush', 'Diksha',              'Priyanka', 'Radhika'],         'common_comments' : ['hey buddy meet me today ',                         'sorry bro i cant meet',                         'hey akash i love geeksforgeeks',                         'twiiter is the best way to comment',                         'geeksforgeeks is good for learners']    },       columns = ['name', 'common_comments'])# printing Dataframedf
  
Output:
 
 
Now, Remove continuously repetitive characters from words of the Dataframe common_comments column. 
 
Python3
# define a function to remove# continuously repeating character# from the worddef conti_rep_char(str1):    tchr = str1.group(0)    if len(tchr) > 1:      return tchr[0:1]     # define a function to check# whether unique character# is present or notdef check_unique_char(rep, sent_text):       # regular expression for    # repetition of characters    convert = re.sub(r'(\w)\1+',                     rep,                     sent_text)         # returning the converted word    return convert df['modified_common_comments'] = df['common_comments'].apply(                                   lambda x : check_unique_char(conti_rep_char,                                                              x))# show Dataframedf
  
Output:
 
 
akshaysingh98088
sooda367
prachisoda1234
Python pandas-dataFrame
Python Regex-programs
Python-pandas
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
chr() in Python - GeeksforGeeks

15 Nov, 2017
The chr() method returns a string representing a character whose Unicode code point is an integer.Syntax:
chr(num)
num : integer value

The chr() method takes only one integer as argument.
The range may vary from 0 to 1,1141,111(0x10FFFF in base 16).
The chr() method returns a character whose unicode point is num, an integer.
If an integer is passed that is outside the range then the method returns a ValueError.
Example: Suppose we want to print ‘G e e k s f o r G e e k s’.
# Python program to illustrate # chr() builtin function  print(chr(71), chr(101),chr(101), chr(107),chr(115), chr(32),chr(102), chr(111),chr(114),chr(32),chr(71), chr(101),chr(101), chr(107), chr(115))
Output:
G e e k s   f o r   G e e k s

Another example :
# Python program to illustrate # chr() builtin function  numbers = [17, 38, 79]  for number in numbers:          # Convert ASCII-based number to character.    letter = chr(number)    print("Character of ASCII value", number, "is ", letter)
Output:
Character of ASCII value 17 is  
Character of ASCII value 38 is  &
Character of ASCII value 79 is  O
What happens if we give something out of range?
# Python program to illustrate # chr() builtin function# if value given is # out of range  # Convert ASCII-based number to characterprint(chr(400))
Output:
No Output

We wont get any output and the compiler will throw an error:
Traceback (most recent call last):
  File "/home/484c76fb455a624cc137946a244a9aa5.py", line 1, in 
    print(chr(400))
UnicodeEncodeError: 'ascii' codec can't encode character 
'\u0190' in position 0: ordinal not in range(128)

Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
Data Structures | Linked List | Question 3 - GeeksforGeeks

11 Jan, 2013
Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node of doubly linked list has previous pointer as prev and next pointer as next.
void fun(struct node **head_ref){    struct node *temp = NULL;    struct node *current = *head_ref;      while (current !=  NULL)    {        temp = current->prev;        current->prev = current->next;        current->next = temp;        current = current->prev;    }      if(temp != NULL )        *head_ref = temp->prev;}
Assume that reference of head of following doubly linked list is passed to above function
1 2 3 4 5 6.
What should be the modified linked list after the function call?(A) 2 1 4 3 6 5(B) 5 4 3 2 1 6.(C) 6 5 4 3 2 1.(D) 6 5 4 3 1 2Answer: (C)Explanation: The given function reverses the given doubly linked list. See Reverse a Doubly Linked List for details.
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Advantages and Disadvantages of Linked List
Introduction to Data Structures | 10 most commonly used Data Structures
FIFO vs LIFO approach in Programming
Data Structures | Stack | Question 6
Bit manipulation | Swap Endianness of a number
Data Structures | Queue | Question 11
Advantages of vector over array in C++
Data Structures | Queue | Question 2
Encryption and Decryption of String according to given technique
CICS - COBOL Basics

CICS programs are written in COBOL language in Mainframes. We will be discussing about writing a simple COBOL-CICS program, compiling it, and then executing it.
We will be writing a simple COBOL-CICS program which displays some message on the CICS output screen. This program is to demonstrate the steps involved in executing a COBOL-CICS program. Following are the steps to code a simple program −
Login to Mainframes and open a TSO Session.
Create a new PDS in which we will be coding our program.
Create a new member inside the PDS and code the following program −
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
01 WS-MESSAGE PIC X(40).
01 WS-LENGTH  PIC S9(4) COMP.
PROCEDURE DIVISION.
A000-MAIN-PARA.
   MOVE 'Hello World' TO WS-MESSAGE
   MOVE '+12' TO WS-LENGTH
   EXEC CICS SEND TEXT 
      FROM (WS-MESSAGE)
      LENGHT(WS-LENGTH)  
   END-EXEC
   EXEC CICS RETURN
   END-EXEC.	 

After coding the program, we need to compile it. We can compile the program using the following JCL −
//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C  
//CICSCOB  EXEC CICSCOB,                                                
//COPYLIB = ABC.XYZ.COPYLIB,                            
//LOADLIB = ABC.XYZ.LOADLIB 
//LIB        JCLLIB ORDER = CICSXXX.CICS.XXXPROC                
//CPLSTP     EXEC DFHEITVL                                
//TRN.SYSIN  DD DSN = ABC.XYZ.PDS(HELLO),DISP = SHR     
//LKED.SYSIN DD *                                        
   NAME HELLO(R)                                          
//

Open a CICS session.
We will now install the program using the following command −
CEMT SET PROG(HELLO) NEW.

Execute the program using the associated transaction-id. Transaction-id is provided by the Administrator. It will show the following output −
The following flowchart shows the steps used in compiling a COBOL-CICS program −
The function of a translator is to check for syntax errors in CICS commands. It translates them into equivalent COBOL statements.
The function of a compiler is to expand the COBOL copy books. It compiles the code after checking the source code for syntax errors.
The function of a Linkage Editor is to link different object modules to create a single load module.
 Print
 Add Notes
 Bookmark this page
Program to find the maximum profit we can get by buying on stock market once in Python

Suppose we have a list of prices representing the stock prices of a company in chronological sequence, we have to find the maximum profit we could have made from buying and selling that stock only once. We have to keep in mind that we must buy before we can sell it.
So, if the input is like prices = [10, 12, 9, 6, 8, 12], then the output will be 6, as we can buy at 6 and sell at 12.
To solve this, we will follow these steps −
max_profit := 0
min_stock := infinity
for each price in prices, domax_profit := maximum of max_profit and (price - min_stock)min_stock := minimum of min_stock and price
max_profit := maximum of max_profit and (price - min_stock)
min_stock := minimum of min_stock and price
return max_profit
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, prices):
      max_profit = 0
      min_stock = float('inf')
      for price in prices:
         max_profit = max(max_profit, price - min_stock)
         min_stock = min(min_stock, price)
      return max_profit
ob = Solution()
print(ob.solve([10, 12, 9, 6, 8, 12]))
[10, 12, 9, 6, 8, 12]
6
How can we Implement a Queue using Stack in Java?


A Queue class extends Collection interface and it supports the insert and removes operations using a first-in-first-out (FIFO).  A Stack is a subclass of Vector class and it represents last-in-first-out (LIFO) stack of objects. The last element added at the top of the stack (In) can be the first element to be removed (Out) from the stack. We can also implement a Queue using Stack in the below program.
import java.util.*;
public class QueueUsingStackTest {
   private Stack stack1 = new Stack<>();
   private Stack stack2 = new Stack<>();
   public void enqueue(int element) {
      stack1.push(element);
      System.out.println(element + " inserted");
   }
   public void dequeue() {
      if(stack2.isEmpty()) {
         while (!stack1.isEmpty()) {
            stack2.push(stack1.pop());
         }
      }
      System.out.println(stack2.pop() + " removed");
   }
   public static void main(String args[]) {
      QueueUsingStackTest test = new QueueUsingStackTest();
      test.enqueue(10);
      test.enqueue(50);
      test.enqueue(100);
      test.dequeue();
   }
}
10 inserted
50 inserted
100 inserted
10 removed
Convert the ASCII value sentence to its equivalent string in C++

In this tutorial, we will be discussing a program to convert the ASCII value sentence to its equivalent string.
For this we will be provided with a string containing the ASCII codes. Our task is to convert the given string into the equivalent characters and print it back.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//converting the ASCII sequence into
//character string
void convert_ASCII(string str, int len){
   int num = 0;
   for (int i = 0; i < len; i++) {
      //appending the current digit
      num = num * 10 + (str[i] - '0');
      //checking if number is within range
      if (num >= 32 && num <= 122) {
         char ch = (char)num;
         cout << ch;
         num = 0;
      }
   }
}
int main(){
   string str = "104101108108111443211911111410810033";
   int len = str.length();
   convert_ASCII(str, len);
   return 0;
}
hello, world!
Material - Alert Icons

This chapter explains the usage of Google's (Material) Alert icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
		
      <style>
         i.custom {font-size: 2em; color: green;}
      </style>
		
   </head>
	
   <body>
      <i class = "material-icons custom">accessibility</i>
   </body>
	
</html>
The following table contains the usage and results of Google's (Material) Alert icons. Replace the < body > tag of the above program with the code given in the table to get the respective outputs −

    26 Lectures 
     2 hours 

 Neha Gupta

    20 Lectures 
     2 hours 

 Asif Hussain

    43 Lectures 
     5 hours 

 Sharad Kumar

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    71 Lectures 
     10 hours 

 Chaand Sheikh

    207 Lectures 
     33 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How can I filter JSON data with multiple objects?

To filter JSON data with multiple objects, you can use the concept of filter along with ==.
const jsonObject=
[
   {
      studentId:101,
      studentName:"David"
   },
   {
      studentId:102,
      studentName:"Mike"
   },
   {
      studentId:103,
      studentName:"David"
   },
   {
      studentId:104,
      studentName:"Bob"
   }
]
var result=jsonObject.filter(obj=> obj.studentName == "David");
console.log(result);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo194.js. This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo194.js
[
   { studentId: 101, studentName: 'David' },
   { studentId: 103, studentName: 'David' }
]
queue::swap() in C++ STL

In this article we will be discussing the working, syntax and examples of queue::swap() function in C++ STL.
Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue.
queue::swap() is an inbuilt function in C++ STL which is declared in  header file. queue::swap() is used to swap the contents of the queue containers. This function accepts one parameter, which is the other queue container with whom we wish to swap the contents of the associated queue container.
myqueue1.swap(myqueue2);
This function accepts one parameter the second queue container with whom we wish to swap the associated queue.
This function returns nothing.
Input: queue<int> odd = {1, 3, 5};
      queue<int> eve = {2. 4. 6};
Output:
      Odd: 2 4 6
      Eve: 1 3 5
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue_1, Queue_2;
   for(int i=0 ;i<=5 ;i++){
      Queue_1.push(i);
   }
   for(int i=5 ;i<=10 ;i++){
      Queue_2.push(i);
   }
   //call swap function
   Queue_1.swap(Queue_2);
   cout<<"Element in Queue_1 are: ";
   while (!Queue_1.empty()){
      cout << ' ' << Queue_1.front();
      Queue_1.pop();
   }
   cout<<"\nElement in Queue_2 are: ";
   while (!Queue_2.empty()){
      cout << ' ' << Queue_2.front();
      Queue_2.pop();
   }
}
If we run the above code it will generate the following output −
Element in Queue_1 are: 5 6 7 8 9 10
Element in Queue_1 are: 0 1 2 3 4 5
How to convert a Python for loop to while loop?

Unlike while loop, for loop in Python doesn't need a counting variable to keep count of number of iterations. Hence, to convert a for loop into equivalent while loop, this fact must be taken into consideration.
Following is a simple for loop that traverses over a range
for x in range(5):
     print (x)


To convert into a while loop, we initialize a counting variable to 0 before the loop begins and increment it by 1 in every iteration as long as it is less than 5
x=0
while x<5:
     x=x+1
     print (x)