code-rag-bench/online-tutorials huggingface dataset:
Scraping websites with Newspaper3k in Python - GeeksforGeeks

23 Jan, 2022
Web Scraping is a powerful tool to gather information from a website. To scrape multiple URLs, we can use a Python library called Newspaper3k. The Newspaper3k package is a Python library used for Web Scraping articles, It is built on top of requests and for parsing lxml. This module is a modified and better version of the Newspaper module which is also used for the same purpose.
To install this module type the below command in the terminal.
pip install newspaper3k
First we will define a list containing the URLs or assign a single URL.We will create an Article object passing in the parameters such as the name of the URL and optional parameters     like language=’en’, for EnglishWe will then download and parse the file.Finally, display the data extracted.
First we will define a list containing the URLs or assign a single URL.
We will create an Article object passing in the parameters such as the name of the URL and optional parameters     like language=’en’, for English
We will then download and parse the file.
Finally, display the data extracted.
Below are some examples based on the above approach:
Example 1
Below is a program to scrap data from a given URL.
Python3
# Import required moduleimport newspaper # Assign urlurl = 'https://www.geeksforgeeks.org/top-5-open-source-online-machine-learning-environments/' # Extract web dataurl_i = newspaper.Article(url="%s" % (url), language='en')url_i.download()url_i.parse() # Display scrapped dataprint(url_i.text)
Output:
Example 2
Here, we scrap data from multiple URLs and then display it.
Python3
# Import required modulesimport newspaper # Define list of urlslist_of_urls = ['https://www.geeksforgeeks.org/how-to-get-the-magnitude-of-a-vector-in-numpy/',                'https://www.geeksforgeeks.org/3d-wireframe-plotting-in-python-using-matplotlib/',                'https://www.geeksforgeeks.org/difference-between-small-data-and-big-data/'] # Parse through each url and display its contentfor url in list_of_urls:    url_i = newspaper.Article(url="%s" % (url), language='en')    url_i.download()    url_i.parse()    print(url_i.text)
Output:
abhishek0719kadiyan
sumitgumber28
Python web-scraping-exercises
python-modules
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
How to Install and Use Htop on Linux? - GeeksforGeeks

09 Apr, 2021
For Linux systems, Htop is an interactive system control, process viewer, and process manager. It was created as a replacement for the Linux program top, and it has a lot of the same features as the top, but with a lot more flexibility in terms of how system processes can be interpreted. Unlike top, htop displays the entire list of running processes rather than just the most resource-intensive ones. Htop can view processes as a tree and provides resource-usage statistics using color.
First, update your system sources:
$ sudo apt install htop
Updating system source
Now, install htop using the below command:
$ sudo apt-get install -y htop
Installing htop
We’ll need ncurses, as well as development tools/build necessary, to compile htop from the source. The steps for downloading htop from the source are as follows.
Install development tools using the below command:
$ sudo apt-get install build-essential
Installing development tools
Installing ncurses:
$ sudo apt-get install libncurses5-dev libncursesw5-dev
Installing ncurses
Now download htop from the source using wget:
$ wget http://hisham.hm/htop/releases/2.2.0/htop-2.2.0.tar.gz
Downloading htop
Extract tar:
$ tar xvfvz htop-2.2.0.tar.gz
Extract tar
Change directory to htop:
$ cd htop-2.2.0/
Change directory to htop
Now run the configure:
$ ./configure
Running the configure file
Now make a script:
$ make
Making script
Now we can install htop:
$ make install
Installing htop
Now you can open htop by simply typing:
$ htop
htop
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Install Selenium on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Check the OS Version in Linux?
AWK command in Unix/Linux with examples
Sed Command in Linux/Unix with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C
Concatenated string with uncommon characters in Python?

Here two strings are given, first we have to remove all the common element from the first string and uncommon characters of the second string have to be concatenated with uncommon element of first string.
Input >> first string::AABCD
Second string:: MNAABP
Output >> CDMNP

Uncommonstring(s1,s2)
/* s1 and s2 are two string */
Step 1: Convert both string into set st1 and st2.
Step 2: use the intersection of two sets and get common characters.
Step 3: now separate out characters in each string which are not common in both string.
Step 4: join each character without space to get a final string.

# Concatination of two uncommon strings 
def uncommonstring(s1, s2):
# convert both strings into set
   st1 = set(s1)
   st2 = set(s2)
   # take intersection of two sets to get list of common characters 
   lst = list(st1 & st2)
   finallist = [i for i in s1 if i not in lst] + \ [i for i in s2 if i not in lst]
   print("CONCATENATED STRING IS :::", ''.join(finallist))
# Driver program
if __name__ == "__main__":
   s1 =input("Enter the String ::")
   s2=input("Enter the String ::")
   uncommonstring(s1,s2)
Enter the String ::abcde
Enter the String ::bdkl
CONCATEATED STRINGIS ::: acekl
How to generate PDF file using PHP ? - GeeksforGeeks

02 Jul, 2021
In this article, we will learn how to generate PDF files with PHP by using FPDF. It is a free PHP class that contains many functions for creating and modifying PDFs. The FPDF class includes many features like page formats, page headers, footers, automatic page break, line break, image support, colors, links, and many more.
Approach:
You need to download the FPDF class from the FPDF website and include it in your PHP script.
require('fpdf/fpdf.php');
Instantiate and use the FPDF class according to your need as shown in the following examples.
$pdf=new FPDF();
Example 1: The following example generates a PDF file with the given text in the code. The file can be downloaded or previewed as needed.
PHP
<?php    ob_end_clean();require('fpdf/fpdf.php');  // Instantiate and use the FPDF class $pdf = new FPDF();  //Add a new page$pdf->AddPage();  // Set the font for the text$pdf->SetFont('Arial', 'B', 18);  // Prints a cell with given text $pdf->Cell(60,20,'Hello GeeksforGeeks!');  // return the generated output$pdf->Output();  ?>
 
Output:
Example 2: The following example helps in understanding the setting of the page header and footer along with printing many lines on different pages of PDF files.
PHP
<?php  require('fpdf/fpdf.php');  class PDF extends FPDF {      // Page header    function Header() {                  // Add logo to page        $this->Image('gfg1.png',10,8,33);                  // Set font family to Arial bold         $this->SetFont('Arial','B',20);                  // Move to the right        $this->Cell(80);                  // Header        $this->Cell(50,10,'Heading',1,0,'C');                  // Line break        $this->Ln(20);    }      // Page footer    function Footer() {                  // Position at 1.5 cm from bottom        $this->SetY(-15);                  // Arial italic 8        $this->SetFont('Arial','I',8);                  // Page number        $this->Cell(0,10,'Page ' .             $this->PageNo() . '/{nb}',0,0,'C');    }}  // Instantiation of FPDF class$pdf = new PDF();  // Define alias for number of pages$pdf->AliasNbPages();$pdf->AddPage();$pdf->SetFont('Times','',14);  for($i = 1; $i <= 30; $i++)    $pdf->Cell(0, 10, 'line number '             . $i, 0, 1);$pdf->Output();  ?>
Output:
PHP-function
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP Database connection
How to pass a PHP array to a JavaScript function?
String comparison using == vs strcmp() in PHP
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Installation of Node.js on Linux
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
jQuery keypress() with Examples

The keypress method in jQuery is used to trigger the keypress event. It occurs when a keyboard key is pressed down.
The syntax is as follows −
$(selector).keypress(func)
Let us now see an example to implement the jQuery keypress() method−
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   count = 0;
   $(document).ready(function(){
      $("input").keypress(function(){
         $("span").text(count += 1);
      });
      $("input").keyup(function(){
         $("input").css("color", "blue");
      });
   });
</script>
</style>
</head>
<body>
<h2>Registeration</h2>
<p>Enter username of the student:</p>
Username: <input type="text"><br><br>
Key is pressed <span> 0 </span>times.
</body>
</html>
This will produce the following output−
Now, when the key is pressed, the count of the number of keys appeared−
Import and Merge Multiple CSV Files in R - GeeksforGeeks

17 Jun, 2021
In this article, we will be looking at the approach to merge multiple CSV files in the R programming language.
dplyr: This is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles.
plyr: plyr is an R package that makes it simple to split data apart, do stuff to it, and mash it back together.
readr: This provides a fast and friendly way to read rectangular data (like ‘csv’, ‘tsv’, and ‘fwf’).
list.files() function: This function produces a character vector of the names of files or directories in the named directory.
Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
lapply() function: This function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.
Syntax: lapply(X, FUN, ...)
bind_rows() function: This function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one.
Syntax:
bind_rows(..., .id = NULL)
Parameter:
...: Data frames to combine.
.id: Data frame identifier.
To merge multiple CSV files, the user needs to install and import dplyr,plyr, and readr packages in the R console to call the functions which are list.files(), lapply(), and bind_rows() from these packages and pass the required parameters to these functions to merge the given multiple CSV files to a single data frame in the R programming language.
Data in Use:
Example:
R
library("dplyr")                                                library("plyr")                                               library("readr")    gfg_data <- list.files(path = "C:/Users/Geetansh Sahni/Documents/R/Data",                       pattern = "*.csv", full.names = TRUE) %>% lapply(read_csv) %>%                                           bind_rows                                                        gfg_data
 Output:
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ?
How to disable ONLY_FULL_GROUP_BY in MySQL?

You can enable ONLY_FULL_GROUP_BY in MySQL as shown in the following query −
mysql> SET sql_mode = 'ONLY_FULL_GROUP_BY';
Query OK, 0 rows affected (0.01 sec)
As shown above, we can enable ONLY_FULL_GROUP_BY with the help of SET command.
To disable ONLY_FULL_GROUP_BY with the help of the following query −
mysql> SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
Query OK, 0 rows affected (0.04 sec)
We have disabled ONLY_FULL_GROUP_BY successfully.
Min Stack in Python

Here we will see how to make a stack, that can perform push, pop, top, and retrieve the min element in constant time. So the functions will be push(x), pop(), top() and getMin()
To solve this, we will follow these steps −
Initialize the stack by min element as infinity
For push operation push(x)if x < min, then update min := x,push x into stack
if x < min, then update min := x,
push x into stack
For pop operation pop()t := top elementdelete t from stackif t is min, then min := top element of the stack
t := top element
delete t from stack
if t is min, then min := top element of the stack
For top operation top()simply return the top element
simply return the top element
for getMin operation getMin()return the min element
return the min element
Let us see the following implementation to get better understanding −
class MinStack(object):
   min=float('inf')
   def __init__(self):
      self.min=float('inf')
      self.stack = []
   def push(self, x):
      if x<=self.min:
         self.stack.append(self.min)
         self.min = x
      self.stack.append(x)
   def pop(self):
      t = self.stack[-1]
      self.stack.pop()
      if self.min == t:
         self.min = self.stack[-1]
         self.stack.pop()
   def top(self):
      return self.stack[-1]
   def getMin(self):
      return self.min
m = MinStack()
m.push(-2)
m.push(0)
m.push(-3)
print(m.getMin())
m.pop()
print(m.top())
print(m.getMin())
m = MinStack()
m.push(-2)
m.push(0)
m.push(-3)
print(m.getMin())
m.pop()
print(m.top())
print(m.getMin())
-3
0
-2
How to write a jQuery selector for the label of a checkbox?

To write a jQuery selector for the label of a checkbox, use the for attribute of label element.
You can try to run the following code to learn how to write a jQuery selector for the label of a checkbox:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

   $("label[for='mysubjects1']").css("background-color", "yellow");
   $("label[for='mysubjects2']").css("background-color", "gray");

});
</script>
</head>
<body>
<form>
  <input type="checkbox" name="filter" id="sub1"/>
  <label for="mysubjects1">Subjects</label><br>
  <input type="checkbox" name="filter2" id="sub2"/>
  <label for="mysubjects2">New Subjects</label>
</form>

</body>
</html>
DATE_ADD() Function in MySQL - GeeksforGeeks

25 Nov, 2020
DATE_ADD() function in MySQL is used to add a specified time or date interval to a specified date and then return the date.
Syntax:
DATE_ADD(date, INTERVAL value addunit)


Parameter: This function accepts two parameters which are illustrated below:
date –Specified date to be modified.
value addunit –Here the value is the date or time interval to add. This value can be both positive and negative. And here the addunit is the type of interval to add such as SECOND, MINUTE, HOUR, DAY, YEAR, MONTH, etc.
Returns :
It returns the new date after the addition of a specified time or date.
Example 1:
Getting a new date of “2020-11-22” after the addition of 3 years to the specified date “2017-11-22”.
SELECT DATE_ADD("2017-11-22", INTERVAL 3 YEAR);


Output:
2020-11-22


Example 2:
Getting a new date of “2020-11-22” after the addition of 2 months to the specified date “2020-9-22”.
SELECT DATE_ADD("2020-9-22", INTERVAL 2 MONTH);


Output:
2020-11-22


Example 3:
Getting a new date of “2020-11-22” after the addition of 10 days to the specified date “2020-11-12”.
SELECT DATE_ADD("2020-11-12", INTERVAL 10 DAY);


Output:
2020-11-22


Example 4:
Getting a new date of “2020-11-22 09:12:10” after the addition of 3 hours to the specified date “2020-11-22 06:12:10”.
SELECT DATE_ADD("2020-11-22 06:12:10", INTERVAL 3 HOUR);


Output:
2020-11-22 09:12:10


Example 5:
Getting a new date of “2020-11-22 09:09:10” after the addition of 3 minutes to the specified date “2020-11-22 09:06:10”.
SELECT DATE_ADD("2020-11-22 09:06:10", INTERVAL 3 MINUTE);


Output:
2020-11-22 09:09:10


Example 6:
Getting a new date of “2020-11-22 09:09:10” after the addition of 5 seconds to the specified date “2020-11-22 09:09:5”.
SELECT DATE_ADD("2020-11-22 09:09:5", INTERVAL 5 SECOND);


Output:
2020-11-22 09:09:10


mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL - ORDER BY
SQL using Python
MySQL | Regular expressions (Regexp)
Python Number cos() Method

Python number  method cos() returns the cosine of x radians.
Following is the syntax for cos() method −
cos(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
x − This must be a numeric value.
This method returns a numeric value between -1 and 1, which represents the cosine of the angle.
The following example shows the usage of cos() method.
#!/usr/bin/python
import math

print "cos(3) : ",  math.cos(3)
print "cos(-3) : ",  math.cos(-3)
print "cos(0) : ",  math.cos(0)
print "cos(math.pi) : ",  math.cos(math.pi)
print "cos(2*math.pi) : ",  math.cos(2*math.pi)
When we run above program, it produces following result −
cos(3) :  -0.9899924966
cos(-3) :  -0.9899924966
cos(0) :  1.0
cos(math.pi) :  -1.0
cos(2*math.pi) :  1.0
Python program to calculate BMI(Body Mass Index) of your Body

We have to enter our height and weight. Our task is to calculate BMI using formula.
Step 1: input height and weight of your body.
Step 2: then applying the formula for calculation BMI.
Step 3: display BMI.

height = float(input("Enter your height(m): "))
weight = float(input("Enter your weight(kg): "))
print("Your BMI is: ", round(weight / (height * height), 2))
Enter your height (m): 5.8
Input your weight (kg): 64
Your body mass index is:  1.9
Thread joinable() function in C++

26 Oct, 2018
Thread::joinable is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output and checks whether the thread object is joinable or not.
A thread object is said to be joinable if it identifies/represent an active thread of execution.
A thread is not joinable if:
It was default-constructed
If either of its member join or detach has been called
It has been moved elsewhere
Syntax:
std::thread::joinable()

Parameters: This function does not accepts any parameters.
Return Value: It is a boolean type function and returns true when the thread object isjoinable. It returns false if the thread object is not joinable.
The following program demonstrate the use of std::thread::joinable()
Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”.
// C++ program to demonstrate the use of// std::thread::joinable()  #include <chrono>#include <iostream>#include <thread>  using namespace std;  // function to put thread to sleepvoid threadFunc(){    std::this_thread::sleep_for(        std::chrono::seconds(1));}  int main(){    std::thread t1; // declaring the thread      cout << "t1 joinable when default created? \n";    // checking if it is joinable    if (t1.joinable())        cout << "YES\n";    else        cout << "NO\n";      // calling the function threadFunc    // to put thread to sleep    t1 = std::thread(threadFunc);      cout << "t1 joinable when put to sleep? \n";      // checking if t1 is joinable    if (t1.joinable())        cout << "YES\n";    else        cout << "NO\n";      // joining t1    t1.join();      // checking joinablity of t1 after calling join()    cout << "t1 joinable after join is called? \n";    if (t1.joinable())        cout << "YES\n";    else        cout << "NO\n";      return 0;}
Output:
t1 joinable when default created? 
NO
t1 joinable when put to sleep? 
YES
t1 joinable after join is called? 
NO

Note: The third output will appear 1 sec later because the thread was put to sleep for 1 minute.
CPP-Library
cpp-multithreading
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining
Python | Pandas Series.is_unique

28 Jan, 2019
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 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.is_unique attribute return a boolean value. It returns True if the data in the given Series object is unique else it return False.
Syntax:Series.is_unique
Parameter : None
Returns : boolean
Example #1: Use Series.is_unique attribute to check if the underlying data in the given Series object is unique or not.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Chicago'])  # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # Print the seriesprint(sr)
Output :
Now we will use Series.is_unique attribute to check if the underlying data in the given Series object is unique or it contains some duplicated value.
# check if underlying data is# is unique or notsr.is_unique
Output :
As we can see in the output, the Series.is_unique attribute has returned False indicating the underlying in the given series object is not unique. Example #2 : Use Series.is_unique attribute to check if the underlying data in the given Series object is unique or not.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018'])  # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4']  # Print the seriesprint(sr)
Output :
Now we will use Series.is_unique attribute to check if the underlying data in the given Series object is unique or it contains some duplicated value.
# check if underlying data is# is unique or notsr.is_unique
Output :As we can see in the output, the Series.is_unique attribute has returned True indicating the underlying in the given series object is unique.
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.
Getting the current date and time with timestamp in local and other timezones in Golang

22 Jun, 2020
We can get the current date and time with a timestamp in local with the help of Location() function and other timezones in Golang with the help of LoadLocation() function. The LoadLocation() takes a string(city name) as parameter and returns the place..location() takes no parameter and return location .time.now() returns current date and time with a timestamp in local.
1. location(): It takes no parameter and returns local time.
2. func LoadLocation(name string) (*Location, error): It takes the place name as a parameter. Returns the location with the given name or return nil as an error.
3. time.Now() : It return current time.
Example 1:
package main  import (    "fmt"    "time")  //main functionfunc main() {      // with the help of time.Now()    // store the local time    t := time.Now()          // print location and local time    fmt.Println("Location : ", t.Location(), " Time : ", t)}
Output:
Location :  Local  Time :  2009-11-10 23:00:00 +0000 UTC m=+0.000000001

Example 2:
package main  import (    "fmt"    "time")  // main functionfunc main() {      // with the help of time.Now()     // store the local time    t := time.Now()          // print location and local time    location, err := time.LoadLocation("America/New_York")    if err != nil {        fmt.Println(err)    }          // America/New_York    fmt.Println("Location : ", location, " Time : ", t.In(location)) }
Output:
Location :  America/New_York  Time :  2009-11-10 18:00:00 -0500 EST

GoLang-time
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
strings.Replace() Function in Golang With Examples
How to convert a string in lower case in Golang?
How to Sort Golang Map By Keys or Values?
Different Ways to Find the Type of Variable in Golang
Anonymous function in Go Language
Strings in Golang
Golang Maps
How to Trim a String in Golang?
Nested Structure in Golang
Python – Regex Lookbehind

24 Feb, 2021
Regex Lookbehind is used as an assertion in Python regular expressions(re) to determine success or failure whether the pattern is behind i.e to the right of the parser’s current position. They don’t match anything. Hence, Regex Lookbehind and lookahead are termed as a zero-width assertion.
Syntax:
# Positive lookbehind
(?<=<lookbehind_regex>)

# Positive lookahead
(?=<lookahead_regex>)
In this post we will talk about regex lookbehind.
Example 1:
Python3
# importing regeximport re  # Regex Lookbehind exampleexample = re.search(r'(?<=geeks)\w',                     'geeksforgeeks')  print(example.group())print("Pattern found from index",       example.start(), example.end())
Output:
f
Pattern found from index 5 6
The regex lookbehind assertion (?<=geeks) specifies that what precedes before any word character(‘\w’) must be ‘geeks’ string. In this case, it’s the character ‘f’ before which ‘geeks’ string occurs.
Example 2:
Python3
# importing regeximport re  # Regex Lookbehind exampleexample = re.search(r'(?<=geeks)\d',                     'geeksforgeeks')print(example)
Output:
None
In the above example, the output is None because there is no decimal digit preceded by ‘geeks’ string.
Lookbehind portion is not part of the search string. They are important when you don’t want the output to return lookbehind portion present in search string but want to use it to match pattern which is preceded by a particular section. Below example will make this clear:
Example 3:
Python3
import re  # Using lookbehindexample1 = re.search(r'(?<=[a-z])\d',                     "geeks12")print(example1.group())  # Without using lookbehindexample2 = re.search(r'([a-z])\d',                     "geeks12")print(example2.group())
Output:
1
s1
Using lookbehind the output generated is ‘1’ whereas without using lookbehind the output generated is ‘s1’.  Any word character (\w) which precedes any decimal digit is consumed by regex so it doesn’t become part of the search string. 
Negative Lookbehind
Negative Lookbehind is the opposite of lookbehind. It is to assure that the search string is not preceded by <lookbehind_regex>.
Syntax:
(?<!<lookbehind_regex>) 
Negative Lookbehind
Example 4:
Python3
import re  # Lookbehindexample1 = re.search('(?<=[a-z])geeks',                      'geeksforgeeks')print(example1.group())  # Negative Lookbehindexample2 = re.search('(?<![a-z])123',                      'geeks123')  # Output is None because 123 # is preceded by a character i.e 's'print(example2)
Output:
geeks
None
python-regex
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
HTML <Textarea>maxlength attribute

09 Jan, 2020
The HTML <Textarea>maxlength attribute is used to specify the maximum number of characters enters into the Textarea element.
Syntax:
<Textarea maxlength ="number">
Attribute Value:
Example:
<!DOCTYPE html> <html>   <head>     <title>Textarea maxlength Attribute</title>     <style>     }     fieldset {         width: 50%;         margin-left: 22%;     }     h1 {         color: green;     }     </style> </head>   <body>     <center>         <h1>GeeksforGeeks</h1>         <h2>Textarea maxlength Attribute</h2>         <textarea form="mygeeks"  maxlength="9">         </textarea>         <br>         <form id="mygeeks">             Name:             <input type="text" name="usrname">             <input type="submit">         </form>     </center> </body>   </html> 
Output:
Supported Browsers: The browsers supported by HTML <Textarea>maxlength attribute are listed below:
Google Chrome
Internet Explorer 10.0 +
Firefox 4.0
Opera 15.0
Safari
HTML-Attributes
HTML-Basics
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL – Size of value

28 Aug, 2020
The size of a value means the space needed to store a specific value in the database table.In this article we will look into function that is used to get the size of the PostgreSQL database value.The pg_column_size() function is used to get the size of a value.
Syntax: select pg_column_size(no. of values :: type of value)
Here we will be using a sample database for reference which is described here and can be downloaded from hereExample 1:Here we will query for space required to store 10 values of smallint type using the below command:
select pg_column_size(10::smallint);
Output:
Example 2:Here we will query for space required to store 10 values of int type using the below command:
select pg_column_size(10::int);
Output:
Example 3:Here we will query for space required to store 10 values of bigint type using the below command:
select pg_column_size(10::bigint);
Output:
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - INSERT
PostgreSQL - SELECT
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL- LOWER function
PostgreSQL - EXISTS Operator
PostgreSQL - BIGINT Integer Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Select Into
PostgreSQL - LAST_VALUE Function
PostgreSQL - DROP INDEX
MySQL Tryit Editor v1.0

SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Create multiple buttons with "different" command function in Tkinter

A Button can be initialized using the for loop in a Tkinter application. Let us suppose that we want to create multiple buttons, each with different commands or operations defined in it. We have to first initialize the Button inside a for loop. The iterator will return the object for which multiple instances of the button will be created.
In this example, we will define some buttons that will have different commands or functionalities.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of the Tkinter frame
win.geometry("750x250")

#Define a function to update the entry widget
def entry_update(text):
   entry.delete(0,END)
   entry.insert(0,text)

#Create an Entry Widget
entry= Entry(win, width= 30, bg= "white")
entry.pack(pady=10)

#Create Multiple Buttons with different commands
button_dict={}
option= ["Python", "Java", "Go", "C++"]

for i in option:
   def func(x=i):
      return entry_update(x)

   button_dict[i]=ttk.Button(win, text=i, command= func)
   button_dict[i].pack()

win.mainloop()
Running the above code will display a window that contains some buttons. When we click a particular button, it will update the message in the Entry widget.
Now, click each button to see the resultant output.
Ceil and Floor functions in C++ - GeeksforGeeks

04 Apr, 2018
In mathematics and computer science, the floor and ceiling functions map a real number to the greatest preceding or the least succeeding integer, respectively.
floor(x) : Returns the largest integer that is smaller than or equal to x (i.e : rounds downs the nearest integer).
// Here x is the floating point value.
// Returns the largest integer smaller 
// than or equal to x 
double floor(double x)  
Examples of Floor:
Input : 2.5
Output : 2

Input : -2.1
Output : -3

Input : 2.9
Output : 2

// C++ program to demonstrate floor function#include <iostream>#include <cmath>using namespace std;  // Driver functionint main(){    // using floor function which return    // floor of input value    cout << "Floor is : " << floor(2.3) << endl;    cout << "Floor is : " << floor(-2.3) << endl;      return 0;}
Output:
Floor is : 2
Floor is : -3

 
ceil(x) : Returns the smallest integer that is greater than or equal to x (i.e : rounds up the nearest integer).
// Here x is the floating point value.
// Returns the smallest integer greater 
// than or equal to x 
double ceiling(double x)  
Examples of Ceil:
Input : 2.5
Output : 3

Input : -2.1
Output : -2

Input : 2.9
Output : 3

// C++ program to demonstrate ceil function#include <iostream>#include <cmath>using namespace std;  // Driver functionint main(){    // using ceil function which return    // floor of input value    cout << " Ceil is : " << ceil(2.3) << endl;    cout << " Ceil is : " << ceil(-2.3) << endl;      return 0;}
Ceil is : 3
Ceil is : -2

This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
CPP-Library
cpp-math
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Socket Programming in C/C++
Operator Overloading in C++
Iterators in C++ STL
C++ Classes and Objects
Multidimensional Arrays in C / C++
Python Dictionary
Reverse a string in Java
Interfaces in Java
Operator Overloading in C++
C++ Classes and Objects
Python program to read character by character from a file

24 Jan, 2022
Given a text file. The task is to read the text from the file character by character.Function used: 
Syntax: file.read(length)Parameters: An integer value specified the length of data to be read from the file.Return value: Returns the read bytes in form of a string.  
Examples 1: Suppose the text file looks like this. 
 
Python3
# Demonstrated Python Program# to read file character by character  file = open('file.txt', 'r') while 1:         # read by character    char = file.read(1)             if not char:        break             print(char) file.close()
Output  
Example 2: REading more than one characters at a time.  
Python3
# Python code to demonstrate# Read character by character  with open('file.txt') as f:         while True:                 # Read from file        c = f.read(5)        if not c:            break         # print the character        print(c)
Output  
 
anikakapoor
khushboogoyal499
Python file-handling-programs
python-file-handling
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
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
How to create softlink of a file using Python?

The method os.symlink(src, dst) creates a symbolic link dst pointing to src. For example, if you have a file called photo.jpg and want to create a softlink/symbolic link to it called my_photo.jpg, then you could simply use:
>>> import os
>>> os.symlink('photo.jpg', 'my_photo.jpg')
Now if you list the files in that directory, you'll get the my_photo.jpg there as well.
Types of Schedules based Recoverability in DBMS

26 Apr, 2021
Generally, there are three types of schedule given as follows: 
 
1. Recoverable Schedule – A schedule is said to be recoverable if it is recoverable as name suggest. Only reads are allowed before write operation on same data. Only reads (Ti->Tj) is permissible. 
Example –  
S1: R1(x), W1(x), R2(x), R1(y), R2(y), 
         W2(x), W1(y), C1, C2; 
Given schedule follows order of Ti->Tj => C1->C2. Transaction T1 is executed before T2 hence there is no chances of conflict occur. R1(x) appears before W1(x) and transaction T1 is committed before T2 i.e. completion of first transaction performed first update on data item x, hence given schedule is recoverable. 
Lets see example of unrecoverable schedule to clear the concept more:  
S2: R1(x), R2(x), R1(z), R3(x), R3(y), W1(x), 
       W3(y), R2(y), W2(z), W2(y), C1, C2, C3; 
Ti->Tj => C2->C3 but W3(y) executed before W2(y) which leads to conflicts thus it must be committed before T2 transaction. So given schedule is unrecoverable. if Ti->Tj => C3->C2 is given in schedule then it will become recoverable schedule. 
Note: A committed transaction should never be rollback. It means that reading value from uncommitted transaction and commit it will enter the current transaction into inconsistent or unrecoverable state this is called Dirty Read problem. 
Example: 
 
2. Cascadeless Schedule – When no read or write-write occurs before execution of transaction then corresponding schedule is called cascadeless schedule. 
Example –  
S3: R1(x), R2(z), R3(x), R1(z), R2(y), R3(y), W1(x), C1, 
         W2(z), W3(y), W2(y), C3, C2; 
In this schedule W3(y) and W2(y) overwrite conflicts and there is no read, therefore given schedule is cascadeless schedule. 
Special Case – A committed transaction desired to abort. As given below all the transactions are reading committed data hence it’s cascadeless schedule. 
 
3. Strict Schedule – if schedule contains no read or write before commit then it is known as strict schedule. Strict schedule is strict in nature. 
Example –  
S4: R1(x), R2(x), R1(z), R3(x), R3(y), 
        W1(x), C1, W3(y), C3, R2(y), W2(z), W2(y), C2; 
In this schedule no read-write or write-write conflict arises before commit hence its strict schedule: 
 
4. Cascading Abort – Cascading Abort can also be rollback. If transaction T1 abort as T2 read data that written by T1 which is not committed. Hence it’s cascading rollback. 
Example: 
 
Correlation between Strict, Cascadeless and Recoverable schedule: 
 
From above figure:  
Strict schedules are all recoverable and cascadeless schedules  All cascadeless schedules are recoverable  
Strict schedules are all recoverable and cascadeless schedules  
All cascadeless schedules are recoverable  
 
simmytarika5
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find the maximum element of a Vector using STL in C++?

19 Mar, 2019
Given a vector, find the maximum element of this vector using STL in C++.
Example:
Input: {1, 45, 54, 71, 76, 12}
Output: 76

Input: {1, 7, 5, 4, 6, 12}
Output: 12

Approach: Max or Maximum element can be found with the help of *max_element() function provided in STL.
Syntax:
*max_element (first_index, last_index);

// C++ program to find the max// of Array using *max_element() in STL  #include <bits/stdc++.h>using namespace std;  int main(){    // Get the vector    vector<int> a = { 1, 45, 54, 71, 76, 12 };      // Print the vector    cout << "Vector: ";    for (int i = 0; i < a.size(); i++)        cout << a[i] << " ";    cout << endl;      // Find the max element    cout << "\nMax Element = "         << *max_element(a.begin(), a.end());    return 0;}
Vector: 1 45 54 71 76 12 

Max Element = 76

cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Object Oriented Programming in C++
Inheritance in C++
C++ Classes and Objects
Sorting a vector in C++
How we can import Python modules without installing?

Yes there are ways to import Python modules without installing. If you are not able to install modules on a machine(due to not having enough permissions), you could use either virtualenv or save the module files in another directory and use the following code to allow Python to search for modules in the given module:
>>> import os, sys
>>> file_path = 'AdditionalModules/'
>>> sys.path.append(os.path.dirname(file_path))
>>> # Now python also searches AdditionalModules folder for importing modules as we have set it on the PYTHONPATH.
You can also use virtualenv to create an isolated local Python environment. The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded. This can also be used in our use case where we cannot install the package on the machine as we dont have the permissions. For more info on virtual env, read the docs: https://virtualenv.pypa.io/en/stable/
How to draw a violin plot in R?

A violin plot is similar to a boxplot but looks like a violin and shows the distribution of the data for different categories. It shows the density of the data values at different points. In R, we can draw a violin plot with the help of ggplot2 package as it has a function called geom_violin for this purpose.
Consider the below data frame −
set.seed(1)
x <-rep(c("S1","S2","S3","S4","S5"),each=50)
set.seed(1)
x <-rep(c("S1","S2","S3","S4","S5"),each=100)
y <-rnorm(500)
grp <-rep(c("A","B"),times=250)
df <-data.frame(x,y,grp)
head(df,20)
   x    y    grp
1 S1 -0.62645381 A
2 S1 0.18364332 B
3 S1 -0.83562861 A
4 S1 1.59528080 B
5 S1 0.32950777 A
6 S1 -0.82046838 B
7 S1 0.48742905 A
8 S1 0.73832471 B
9 S1 0.57578135 A
10 S1 -0.30538839 B
11 S1 1.51178117 A
12 S1 0.38984324 B
13 S1 -0.62124058 A
14 S1 -2.21469989 B
15 S1 1.12493092 A
16 S1 -0.04493361 B
17 S1 -0.01619026 A
18 S1 0.94383621 B
19 S1 0.82122120 A
20 S1 0.59390132 B
Creating violin plot by filling colors with x variable −
ggplot(df,aes(grp,y,fill=x))+geom_violin()
Creating violin plot by filling colors with grp variable −
ggplot(df,aes(x,y,fill=grp))+geom_violin()
ES6 - Collections Set Method add()

This method appends a new element with the given value to the Set object.
mySet.add(value);

Value − item to add to the list.
Value − item to add to the list.
Set Object.
var set = new Set(); 
set.add(10); 
set.add(10); // duplicate not added 
set.add(10); // duplicate not added 
set.add(20); 
set.add(30); 
console.log(set.size);
3


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
Python | Matrix Product - GeeksforGeeks

30 Dec, 2020
Getting the product of list is quite common problem and has been dealt with and discussed many times, but sometimes, we require to better it and total product, i.e. including those of nested list as well. Let’s try and get the total product and solve this particular problem.
Method #1 : Using list comprehension + loopWe can solve this problem using the list comprehension as a potential shorthand to the conventional loops that we may use to perform this particular task. We just iterate and product the nested list and at end return the cumulative product using function.
# Python3 code to demonstrate# Matrix Product# Using list comprehension + loop  # getting Productdef prod(val) :    res = 1     for ele in val:        res *= ele    return res   # initializing listtest_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + loop# Matrix Productres = prod([ele for sub in test_list for ele in sub])  # print resultprint("The total element product in lists is : " + str(res))
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880

 
Method #2 : Using chain() + loopThis particular problem can also be solved using the chain function instead of list comprehension in which we use the conventional function to perform product.
# Python3 code to demonstrate# Matrix Product# Using chain() + loopfrom itertools import chain  # getting Productdef prod(val) :    res = 1     for ele in val:        res *= ele    return res   # initializing listtest_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]  # printing original listprint("The original list : " + str(test_list))  # using chain() + loop# Matrix Productres = prod(list(chain(*test_list)))  # print resultprint("The total element product in lists is : " + str(res))
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element product in lists is : 1622880

Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?