code-rag-bench/online-tutorials huggingface dataset:
Python String lstrip() Method

Python string  method lstrip() returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters).
Following is the syntax for lstrip() method −
str.lstrip([chars])

chars − You can supply what chars have to be trimmed.
chars − You can supply what chars have to be trimmed.
This method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters).
The following example shows the usage of lstrip() method.
#!/usr/bin/python

str = "     this is string example....wow!!!     ";
print str.lstrip()
str = "88888888this is string example....wow!!!8888888";
print str.lstrip('8')
When we run above program, it produces following result −
this is string example....wow!!!
this is string example....wow!!!8888888
Software Testing | Static Testing

13 May, 2019
Static Testing is a type of a Software Testing method which is performed to check the defects in software without actually executing the code of the software application. Whereas in Dynamic Testing checks the code is executed to detect the defects.
Static testing is performed in early stage of development to avoid errors as it is easier to find sources of failures and it can be fixed easily. The errors that can’t not be found using Dynamic Testing, can be easily found by Static Testing.
Static Testing Techniques:There are mainly two type techniques used in Static Testing:
1. Review:In static testing review is a process or technique that is performed to find the potential defects in the design of the software. It is process to detect and remove errors and defects in the different supporting documents like software requirements specifications. People examine the documents and sorted out errors, redundancies and ambiguities.Review is of four types:
Informal:In informal review the creator of the documents put the contents in front of audience and everyone gives their opinion and thus defects are identified in the early stage.
Walkthrough:It is basically performed by experienced person or expert to check the defects so that there might not be problem further in the development or testing phase.
Peer review:Peer review means checking documents of one-another to detect and fix the defects. It is basically done in a team of colleagues.
Inspection:Inspection is basically the verification of document the higher authority like the verification of software requirement specifications (SRS).
2. Static Analysis:Static Analysis includes the evaluation of the code quality that is written by developers. Different tools are used to do the analysis of the code and comparison of the same with the standard.It also helps in following identification of following defects:
(a) Unused variables
(b) Dead code
(c) Infinite loops
(d) Variable with undefined value
(e) Wrong syntax 
Static Analysis is of three types:
Data Flow:Data flow is related to the stream processing.
Control Flow:Control flow is basically how the statements or instructions are executed.
Cyclomatic Complexity:Cyclomatic complexity is the measurement of the complexity of the program that is basically related to the number of independent paths in the control flow graph of the program.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Print Left Triangle Star Pattern

06 Jun, 2022
In this article, we will learn about printing Left Triangle Star Pattern.
Examples:
Input : n = 5
Output: 
           * 
         * * 
       * * * 
     * * * * 
   * * * * * 
Left Triangle Star Pattern:
Java
import java.io.*; // java program for left trianglepublic class GFG {    // Function to demonstrate printing pattern    public static void StarleftTriangle(int k)    {        int a, b;         // 1st loop        for (a = 0; a < k; a++) {             // nested 2nd loop            for (b = 2 * (k - a); b >= 0; b--) {                // printing spaces                System.out.print(" ");            }             // nested 3rd loop            for (b = 0; b <= a; b++) {                // printing stars                System.out.print("* ");            }             // end-line            System.out.println();        }    }     // Driver Function    public static void main(String args[])    {        int k = 5;        StarleftTriangle(k);    }}
           * 
         * * 
       * * * 
     * * * * 
   * * * * * 
Time Complexity: O(k2), where k represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant.
tamanna17122007
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Split a list having single integer

28 Feb, 2019
Given a list containing single integer, the task is to split each value in the list.
Examples:
Input: Input = [23]
Output: Output  = [2, 3]

Input: Input = [15478]
Output: Output  = [1, 5, 4, 7, 8]

Method #1 : Using Map
# Python code to split list containing single integer  # List initializationinput = [200]  # Using mapoutput = list(map(int, str(input[0])))  # Printing outputprint(output)
[2, 0, 0]

 
Method #2 : Using list comprehension
# Python code to split list containing single integer  # List initializationinput = [231]  # Using list comprehensionoutput = [int(x) if x.isdigit() else x           for z in input for x in str(z)]  # Printing outputprint(output)
[2, 3, 1]

 Method #3 : Using Loops
# Python code to split list containing single integer  # List initializationinput = [987]  # Converting to intinput = int(input[0])  # Output list initializationoutput = []  while input>0:    rem = input % 10    input = int(input / 10)    output.append(rem)  # Printing outputprint(output)
[7, 8, 9]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Virtual Functions in Derived Classes in C++

16 May, 2022
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class’s version of the function.
In C++, once a member function is declared as a virtual function in a base class, it becomes virtual in every class derived from that base class. In other words, it is not necessary to use the keyword virtual in the derived class while declaring redefined versions of the virtual base class function.
For example, the following program prints “C::fun() called“ as “B::fun()“ becomes virtual automatically.
CPP
// C++ Program to demonstrate Virtual// functions in derived classes#include <iostream>using namespace std; class A {public:    virtual void fun() { cout << "\n A::fun() called "; }}; class B : public A {public:    void fun() { cout << "\n B::fun() called "; }}; class C : public B {public:    void fun() { cout << "\n C::fun() called "; }}; int main(){    // An object of class C    C c;       // A pointer of class B pointing    // to memory location of c    B* b = &c;       // this line prints "C::fun() called"    b->fun();       getchar(); // to get the next character    return 0;}
 C::fun() called 
Note: Never call a virtual function from a CONSTRUCTOR or DESTRUCTOR
anshikajain26
harsh_shokeen
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
vector erase() and clear() in C++
Substring in C++
C++ Classes and Objects
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
Pytest - Run Tests in Parallel

By default, pytest runs tests in sequential order. In a real scenario, a test suite will have a number of test files and each file will have a bunch of tests. This will lead to a large execution time. To overcome this, pytest provides us with an option to run tests in parallel.
For this, we need to first install the pytest-xdist plugin.
Install pytest-xdist by running the following command −
pip install pytest-xdist

Now, we can run tests by using the syntax pytest -n <num>
pytest -n 3

-n <num> runs the tests by using multiple workers, here it is 3.
We will not be having much time difference when there is only a few tests to run. However,
it matters when the test suite is large.
How to get integer values from a string in Python?

You can use regular expressions to get all integer values in order of their occurance in an array. You can use the following code to get those values -
import re
s = "12 hello 52 19 some random 15 number"
# Extract numbers and cast them to int
list_of_nums = map(int, re.findall('\d+', s))
print list_of_nums
[12, 52, 19, 15]
If you want to concatenate all numbers in one number and output that, then you can use str.isdigit method to filter them. For example,
>>> s = "12 hello 52 19 some random 15 number"
>>> print int(filter(str.isdigit, s))
12521915
What is an object in Python? Explain with examples

A python is an object-oriented programming language. Almost everything in Python is considered as an object. An object has its own properties(attributes) and behavior(methods).
A class is a blueprint of the objects or can be termed as object constructor for creating objects.
One class can have many objects and value of properties for different objects can be different.
Let’s take the example of car as an object. Its properties will include its color, company name, year of manufacture , price , mileage etc. The behavior of the car will include the functions it can perform, this will include increase speed, decrease speed, apply brakes etc. Object basically related everything with real life objects. Everything we find around us in real life has some properties and some functions.
Different objects belonging to same class can have different properties. For example, Person(Human) can be treated as a class which has properties such as name, age,gender etc. Every individual can be treated as an object of the class human or Person. Each individual will have different values of the properties of class Person.Everyone will have different names, age and gender.
An object is also called an instance of a class. Thus, the process of creating object of a class is known as instantiation.
As the function in Python is defined using the keyword ‘def’. The keyword ‘class’ is used to define a class in Python. Since the class is a blueprint of the object, all the common attributes and methods will be declared and defined in the class. Different objects which are created from the class can access those properties and functions. Different objects can hold their own values for properties defined inside the class.
Creating object of a class is simple. The name of the class must be known and object can be created as follows −
Object_name= class_name()
 Live Demo
class Person:
   name=""
   age=0
   city=""
   def display(self):
      print("Name : ",self.name)
      print("Age : ",self.age)
      print("City : ",self.city)

p1=Person()
p1.name="Rahul"
p1.age=20
p1.city="Kolkata"
p1.display()

print()

p2=Person()
p2.name="Karan"
p2.age=22
p2.city="Bangalore"
p2.display()

print()
p1.display()
In the above implementation, p1=Person() is the object instantiation. p1 is the name of the object . We accessed the properties of the class through object p1 and gave them different values and later called the display function to display values of this object.Later,we do the same for second object p2 and display properties of p2.
At the end, we again call display() for object p1 to show that each object holds its own value of properties and those are independent of the other objects.
Name : Rahul
Age : 20
City : Kolkata
Name : Karan
Age : 22
City : Bangalore
Name : Rahul
Age : 20
City : Kolkata
SQL – Logical Operators

18 Oct, 2021
SQL logical operators are used to test for the truth of the condition. A logical operator like the Comparison operator returns a boolean value of TRUE, FALSE, or UNKNOWN.
Given below is the list of logical operators available in SQL.
In the below example, we will see how this logical operator works.
Step 1: Creating a Database 
In order to create a database, we need to use the CREATE operator.
Query:
CREATE DATABASE xstream_db;
Step 2: Create table employee 
In this step, we will create the table employee inside the xstream_db database.
Query:
CREATE TABLE employee (emp_id INT, emp_name VARCHAR(255), 
                                  emp_city VARCHAR(255),
                                  emp_country VARCHAR(255),
                                  PRIMARY KEY (emp_id));
In order to insert the data inside the database, we need to use the INSERT operator.
Query:
INSERT INTO employee VALUES (101, 'Utkarsh Tripathi', 'Varanasi', 'India'),
                            (102, 'Abhinav Singh', 'Varanasi', 'India'), 
                            (103, 'Utkarsh Raghuvanshi', 'Varanasi', 'India'),
                            (104, 'Utkarsh Singh', 'Allahabad', 'India'),
                            (105, 'Sudhanshu Yadav', 'Allahabad', 'India'),
                            (106, 'Ashutosh Kumar', 'Patna', 'India');
Output: 
Now the given below is an example of the logical operators.
Query : 
SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country = 'India';
Output: 
Query:
SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');
Output: 
Query:
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output:
Query:
SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country = 'India';
Output:
Query:
SELECT * FROM employee WHERE emp_city LIKE 'P%';
Output:
Query:
SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;
Output:
Query:
SELECT * FROM employee WHERE emp_id = ALL 
                (SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
Output:
Query:
SELECT * FROM employee WHERE emp_id = ANY
                (SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');
Output:
Query:
SELECT emp_name FROM employee WHERE EXISTS
                (SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Output:
Query:
SELECT * FROM employee WHERE emp_id < SOME 
                (SELECT emp_id FROM employee WHERE emp_city = 'Patna');
Output:
Picked
sql-operators
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
Laplace Transform in MATLAB

21 Apr, 2021
In this article, we will see how to find Laplace Transform in MATLAB. Laplace Transform helps to simplify problems that involve Differential Equations into algebraic equations. As the name suggests, it transforms the time-domain function f(t) into Laplace domain function F(s).
 
Using the above function one can generate a Laplace Transform of any expression.
Example 1: Find the Laplace Transform of .
Matlab
% specify the variable a, t and s as symbolic ones % The syms function creates a variable dynamically % and automatically assigns to a MATLAB variable% with the same namesyms a t s  % define function f(t) f=cos(a*t);  % laplace command to transform into % Laplace domain function F(s)F=laplace(f,t,s);    % Display the output valuedisp('Laplace Transform of cos(at):')disp(F);
Output:
Example 2: Find the Laplace Transform of a particular expression i.e. 1+2e^{(-t)}+3e^{(-2t)}.
Matlab
% specify the variable a, t and s % as symbolic ones  syms a t s e  % define function f(t) f=1+2*exp(-t)+3*exp(-2*t);  % laplace command to transform into % Laplace domain function F(s)F=laplace(f,t,s);    % Display the output valuedisp('Laplace Transform of 1+2e^{(-t)}+3e^{(-2t)}:')disp(F);
Output: 
MATLAB-Maths
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Classes and Object in MATLAB
How to find inverse Laplace Transforms using MATLAB ?
2D Array Interpolation in MATLAB
Create Array of Zeros in MATLAB
Installing MATLAB on MacOS
Page-wise matrix multiplication in MATLAB
MATLAB - Trapezoidal numerical integration without using trapz
Mesh Surface Plot in MATLAB
How to run a node.js application permanently ?

03 Feb, 2021
NodeJS is a runtime environment on a V8 engine for executing JavaScript code with some additional functionality that allows the development of fast and scalable web applications but we can’t run the Node.js application locally after closing the terminal or Application, to run the nodeJS application permanently. We use  NPM modules such as forever or PM2 to ensure that a given script runs continuously. NPM is a Default Package manager for Node.js Which enables us to access a lot of packages or modules that make things a lot easier for developing a web application.
Method 1: 
Using PM2 module:
Installing module in project Directory:
npm install pm2 -g
Start Your Node.js Application by pm2.
pm2 start [Your fileName]
All processes listed up which are registered with pm2.
pm2 list
Console output:
We can also stop any process runs by pm2 stop command:
 pm2 stop all                  
 pm2 stop [id number]       
Method 2: 
Using forever module
Installing module in your project Directory:
npm install forever -g
Start Your Node.js Application by forever module. 
forever start [Your FileName]
All processes listed up which are registered with forever
forever list
Console output:
 We can also remove or stop any processes that are registered with forever using index (such as 0 in this case)              
forever stopall
forever stop [index]
So now your Application will be running permanently even after exiting the terminal or Application.
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
CSS | rgb() Function

04 Dec, 2018
The rgb() function is an inbuilt function in CSS which is used to define the colors using the Red Green Blue (RGB) model.
Syntax:
rgb( red, green, blue )
Parameters: This function accepts three parameters as mentioned above and described below:
red: This parameter is used to define the intensity of red color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%.
green: This parameter is used to define the intensity of green color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%.
blue: This parameter is used to define the intensity of blue color. It is an integer value lies between 0 to 255, or as a percentage value between 0% to 100%.
Below programs illustrates the rgb() function in CSS:
Program:
<!DOCTYPE html><html>    <head>        <title>rgb function</title>        <style>             .gfg1 {                background-color:rgb(1, 153, 0);                text-align:center;            }            .gfg2 {                background-color:rgb(0, 255, 0);                text-align:center            }            .gfg3 {                background-color:rgb(133, 150, 150);                text-align:center            }            .gfg {                font-size:40px;                font-weight:bold;                color:green;                text-align:center;            }            h1 {                text-align:center;            }        </style>    </head>    <body>        <div class = "gfg">GeeksforGeeks</div>        <h1>The rgb() Function</h1>        <p class = "gfg1">Green</p>        <p class = "gfg2">Light green</p>        <p class = "gfg3">Light black</p>    </body></html>                    
Output:
Supported Browsers: The browser supported by rgb() function are listed below:
Chrome 1.0 and above
Internet Explorer 4.0 and above
Firefox 1.0 and above
Safari 1.0 and above
Opera 3.5 and above
CSS-Functions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Python – Difference between json.dump() and json.dumps()

02 Jun, 2022
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. 
Note: For more information, refer to Working With JSON Data in Python
json.dumps() method can convert a Python object into a JSON string.
Syntax: json.dumps(dict, indent) 
Parameters:
dictionary – name of dictionary which should be converted to JSON object.
indent – defines the number of units for indentation
Example: 
Python3
# Python program to convert# Python to JSON        import json    # Data to be writtendictionary ={  "id": "04",  "name": "sunil",  "department": "HR"}    # Serializing json json_object = json.dumps(dictionary, indent = 4)print(json_object)
Output:
{
    "department": "HR",
    "id": "04",
    "name": "sunil"
}
Python objects and their equivalent conversion to JSON:
json.dump() method can be used for writing to JSON file.
Syntax: json.dump(dict, file_pointer) 
Parameters:
dictionary – name of dictionary which should be converted to JSON object.
file pointer – pointer of the file opened in write or append mode.
Example: 
Python3
# Python program to write JSON# to a file    import json  # Data to be writtendictionary ={    "name" : "sathiyajith",    "rollno" : 56,    "cgpa" : 8.6,    "phonenumber" : "9976770500"}  with open("sample.json", "w") as outfile:    json.dump(dictionary, outfile)
Output: 
Let us see the differences in a tabular form -:
Its syntax is -:
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Its syntax is -:
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) 
sagar0719kumar
prachisoda1234
mayank007rawa
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Program to check a number is power of two or not in Python

Suppose we have a number n. We have to check whether this is power of 2 or not.
So, if the input is like n = 2048, then the output will be True as 2048 is 2^11.
To solve this, we will follow these steps −
if n is same as 0, thenreturn False
if n is same as 0, then
return False
return False
return true when (n AND (n - 1)) is same as 0 otherwise false
return true when (n AND (n - 1)) is same as 0 otherwise false
Let us see the following implementation to get better understanding
def solve(n):
   if n == 0:
      return False
   return (n & (n - 1)) == 0

n = 2048
print(solve(n))
2048
True
Python | Pandas dataframe.cumprod()

16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.cumprod() is used to find the cumulative product of the values seen so far over any axis.Each cell is populated with the cumulative product of the values seen so far.
Syntax: DataFrame.cumprod(axis=None, skipna=True, *args, **kwargs)
Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns: cumprod : Series
Example #1: Use cumprod() function to find the cumulative product of the values seen so far along the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                   "B":[11, 2, 4, 3],                   "C":[4, 3, 8, 5],                    "D":[5, 4, 2, 8]})  # Print the dataframedf
Output :
Now find the cumulative product of the values seen so far over the index axis
# To find the cumulative proddf.cumprod(axis = 0)
Output :
 
Example #2: Use cumprod() function to find the cumulative product of the values seen so far along the column axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                    "B":[11, 2, 4, 3],                   "C":[4, 3, 8, 5],                    "D":[5, 4, 2, 8]})  # cumulative product along column axisdf.cumprod(axis = 1)
Output :
 
Example #3: Use cumprod() function to find the cumulative product of the values seen so far along the index axis in a data frame with NaN value present in dataframe.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, None, 4],                   "B":[None, 2, 4, 3],                    "C":[4, 3, 8, 5],                    "D":[5, 4, 2, None]})  # To find the cumulative productdf.cumprod(axis = 0, skipna = True)
Output :
The output is a dataframe with cells containing the cumulative product of the values seen so far along the index axis. Any Nan value in the dataframe is skipped.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
How to make a beep sound in JavaScript ?

13 Mar, 2020
A beep sound in a website can be used for the following tasks:
Alert notification
Make the website more interactive
There can be many more use cases of these sounds. It all depends on one’s creativity and needs. Usually, we create a function in Javascript and call that function whenever required. In this tutorial, we are using a button to play the “beep” sound using the onclick method.
Method 1: Use Audio function in Javascript to load the audio file.
<!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>    <h1>Press the Button</h1>      <button onclick="play()">Press Here!</button>      <script>        function play() {            var audio = new Audio('https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3');            audio.play();        }    </script></body></html>
Output:
Method 2: Use the audio tag in html and play it using Javascript.
<html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport"         content="width=device-width, initial-scale=1.0">    <title>Document</title></head>  <body>    <h1>Press the Button</h1>      <audio id="chatAudio" >        <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3"         type="audio/mpeg">    </audio>    <button onclick="play()">Press Here!</button>       <script>        var audio = document.getElementById('chatAudio');        function play(){            audio.play()        }    </script></body></html>
Output:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
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
PHP | preg_match() Function

27 Feb, 2019
This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search.
Syntax:
int preg_match( $pattern, $input, $matches, $flags, $offset )
Parameters: This function accepts five parameters as mentioned above and described below:
pattern: This parameter holds the pattern to search for, as a string.
input: This parameter holds the input string.
matches: If matches exists then it contains results of search. The $matches[0] will contain the text that matched full pattern, $matches[1] will contain the text that matched the first captured parenthesized subpattern, and so on.
flags: The flags can be following flags:PREG_OFFSET_CAPTURE: If this flag is passed, for every match the append string offset will be returned.PREG_UNMATCHED_AS_NULL: If this flag is passed, subpatterns which are not matched reports as NULL; otherwise they reports as empty string.
PREG_OFFSET_CAPTURE: If this flag is passed, for every match the append string offset will be returned.
PREG_UNMATCHED_AS_NULL: If this flag is passed, subpatterns which are not matched reports as NULL; otherwise they reports as empty string.
offset: Usually, search starts from the beginning of input string. This optional parameter offset is used to specify the place from where to start the search (in bytes).
Return value: It returns true if pattern exists, otherwise false.
Below examples illustrate the preg_match() function in PHP:
Example 1: This example accepts the PREG_OFFSET_CAPTURE flag.
<?php  // Declare a variable and initialize it$geeks = 'GeeksforGeeks';  // Use preg_match() function to check matchpreg_match('/(Geeks)(for)(Geeks)/', $geeks, $matches, PREG_OFFSET_CAPTURE);  // Display matches resultprint_r($matches);  ?>
Array
(
    [0] => Array
        (
            [0] => GeeksforGeeks
            [1] => 0
        )

    [1] => Array
        (
            [0] => Geeks
            [1] => 0
        )

    [2] => Array
        (
            [0] => for
            [1] => 5
        )

    [3] => Array
        (
            [0] => Geeks
            [1] => 8
        )

)

Example 2:
<?php  // Declare a variable and initialize it$gfg = "GFG is the best Platform.";  // case-Insensitive search for the word "GFG"if (preg_match("/\bGFG\b/i", $gfg, $match))     echo "Matched!";else    echo "not matched";      ?>
Matched!

Reference: http://php.net/manual/en/function.preg-match.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
How to get parameters from a URL string in PHP?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to remove the border of the legend of a chart created by plot function in R?

When we create a chart using plot function and add a legend to that chart, the output of the chart has the legend that is covered with borders. But this breaks the flow of the chart and the area covered by the order make the chart unattractive. Therefore, we can use bty="n" with the legend function and it will remove the border of the legend.
Creating the chart with legend that has border −
plot(x=1:10,y=10:1)
legend(1,2,"This is a scatterplot between x and y")
Creating the chart with legend which does not have a border −
plot(x=1:10,y=10:1)
legend(1,2,"This is a scatterplot between x and y",bty="n")
Python | Reverse Geocoding to get location on a map using geographic coordinates

12 Jul, 2021
Reverse geocoding is the process of finding a place or a location address from a given pair of geographic coordinates(latitude and longitude).Modules needed:  
reverse_geocoder: A Python library for offline reverse geocoding.
pprint: A module which helps to "pretty-print" any arbitrary python data structure.
Installation: The modules can be easily installed using pip.  
pip install reverse_geocoder
pip install pprint
Examples:  
Input : (36.778259, -119.417931)
Output : 
Loading formatted geocoded file...
[{'admin1': 'California',
  'admin2': 'Fresno County',
  'cc': 'US',
  'lat': '36.72384',
  'lon': '-119.45818',
  'name': 'Minkler'}]
Input : (28.644800, 77.216721)
Output : 
Loading formatted geocoded file...
[{'admin1': 'NCT',
  'admin2': 'New Delhi',
  'cc': 'IN',
  'lat': '28.63576',
  'lon': '77.22445',
  'name': 'New Delhi'}]
Below is the implementation: 
Python3
# Python3 program for reverse geocoding. # importing necessary librariesimport reverse_geocoder as rgimport pprint def reverseGeocode(coordinates):    result = rg.search(coordinates)         # result is a list containing ordered dictionary.    pprint.pprint(result) # Driver functionif __name__=="__main__":         # Coordinates tuple.Can contain more than one pair.    coordinates =(28.613939, 77.209023)         reverseGeocode(coordinates)
Output:  
Loading formatted geocoded file...
[{'admin1': 'NCT',
  'admin2': 'New Delhi',
  'cc': 'IN',
  'lat': '28.63576',
  'lon': '77.22445',
  'name': 'New Delhi'}]
References: https://pypi.org/project/reverse_geocoder/ https://www.latlong.net/ 
KrithikVaidya
surindertarika1234
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
numpy.ndarray.fill() in Python

28 Dec, 2018
numpy.ndarray.fill() method is used to fill the numpy array with a scalar value.
If we have to initialize a numpy array with an identical value then we use numpy.ndarray.fill(). Suppose we have to create a NumPy array a of length n, each element of which is v. Then we use this function as a.fill(v). We need not use loops to initialize an array if we are using this fill() function.
Syntax : ndarray.fill(value)
Parameters:value : All elements of a will be assigned this value.
Code #1:
# Python program explaining# numpy.ndarray.fill() functionimport numpy as geek  a = geek.empty([3, 3])  # Initializing each element of the array# with 1 by using nested loops for i in range(3):    for j in range(3):        a[i][j] = 1  print("a is : \n", a)        # now we are initializing each element# of the array with 1 using fill() function. a.fill(1)  print("\nAfter using fill() a is : \n", a)       
a is : 
 [[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

After using fill() a is : 
 [[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

 
Code #2:
# Python program explaining# numpy.ndarray.fill() functionimport numpy as geek  a = geek.arange(5)  print("a is \n", a)  # Using fill() methoda.fill(0)  print("\nNow a is :\n", a)       
a is 
 [0 1 2 3 4]

Now a is :
 [0 0 0 0 0]

 Code #3: numpy.ndarray.fill() also works on multidimensional array.
# Python program explaining# numpy.ndarray.fill() function  import numpy as geek  a = geek.empty([3, 3])  # Using fill() methoda.fill(0)  print("a is :\n", a)
a is :
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Speech Recognition in Hindi using Python

17 May, 2022
We can use Python for Speech Recognition, it is mostly used to recognize English words. However, in this article, we are going to use Python so that it can also recognize Hindi words with the help of the Speech Recognition module. 
Speech Recognition Module: It is a library with the help of which Python can recognize the command given. We have to use pip for Speech Recognition. 
pip install SpeechRecognition

PyAudio Module: It is a set of Python bindings for PortAudio, a cross-platform C++ library interfacing with audio drivers. We need to also install Pyaudio as the Speech Recognition module is dependent on it.
pip install PyAudio

If the above command doesn’t work in windows then use the below commands in the windows command prompt:
pip install pipwin
pipwin install pyaudio
We will use Google Speech Recognition API for letting the software understand Hindi. We will assign language as hn-IN.
Below is the complete Python program to take input commands in Hindi and to recognize them:
Python3
# import required moduleimport speech_recognition as sr      # explicit function to take input commands # and recognize themdef takeCommandHindi():             r = sr.Recognizer()    with sr.Microphone() as source:                  # seconds of non-speaking audio before         # a phrase is considered complete        print('Listening')        r.pause_threshold = 0.7          audio = r.listen(source)          try:            print("Recognizing")            Query = r.recognize_google(audio, language='hi-In')                          # for listening the command in indian english            print("the query is printed='", Query, "'")                  # handling the exception, so that assistant can         # ask for telling again the command        except Exception as e:            print(e)              print("Say that again sir")            return "None"        return Query      # Driver Code           # call the functiontakeCommandHindi()
Output:
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
uDork – Google Hacking Tool

23 Sep, 2021
Google Dorking is the technique used for advanced searching. Google Dorking can be beneficial in victim domain detection or collecting some sensitive data from the target domain, This can be done through automated tools which can decrease the time of old-fashioned searching. 
uDork is an automated tool developed in the Python language which performs an advanced search for relevant results on the target domain. This search can retrieve the links to admin panels that are not easily discovered, along with this we can get the sensitive files and directories and also the password files through advanced search. This tool contains various modules for dividing the task. uDork tool is available on the GitHub platform, it’s free and open-source to use.
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/m3n0sd0n4ld/uDork
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd uDork
Step 3: Change the permissions of install.sh file by using the following command.
sudo chmod +x uDork.sh
Step 4: Open the file and write inside this line:
mousepad uDork.sh
cookie = ‘YOUR FACEBOOK COOKIES HERE’
Step 5: Launching the tool by using the following command.
./uDork -h
Example 1: Example of searching pdf files
./uDork.sh geeksforgeeks.org -e pdf -p 3
We have got all the PDF files which are available on the http://geeksforgeeks.org domain.
Example 2: Example of searching routes with the word “password”
./uDork.sh geeksforgeeks.org -s password
We have got all the URLs that contain the term Password.
Example 3: Dorks listing
./uDork.sh -l
We are displaying the list of available dorks.
Example 4: Example of use Dorks Massive
./uDork.sh geeksforgeeks.org -g admin -p 3 -o report.txt
In this example, we auDork – Google Hacking Toolre using the admin dork file to get results.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
Basic Operators in Shell Scripting
current_window_handle driver method – Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around current_window_handle driver method in Selenium. current_window_handle method returns the handle of the current window.
Syntax –
driver.current_window_handle
Example –Now one can use current_window_handle method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.current_window_handle

To demonstrate, current_window_handle method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get current_window_handle,
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get current_window_handleprint(driver.current_window_handle)
Output –Screenshot added –
Terminal output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Simple POST request using the fetch API

25 May, 2020
The fetch() method, like the XMLHttpRequest and Axios request, is used to send the requests to the server. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API. You will get the whole Get and Post method using fetch API
Syntax:
fetch(url, { config }) 
.then(res => { 
    // Handle response 
}) 
.catch(err => { 
    // Handle errors 
}) 

fetch(url, { config }) 
.then(res => { 
    // Handle response 
}) 
.catch(err => { 
    // Handle errors 
}) 

Since fetch returns a Promise, we can also use async/await keywords to make requests:async () => {
  const resp = await fetch('http://example.com/example.json');
  // Handle response
}

async () => {
  const resp = await fetch('http://example.com/example.json');
  // Handle response
}

Create a POST request using fetch(): The POST request is widely used to submit forms to the server.
fetch(url, {    method: 'POST',    headers: {      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"    },    credentials: 'include',    body: 'foo=bar&lorem=ipsum'  })  .then(res.json())  .then(res => {    // Handle response     console.log('Response: ', res);  })  .catch(err => {    // Handle error     console.log('Error message: ', error);  });
Explanation:
To create a POST request we need to specify some parameters with the request such as method, headers, etc. First, we need to specify the request method (GET, POST, DELETE, etc.) which is POST in our case. This is followed by the Content-type, which tells the client what the content type of the returned data actually is. The credentials key is optional and should be used if you want to make a fetch request with credentials such as cookies. Then we set the body which consists of the data we wish to pass to the server.
The response of a fetch() request is a stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.
If the API returns a status of 201 (the HTTP status code for Created), the data returned by the API can be accessed- res(response). In case an error occurs, the code inside the catch block will be executed.
Picked
Web Technologies
Web technologies Questions
Write From Home
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
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Remove elements from a JavaScript Array
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
File uploading in React.js
How to Open URL in New Tab using JavaScript ?