code-rag-bench/online-tutorials huggingface dataset:
HTTP headers | Access-Control-Request-Method

10 May, 2020
The HTTP headers Access-Control-Request-Method is a request type header which has been used to inform the server that which HTTP method will be used when the actual request is made.
Syntax:
Access-Control-Request-Method: <method>
Directives: This header accept a single directive which is mentioned above and described below:
<method>: This directive holds the method which will be used when the actual request is made.
Note: Multiple methods can be used when the actual request will be made.
Example:
Access-Control-Request-Method: POST
Access-Control-Request-Method: POST
Access-Control-Request-Method: GET, PUT
Access-Control-Request-Method: GET, PUT
To check this Access-Control-Request-Method in action go to Inspect Element -> Network check the request header for Access-Control-Request-Method like below, Access-Control-Request-Method is highlighted you can see.
Supported Browsers: The browsers compatible with HTTP headers Access-Control-Request-Method are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to import JSON File in MongoDB using Python?

10 Jun, 2020
Prerequisistes: MongoDB and Python, Working With JSON Data in Python
MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs.
JSON stands for JavaScript Object Notation. It is an open standard file format, and data interchange format with an extension “.json”, that uses human-readable text to store and transmit data objects consisting of attribute-value pairs and array data types.
To import a JSON file in MongoDB we have to first load or open the JSON file after that we can easily insert that file into the database or the collection. To load a JSON file we have to first import json in our code after that we can open the JSON file. When our file gets loaded or opened we can easily insert it into the collection and operate on that file. Let’s see the example for better understanding.
Example :
Sample JSON used:
import jsonfrom pymongo import MongoClient     # Making Connectionmyclient = MongoClient("mongodb://localhost:27017/")    # database db = myclient["GFG"]   # Created or Switched to collection # names: GeeksForGeeksCollection = db["data"]  # Loading or Opening the json filewith open('data.json') as file:    file_data = json.load(file)      # Inserting the loaded data in the Collection# if JSON contains data more than one entry# insert_many is used else inser_one is usedif isinstance(file_data, list):    Collection.insert_many(file_data)  else:    Collection.insert_one(file_data)
Output:
Python-mongoDB
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python | Pandas Series.duplicated()

13 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.duplicated() function indicate duplicate Series values. The duplicated values are indicated as True values in the resulting Series. Either all duplicates, all except the first or all except the last occurrence of duplicates can be indicated.
Syntax: Series.duplicated(keep=’first’)
Parameter :keep : {‘first’, ‘last’, False}, default ‘first’
Returns : pandas.core.series.Series
Example #1: Use Series.duplicated() function to find the duplicate values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.duplicated() function to find the duplicate values in the underlying data of the given series object.
# detect duplicatesresult = sr.duplicated()  # Print the resultprint(result)
Output :
As we can see in the output, the Series.duplicated() function has successfully detected the duplicated values in the given series object. False indicates that the corresponding value is unique whereas, True indicates that the corresponding value was a duplicated value in the given series object. Example #2 : Use Series.duplicated() function to find the duplicate values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 11, 8, 18, 65, 18, 32, 10, 5, 32, 32])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.duplicated() function to find the duplicate values in the underlying data of the given series object.
# detect duplicatesresult = sr.duplicated()  # Print the resultprint(result)
Output :As we can see in the output, the Series.duplicated() function has successfully detected the duplicated values in the given series object. False indicates that the corresponding value is unique whereas, True indicates that the corresponding value was a duplicated value in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Change the Line Width of a Graph Plot in Matplotlib with Python?

12 Nov, 2020
Prerequisite : Matplotlib 
In this article we will learn how to Change the Line Width of a Graph Plot in Matplotlib with Python. For that one must be familiar with the given concepts:
Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It was introduced by John Hunter within the year 2002.
Graph Plot : A plot is a graphical technique for representing a data set, usually as a graph showing the relationship between two or more variables.
Line Width : The width of a line is known as line width. One can change the line width of a graph in matplotlib using a feature.
Import packages
Import or create the data
Draw a graph plot with a line
Set the line width by using line-width feature ( lw can also be used as short form ).
Example 1:
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax_values = np.arange(0, 10)y_values = np.arange(0, 10)  # Adjust the line widthsplt.plot(x_values, y_values - 2, linewidth=5)plt.plot(x_values, y_values)plt.plot(x_values, y_values + 2, lw=5)  # add legends and showplt.legend(['Lw = 5', 'Lw = auto', 'Lw = 5'])plt.show()
Output :
Example 2 :
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax_values = np.linspace(0, 10, 1000)y_values = np.sin(x_values)  # Adjust the line widthsfor i in range(20):    plt.plot(x_values, y_values + i*0.5, lw=i*0.5)      plt.show()
Output :
Example 3 :
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax_values = np.linspace(0, 10, 1000)  # Adjust the line widthsfor i in range(20):    plt.plot(x_values, np.sin(x_values) + i*0.5, lw=i*0.4)    plt.plot(x_values, np.cos(x_values) + i*0.5, lw=i*0.4)      plt.show()
Output :
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL | Operator precedence

04 Feb, 2019
Operator precedence specifies the order in which operators are evaluated when two or more operators with different precedence are adjacent in an expression.
For example, 1+2/3 gives the different result as compared to (1+2)/3. Just like all other programming languages C, C++, Java etc. MySQL also has a precedence rule.
The following table describes operator precedence in MySQL, from highest to lowest. Operators which are in the same group have the equal precedence.
These operator precedence rule greatly affects our MySQL queries.Without knowledge of operator precedence we can get unexpected result. To, understand this consider the following table Student.
From the above table we want the result of those students having marks greater than 10 and whose name starts with either ‘p’ or ‘s’. So, it’s query can be written as-
mysql>select * 
from student 
where marks>10 and name like 'p%' 
                   or name like 's%'; 
Result:It will produce the desired result:
This result set is not as expected from the query. As it is giving the result of a student ‘Punit’ having marks less than 10 which is not required. Due to higher precedence of operator AND as compare to OR, the above query give result of all those students having marks greater than 10 and name starting with ‘s’, in addition to those the result of those student having name starting with ‘p’ is also given in output. So, here come role of parentheses. The above-stated query can be written as,
mysql>select * 
from student 
where marks>10 and (name like 'p%' 
                       or name like 's%');
Result:It will produce the desired result:
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
Difference between DELETE and TRUNCATE
MySQL | Group_CONCAT() Function
SQL Correlated Subqueries
MySQL | Regular expressions (Regexp)
SQL - ORDER BY
Difference between Transparent Bridge and Source Routing Bridge

08 Nov, 2020
Bridge is a device that is attached to connect two or more LANs to create continued LAN. A bridge works at data link layer of the OSI reference model. 
Transparent Bridge: Transparent bridge automatically maintains a routing table and update table in response to maintain changing topology. Transparent bridge mechanism consists of three mechanisms: 
1. Frame forwarding
2. Address Learning
3. Loop Resolution 


Transparent bridge is easy to use, install the bridge and no software changes are needed in hosts. In all the cases, transparent bridge flooded the broadcast and multicast frames. 
Source Routing Bridge: Source routing bridge decides the route between two hosts. Source routing bridge uses the MAC destination address of a frame to direct it by the source routing algorithm. In source routing, the route over which the frame is to send is Known to every station on the extended LAN. The routing information is stored in the frames. 
The difference between Transparent Bridge and Source Routing Bridge are as following: 
 
itskawal2000
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Python | Pandas Series.from_csv()

13 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.from_csv() function is used to read a csv file into a series. It is preferable to use the more powerful pandas.read_csv() for most general purposes.
Syntax: Series.from_csv(path, sep=’, ‘, parse_dates=True, header=None, index_col=0, encoding=None, infer_datetime_format=False)
Parameter :path : string file path or file handle / StringIOsep : Field delimiterparse_dates : Parse dates. Different default from read_tableheader : Row to use as header (skip prior rows)index_col : Column to use for indexencoding : a string representing the encoding to use if the contents are non-asciiinfer_datetime_format : If True and parse_dates is True for a column, try to infer the datetime format based on the first datetime string
Returns : Series
For this example we have used a CSV file. To download click here
Example #1: Use Series.from_csv() function to read the data from the given CSV file into a pandas series.
# importing pandas as pdimport pandas as pd  # Read the data into a seriessr = pd.Series.from_csv('nba.csv')  # Print the first 10 rows of seriesprint(sr.head(10))
Output :
As we can see in the output, the Series.from_csv() function has successfully read the csv file into a pandas series. Example #2 : Use Series.from_csv() function to read the data from the given CSV file into a pandas series. Use the 1st column as an index of the series object.
# importing pandas as pdimport pandas as pd  # Read the data into a seriessr = pd.Series.from_csv('nba.csv', index_col = 1)  # Print the first 10 rows of seriesprint(sr.head(10))
Output :
As we can see in the output, the Series.from_csv() function has successfully read the csv file into a pandas series.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Array concat() Method

04 Oct, 2021
Below is the example of Array concat() method to join three arrays.
Example:<script>// JavaScript code for concat() methodfunction func() {    var num1 = [11, 12, 13],        num2 = [14, 15, 16],        num3 = [17, 18, 19];    document.write(num1.concat(num2, num3));}func();</script>
<script>// JavaScript code for concat() methodfunction func() {    var num1 = [11, 12, 13],        num2 = [14, 15, 16],        num3 = [17, 18, 19];    document.write(num1.concat(num2, num3));}func();</script>
Output:[11,12,13,14,15,16,17,18,19]

[11,12,13,14,15,16,17,18,19]

The arr.concat() method is used to merge two or more arrays together. This method does not alter the original arrays passed as arguments.
Syntax:
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
Parameters: The parameters to this method are the arrays or the values that need to be added to the given array. The number of arguments to this method depends upon the number of arrays or values to be merged.
Return value: This method returns a newly created array that is created after merging all the arrays passed to the method as arguments.
Below examples illustrate the JavaScript Array concat() method:
Example 1: In this example, the method concat() concatenates all the three arrays into one array which it return as the answer.var num1 = [11, 12, 13],
    num2 = [14, 15, 16],
    num3 = [17, 18, 19];
print(num1.concat(num2, num3));
Output:[11,12,13,14,15,16,17,18,19]

var num1 = [11, 12, 13],
    num2 = [14, 15, 16],
    num3 = [17, 18, 19];
print(num1.concat(num2, num3));

Output:
[11,12,13,14,15,16,17,18,19]

Example 2: In this example, the method concat() concatenates all the arguments passed to the method with the given array into one array which it return as the answer.var alpha = ['a', 'b', 'c'];
print(alpha.concat(1, [2, 3]));
Output:[a,b,c,1,2,3]

var alpha = ['a', 'b', 'c'];
print(alpha.concat(1, [2, 3]));

Output:
[a,b,c,1,2,3]

Example 3: In this example, the method concat() concatenates both the arrays into one array which it return as the answer.var num1 = [[23]];
var num2 = [89, [67]];
print(num1.concat(num2));
Output:[23,89,67] 

var num1 = [[23]];
var num2 = [89, [67]];
print(num1.concat(num2));

Output:
[23,89,67] 

More example codes for the above method are as follows:Program 1:
<script>    // JavaScript code for concat() method    function func() {        var alpha = ["a", "b", "c"];        document.write(alpha.concat(1, [2, 3]));    }    func();</script>
Output:
[a,b,c,1,2,3]
Program 2:
<script>    // JavaScript code for concat() method    function func() {        var num1 = [[23]];        var num2 = [89, [67]];        document.write(num1.concat(num2));    }    func();</script>
Output:
[23,89,67] 
Supported Browsers: The browsers supported by JavaScript Array concat() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 5.5 and above
Opera 4 and above
Safari 1 and above
arorakashish0911
ysachin2314
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Array push() Method

01 Nov, 2021
Below is the example of Array push() method.
Example:<script>     function func() {         var arr = ['GFG', 'gfg', 'g4g'];               // Pushing the element into the array         arr.push('GeeksforGeeks');                 document.write(arr);          }     func(); </script>                 
<script>     function func() {         var arr = ['GFG', 'gfg', 'g4g'];               // Pushing the element into the array         arr.push('GeeksforGeeks');                 document.write(arr);          }     func(); </script>                 
Output:GFG,gfg,g4g,GeeksforGeeks
GFG,gfg,g4g,GeeksforGeeks
The arr.push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array.
Syntax:
arr.push(element1, elements2 ....., elementN]])
Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.
Return value: This method returns the new length of the array after inserting the arguments into the array.
Below examples illustrate the JavaScript Array push() method:
Example 1: In this example the function push() adds the numbers to the end of the array.var arr = [34, 234, 567, 4];
print(arr.push(23,45,56));
print(arr);
Output:7
34,234,567,4,23,45,56

var arr = [34, 234, 567, 4];
print(arr.push(23,45,56));
print(arr);

Output:
7
34,234,567,4,23,45,56

Example 2: In this example the function push() adds the objects to the end of the array. 
var arr = [34, 234, 567, 4];
print(arr.push('jacob',true,23.45));
print(arr);
Output:7
34,234,567,4,jacob,true,23.45

 
var arr = [34, 234, 567, 4];
print(arr.push('jacob',true,23.45));
print(arr);

Output:
7
34,234,567,4,jacob,true,23.45

More example codes for the above method are as follows:
Program 1:
<script>function func() {      // Original array    var arr = [34, 234, 567, 4];      // Pushing the elements    document.write(arr.push(23,45,56));    document.write("<br>");    document.write(arr);}func();</script>
Output:
7
34,234,567,4,23,45,56

Program 2:
<script>function func() {      var arr = [34, 234, 567, 4];      document.write(arr.push('jacob',true,23.45));    document.write("<br>");    document.write(arr);}func();</script>
Output:
7
34,234,567,4,jacob,true,23.45

Supported Browsers: The browsers supported by JavaScript Array push() method are listed below:
Google Chrome 1.0 and above
Microsoft Edge 12 and above
Mozilla Firefox 1.0 and above
Safari 1 and above
Opera 4 and above
ysachin2314
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use JavaScript to hide a DIV when the user clicks outside of it?

To hide a div when the user clicks outside of it, try to run the following code
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         window.onload = function(){
            var hideMe = document.getElementById('hideMe');
            document.onclick = function(e){
               if(e.target.id !== 'hideMe'){
                  hideMe.style.display = 'none';
               }
            };
         };
      </script>
      <div id="hideMe">Click outside this div and hide it.</div>
   </body>
</html>
Boolean Indexing in Python

The Boolean values like True & false and 1&0 can be used as indexes in panda dataframe. They can help us filter out the required records. In the below exampels we will see different methods that can be used to carry out the Boolean indexing operations.
Let’s consider a data frame desciribing the data from a game. The various points scored on different days are mentioned in a dictionary. Then we can create an index on the dataframe using True and False as the indexing values. Then we can print the final dataframe.
 Live Demo
import pandas as pd
# dictionary
game = {'Day':["Monday","Tuesday","Wednesday","Thursday","Friday"], 'points':[31,24,16,11,22]}
df = pd.DataFrame(game,index=[True,False,True,False,True])
print(df)
Running the above code gives us the following result
               Day       points
True        Monday           31
False      Tuesday           24
True     Wednesday           16
False     Thursday           11
True        Friday           22
This function can be used to filter out records that has a specific Boolean value. In the below example we can see fetch only the records where the Boolean value is True.
 Live Demo
import pandas as pd
# dictionary
game = {'Day':["Monday","Tuesday","Wednesday","Thursday","Friday"], 'points':[31,24,16,11,22]}
df = pd.DataFrame(game,index=[True,False,True,False,True])
#print(df)
print(df.loc[True])
Running the above code gives us the following result
              Day           points
True       Monday       31
True    Wednesday       16
True       Friday       22
In this method we also use integers as Boolean values. So we change the True and False values in the dataframe to 1 and 0. Then use them to filter out the records.
 Live Demo
import pandas as pd
# dictionary
game = {'Day':["Monday","Tuesday","Wednesday","Thursday","Friday"], 'points':[31,24,16,11,22]}
df = pd.DataFrame(game,index=[1,1,0,0,1])
#print(df)
print(df.ix[0])
Running the above code gives us the following result:
        Day points
0 Wednesday     16
0 T hursday     11
Create a stacked bar plot in Matplotlib - GeeksforGeeks

17 Dec, 2020
In this article, we will learn how to Create a stacked bar plot in Matplotlib. Let’s discuss some concepts :
Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack.
A bar plot or bar graph may be a graph that represents the category of knowledge with rectangular bars with lengths and heights that’s proportional to the values which they represent. The bar plots are often plotted horizontally or vertically.
Stacked bar plots represent different groups on the highest of 1 another. The peak of the bar depends on the resulting height of the mixture of the results of the groups. It goes from rock bottom to the worth rather than going from zero to value.
Approach:
Import Library (Matplotlib)Import / create data.Plot the bars in the stack manner.
Import Library (Matplotlib)
Import / create data.
Plot the bars in the stack manner.
Example 1: (Simple stacked bar plot)
Python3
# importing packageimport matplotlib.pyplot as plt  # create datax = ['A', 'B', 'C', 'D']y1 = [10, 20, 10, 30]y2 = [20, 25, 15, 25]  # plot bars in stack mannerplt.bar(x, y1, color='r')plt.bar(x, y2, bottom=y1, color='b')plt.show()
Output :
Example 2: (Stacked bar chart with more than 2 data)
Python3
# importing packageimport matplotlib.pyplot as pltimport numpy as np  # create datax = ['A', 'B', 'C', 'D']y1 = np.array([10, 20, 10, 30])y2 = np.array([20, 25, 15, 25])y3 = np.array([12, 15, 19, 6])y4 = np.array([10, 29, 13, 19])  # plot bars in stack mannerplt.bar(x, y1, color='r')plt.bar(x, y2, bottom=y1, color='b')plt.bar(x, y3, bottom=y1+y2, color='y')plt.bar(x, y4, bottom=y1+y2+y3, color='g')plt.xlabel("Teams")plt.ylabel("Score")plt.legend(["Round 1", "Round 2", "Round 3", "Round 4"])plt.title("Scores by Teams in 4 Rounds")plt.show()
Output :
Example 3: (Stacked Bar chart using dataframe plot)
Python3
# importing packageimport matplotlib.pyplot as pltimport numpy as npimport pandas as pd  # create datadf = pd.DataFrame([['A', 10, 20, 10, 26], ['B', 20, 25, 15, 21], ['C', 12, 15, 19, 6],                   ['D', 10, 18, 11, 19]],                  columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])# view dataprint(df)  # plot data in stack manner of bar typedf.plot(x='Team', kind='bar', stacked=True,        title='Stacked Bar Graph by dataframe')
Output :
  Team  Round 1  Round 2  Round 3  Round 4
0    A       10       20       10       26
1    B       20       25       15       21
2    C       12       15       19        6
3    D       10       18       11       19
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Prime String in C++

In this problem, we are given a string. Our task is to print YES / NO based on is the sum of ASCII values of the characters of the string is prime or not.
ASCII values are character encodings
Prime number is a number that is divisible only by the number itself and 1.
Let’s take an example to understand the problem,
Input: string = “Hello”
Output:No
To solve this problem, we will have to find the sum of ASCII values of all characters of the string. And store the sum in a variable and then check if the sum is a prime number or not.
The code to show the implementation of our solution
 Live Demo
#include <iostream>
using namespace std;
bool CheckPrimeString(string str) {
   int len = str.length(), sum = 0;
   for (int i = 0; i < len; i++)
   sum += (int)str[i];
   if (sum<= 1)
      return false;
   if (sum <= 3)
      return true;
   if (sum % 2 == 0 || sum % 3 == 0)
      return false;
   for (int i = 5; i * i <= sum; i = i + 6)
      if (sum % i == 0 || sum % (i + 2) == 0)
   return false;
   return true;
}
int main() {
   string str = "Hello!";
   cout<<"The string '"<<str<<" ' is ";
   if (CheckPrimeString(str))
      cout<<"a prime String \n";
   else
      cout<<"not a prime String\n";
}
The string 'Hello! ' is not a prime String
Puppeteer - Capture Screenshot

We can capture screenshots while working on automation tests developed in Puppeteer using the screenshot method. A screenshot is generally captured if we encounter an application error, a failure in a test case, and so on.
The syntax to capture screenshot in Puppeteer is as follows −
await page.screenshot({
   path: 'tutorialspoint.png'
})

Here, the path where the screenshot is to be saved is passed as a parameter to the method. With this, only the viewable part of the web page shall be captured. To capture the full page screenshot, we have to pass another parameter called the fullPage and set its value to true.
The syntax is as follows −
await page.screenshot({
   path: 'tutorialspoint.png', fullPage: true
})

Let us capture the screenshot of the below page −
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −
Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).
The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.
Right-click on the folder where the node_modules folder is created, then click on the New file button.
Step 2 − Enter a filename, say testcase1.js.
Step 3 − Add the below code within the testcase1.js file created.
//adding Puppeteer library
const pt = require('puppeteer');
pt.launch().then(async browser => {
   //browser new page
   const p = await browser.newPage();
   //set viewpoint of browser page
   await p.setViewport({ width: 1000, height: 500 })
   //launch URL
   await p.goto('https://www.tutorialspoint.com/index.htm')
   //capture screenshot
   await p.screenshot({
      path: 'tutorialspoint.png'
   });
   //browser close
   await browser.close()
})
Step 4 − Execute the code with the command given below −
node <filename>

So in our example, we shall run the following command −
node testcase1.js

After the command has been successfully executed, a new file called the tutorialspoint.png gets created within the page directory. It contains the captured screenshot of the page launched in the browser.
 Print
 Add Notes
 Bookmark this page
Replace substring with another substring C++

Here we will see how to replace substring with another substring. It replaces the portion of the string that begins at character pos and spans len characters.
The structure of the replace function is like below:
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
The parameters are pos: It is an insertion point, str : It is a string object, len : It contains information about number of characters to erase.
Step 1: Get the main string, and the string which will be replaced. And the match string
Step 2: While the match string is present in the main string:
Step 2.1: Replace it with the given string.
Step 3: Return the modified string
 Live Demo
#include <iostream>
#include <string>
using namespace std;
int main () {
   string base = "this is a test string.";
   string str2 = "n example";
   string str3 = "sample phrase";
   string str4 = "useful.";
   string str = base;
   str.replace(9,5,str2);
   str.replace(19,6,str3,7,6);
   str.replace(8,10,"just a");
   str.replace(8,6,"a shorty",7);
   str.replace(22,1,3,'!');
   str.replace(str.begin(),str.end()-3,str3);
   str.replace(str.begin(),str.begin()+6,"replace");
   str.replace(str.begin()+8,str.begin()+14,"is coolness",7);
   str.replace(str.begin()+12,str.end()-4,4,'o');
   str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());
   cout << str << '\n';
   return 0;
}
replace is useful.
Priority Queue in C++ Standard Template Library (STL)

Priority queue is an abstract data type for storing a collection of prioritized elements that supports insertion and deletion of an element based upon their priorities, that is, the element with first priority can be removed at any time. The priority queue doesn’t stores elements in linear fashion with respect to their locations like in Stacks, Queues, List, etc. The priority queue ADT(abstract data type) stores elements based upon their priorities.
Priority Queue supports the following functions −
Size() − it is used to calculate the size of the priority queue as it returns the number of elements in it.
Empty() − it return true if the Priority Queue is empty and false otherwise
Insert(element) − used to insert the new element into a Priority Queue
Min() − it return the element with the smallest associated key value and display error message if Priority Queue is empty.
removeMin()− it removes the element referenced by the min() function.
Given below is a table that shows the effect of operations on a priority queue
Start
Step 1-> Declare function to display the elements in a Priority Queue
   void display(priority_queue <int> Pq)
   declare and set priority_queue <int> que = Pq
   Loop While (!que.empty())
      call que.top()
      call que.pop()
   End
Step 2-> In main()
Create object of priority_queue <int> Pq
   Call push() to insert element in a priority queue as Pq.push(1)
   Call display(Pq)
   Call to check the size of a priority queue Pq.size()
   Call to display the top element of a priority queue Pq.top()
   Call to remove the elements of a priority queue Pq.pop()
   Call display(Pq)
Stop
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
void display(priority_queue <int> Pq) {
   priority_queue <int> que = Pq;
   while (!que.empty()) {
      cout << '\t' << que.top();
      que.pop();
   }
   //cout << '\n';
}
int main () {
   priority_queue <int> Pq;
   Pq.push(1);
   Pq.push(3);
   Pq.push(5);
   Pq.push(7);
   Pq.push(9);
   cout << "The priority queue is : ";
   display(Pq);
   cout << "\nPrioriy queue size using size() : " << Pq.size();
   cout << "\nFirst element of priority queue using top(): " << Pq.top();
   cout << "\nremoving element using pop() : ";
   Pq.pop();
   display(Pq);
   return 0;
}
The priority queue is : 9 7 5 3 1
Prioriy queue size using size() : 5
First element of priority queue using top(): 9
removing element using pop() : 7 5 3 1
Python - Remove duplicate values from a Pandas DataFrame

To remove duplicate values from a Pandas DataFrame, use the drop_duplicates() method. At first, create a DataFrame with 3 columns −
dataFrame = pd.DataFrame({'Car': ['BMW', 'Mercedes', 'Lamborghini', 'BMW', 'Mercedes', 'Porsche'],'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Delhi', 'Hyderabad', 'Mumbai'],'UnitsSold': [95, 70, 80, 95, 70, 90]})
Remove duplicate values −
dataFrame = dataFrame.drop_duplicates()

Following is the complete code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame({'Car': ['BMW', 'Mercedes', 'Lamborghini', 'BMW', 'Mercedes', 'Porsche'],'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Delhi', 'Hyderabad', 'Mumbai'], 'UnitsSold': [95, 70, 80, 95, 70, 90]})

print"Dataframe...\n", dataFrame

# counting frequency of column Car
count = dataFrame['Car'].value_counts()
print"\nCount in column Car"
print(count)

# removing duplicates
dataFrame = dataFrame.drop_duplicates()
print"\nUpdated DataFrame after removing duplicates...\n",dataFrame

# counting frequency of column Car after removing duplicates
count = dataFrame['Car'].value_counts()
print"\nCount in column Car"
print(count)
This will produce the following output −
Dataframe...
           Car        Place   UnitsSold
0          BMW        Delhi         95
1     Mercedes    Hyderabad         70
2  Lamborghini   Chandigarh         80
3          BMW        Delhi         95
4     Mercedes    Hyderabad         70
5      Porsche       Mumbai         90

Count in column Car
BMW            2
Mercedes       2
Porsche        1
Lamborghini    1
Name: Car, dtype: int64

Updated DataFrame after removing duplicates...
           Car         Place   UnitsSold
0          BMW        Delhi         95
1     Mercedes    Hyderabad         70
2  Lamborghini   Chandigarh         80
5      Porsche       Mumbai         90

Count in column Car
BMW           1
Porsche       1
Lamborghini   1
Mercedes      1
Name: Car, dtype: int64
Executing C# code in Linux

The .NET centric applications are meant to windows operating system up till now, but now Microsoft has introduced a new cross-platform application called Mono which enables the execution of the application developed under the .NET platform in Linux environment by giving an impression in such a way that as if we are running Linux package rather than executing .exe file.
Mono is an open-source utility that allows the developer to execute .NET centric applications on other platforms such as Mac or Linux as it provides an installation package for Windows platform to compile and execute .NET assemblies on Windows OS without ever installing the Visual Studio IDE or .NET Framework SDK. Hence, we can build real-time, production-ready assemblies that use Windows Forms, LINQ, XML web services, ADO.NET and ASP.NET by taking advantage of existing core CLR namespaces under Mono. First, download the Mono binaries using the wget utility and execute these series of commands to configure it properly as;
wget --no-check-certificate https://raw.github.com/nathanb/iws- snippets/master/mono-install-scripts/ubuntu/install_mono-3.0.sh
chmod 755 install_mono-3.0.sh
./install_mono-3.0.sh
Apart from that, install the MCS package too alternatively, to compile the .NET binary as following;
root/kali:~/ sudo apt-get install mcs
The infrastructure of the Mono console application is almost similar to the traditional C#.NET console application. To develop the first Mono based console application (test.cs), open any code editor like VIM and type the following code.
using System;
namespace test {
   class test{
      public static void Main(string[] args) {
         System.Console.WriteLine("C# app Compiled on Kali Linux");
      }
   }      
}
Then, open the Terminal and hit the following commands to compile the code.
root/kali:~/ mcs test.cs
root/kali:~/ ls
test.cs test.exe
The aforesaid command will generate an executable file like windows. Now hit the ./test.exe or mono test.exe command to run the C# binary; Here, the screenshot summarized everything we have done so far.
How to handle EOFException in java?

While reading the contents of a file in certain scenarios the end of the file will be reached in such scenarios a EOFException is thrown.
Especially, this exception is thrown while reading data using the Input stream objects. In other scenarios a specific value will be thrown when the end of file reached.
Let us consider the DataInputStream class, it provides various methods such as readboolean(), readByte(), readChar() etc.. to read primitive values. While reading data from a file using these methods when the end of file is reached an EOFException is thrown.
import java.io.DataInputStream;
import java.io.FileInputStream;
public class EOFExample {
   public static void main(String[] args) throws Exception {
      //Reading from the above created file using readChar() method
      DataInputStream dis = new DataInputStream(new FileInputStream("D:\\data.txt"));
      while(true) {
         char ch;
         ch = dis.readChar();
         System.out.print(ch);
      }
   }
}
Hello how are youException in thread "main" java.io.EOFException
   at java.io.DataInputStream.readChar(Unknown Source)
   at SEPTEMBER.remaining.EOFExample.main(EOFExample.java:11)
You cannot read contents of a file without reaching end of the file using the DataInputStream class. If you want, you can use other sub classes of the InputStream interface.
In the following example we have rewritten the above program using FileInputStream class instead of DataInputStream to read data from a file.
 Live Demo
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String[] args) throws Exception {
      //Reading data from user
      byte[] buf = " Hello how are you".getBytes();
      //Writing it to a file using the DataOutputStream
      DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\data.txt"));
      for (byte b:buf) {
         dos.writeChar(b);
      }
      dos.flush();
      System.out.println("Data written successfully");
   }
}
Data written successfully
Following is another way to handle EOFException in Java −
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class HandlingEOF {
   public static void main(String[] args) throws Exception {
      DataInputStream dis = new DataInputStream(new FileInputStream("D:\\data.txt"));
      while(true) {
         char ch;
         try {
            ch = dis.readChar();
            System.out.print(ch);
         } catch (EOFException e) {
            System.out.println("");
            System.out.println("End of file reached");
            break;
         } catch (IOException e) {
         }
      }
   }
}
Hello how are you
End of file reached
TIKA - Extracting HTML Document

Given below is the program to extract content and metadata from an HTML document.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.html.HtmlParser;
import org.apache.tika.sax.BodyContentHandler;

import org.xml.sax.SAXException;

public class HtmlParse {

   public static void main(final String[] args) throws IOException,SAXException, TikaException {

      //detecting the file type
      BodyContentHandler handler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      FileInputStream inputstream = new FileInputStream(new File("example.html"));
      ParseContext pcontext = new ParseContext();
      
      //Html parser 
      HtmlParser htmlparser = new HtmlParser();
      htmlparser.parse(inputstream, handler, metadata,pcontext);
      System.out.println("Contents of the document:" + handler.toString());
      System.out.println("Metadata of the document:");
      String[] metadataNames = metadata.names();
      
      for(String name : metadataNames) {
         System.out.println(name + ":   " + metadata.get(name));  
      }
   }
}
Save the above code as HtmlParse.java, and compile it from the command prompt by using the following commands −
javac HtmlParse.java
java HtmlParse 

Given below is the snapshot of example.txt file.
The HTML document has the following properties−
If you execute the above program it will give you the following output.
Output −
Contents of the document:

	Name	                     Salary	    age
	Ramesh Raman	             50000	    20
	Shabbir Hussein	             70000          25
	Umesh Raman	             50000	    30
	Somesh	                     50000	    35

Metadata of the document:

title:   HTML Table Header
Content-Encoding:   windows-1252
Content-Type:   text/html; charset = windows-1252
dc:title:   HTML Table Header

 Print
 Add Notes
 Bookmark this page
Java - DataInputStream

The DataInputStream is used in the context of DataOutputStream and can be used to read primitives.
Following is the constructor to create an InputStream −
InputStream in = new DataInputStream(InputStream in);

Once you have DataInputStream object in hand, then there is a list of helper methods, which can be used to read the stream or to do other operations on the stream.
public final int read(byte[] r, int off, int len)throws IOException
Reads up to len bytes of data from the input stream into an array of bytes. Returns the total number of bytes read into the buffer otherwise -1 if it is end of file.
Public final int read(byte [] b)throws IOException
Reads some bytes from the inputstream an stores in to the byte array. Returns the total number of bytes read into the buffer otherwise -1 if it is end of file.
(a) public final Boolean readBooolean()throws IOException
(b) public final byte readByte()throws IOException
(c) public final short readShort()throws IOException
(d) public final Int readInt()throws IOException
These methods will read the bytes from the contained InputStream. Returns the next two bytes of the InputStream as the specific primitive type.
public String readLine() throws IOException
Reads the next line of text from the input stream. It reads successive bytes, converting each byte separately into a character, until it encounters a line terminator or end of file; the characters read are then returned as a String.
Following is an example to demonstrate DataInputStream and DataOutputStream. This example reads 5 lines given in a file test.txt and converts those lines into capital letters and finally copies them into another file test1.txt.
import java.io.*;
public class DataInput_Stream {

   public static void main(String args[])throws IOException {

      // writing string to a file encoded as modified UTF-8
      DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
      dataOut.writeUTF("hello");

      // Reading data from the same file
      DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));

      while(dataIn.available()>0) {
         String k = dataIn.readUTF();
         System.out.print(k+" ");
      }
   }
}
Following is the sample run of the above program −
hello


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python 3 - os.makedirs() Method

The method makedirs() is recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.
The default mode is 0o777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.
If exist_ok is False (the default), an OSError is raised if the target directory already exists.
Following is the syntax for makedirs() method −
os.makedirs(path[, mode])

path − This is the path, which needs to be created recursively.
path − This is the path, which needs to be created recursively.
mode − This is the Mode of the directories to be given.
mode − This is the Mode of the directories to be given.
This method does not return any value.
The following example shows the usage of makedirs() method.
#!/usr/bin/python3
import os, sys

# Path to be created
path = "d:/tmp/home/monthly/daily"

os.makedirs( path, 493 ) #decimal equivalent of 0755 used on Windows

print ("Path is created")
When we run the above program, it produces the following result −
Path is created


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k] in C++

With respect of a given array of positive integers of size n, our task to determine the maximum
sum of triplet ( ai + aj + ak ) such that 0 <= i < j < k < n and ai< aj< ak.
a[] = 3 6 4 2 5 10
19
All possible triplets are:-
3 4 5 => sum = 12
3 6 10 => sum = 19
3 4 10 => sum = 17
4 5 10 => sum = 19
2 5 10 => sum = 17
Maximum sum = 19
Now, a simple approach is to visit for every triplet with three nested ‘for loops’ and determine update the sum of all triplets one by one. Here, time complexity of this method is O(n^3) which is not enough for higher value of ‘n’.
Again, we can apply a better approach for making further optimization in above approach. In this method, instead of visiting through every triplet with three nested loops, we can visit through two nested loops.
At the time of visiting through each number(let as middle element(aj )), determine maximum number(ai) less than aj preceding it and maximum number(ak ) larger than aj beyond it. Finally, now, update the maximum answer with calculated sum of ai + aj + ak
 Live Demo
// C++ program to find maximum triplet sum
#include <bits/stdc++.h>
using namespace std;
// Shows function to calculate maximum triplet sum
int maxTripletSum(int arr1[], int n1){
   // Used to initialize the answer
   int ans1 = 0;
   for (int i = 1; i < n1 - 1; ++i) {
      int max1 = 0, max2 = 0;
      // Determine maximum value(less than arr1[i])
      // from i+1 to n1-1
      for (int j = 0; j < i; ++j)
         if (arr1[j] < arr1[i])
            max1 = max(max1, arr1[j]);
      // Determine maximum value(greater than arr1[i])
      // from i+1 to n1-1
      for (int j = i + 1; j < n1; ++j)
         if (arr1[j] > arr1[i])
            max2 = max(max2, arr1[j]);
      // store maximum answer
      if(max1 && max2)
         ans1=max(ans1,max1+arr1[i]+max2);
   }
   return ans1;
}
// Driver code
int main(){
   int Arr[] = { 3, 6, 4, 2, 5, 10 };
   int N = sizeof(Arr) / sizeof(Arr[0]);
   cout << maxTripletSum(Arr, N);
   return 0;
}
19