code-rag-bench/online-tutorials huggingface dataset:
Combine Multiple ggplot2 Legend in R - GeeksforGeeks

23 May, 2021
In this article, we will see how to combine multiple ggplot2 Legends in the R programming language.
First, load the ggplot2 package by using the library() function. If you have not installed it yet, you can simply install it by writing the below command in R Console.
install.packages("ggplot2")
To create an R plot, we use ggplot() function and for make it scatter plot we add geom_point() function to ggplot() function. Let us first create a plot with multiple legends in the same plot without combining so that the difference is apparent.
Example:
R
# Load Packagelibrary("ggplot2")  # Create a DataFrame data <- data.frame(Xdata = rnorm(6),                                           Ydata = rnorm(6),                   Group1 = c("ld-01", "ld-02", "ld-03",                              "ld-04", "ld-05", "ld-06"),                                        Group2 = c("ld-01", "ld-02", "ld-03",                              "ld-04", "ld-05", "ld-06"))  # Create a Scatter Plot With Multiple Legendsggplot(data, aes(Xdata, Ydata, color = Group1, shape = Group2)) +     geom_point(size = 7)
Output:
Scatterplot with multiple legends
As you can see in the above plot the two legends Group1 represents color and Group2 represents shape of Points in scatter plot are differently outlined. To Combine them into one legend, We should choose only one out of both Legends. Here we have chosen Group2, So we assign Group2 to color and shape parameters of aes() function. You can also choose Group1.
Example:
R
# Load Packagelibrary("ggplot2")  # Create a DataFrame data <- data.frame(Xdata = rnorm(6),                                           Ydata = rnorm(6),                   Group1 = c("ld-01", "ld-02", "ld-03",                               "ld-04", "ld-05", "ld-06"),                                        Group2 = c("ld-01", "ld-02", "ld-03",                              "ld-04", "ld-05", "ld-06"))  # Create a Scatter Plot with Combined# multiple legendsggplot(data, aes(Xdata, Ydata, color = Group2, shape = Group2)) +     geom_point(size = 7)
Output:
Scatteplot with Combined multiple Legends
Picked
R-ggplot
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 import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
Counters in Python | Set 2 (Accessing Counters) - GeeksforGeeks

04 Feb, 2020
Counters in Python | Set 1 (Initialization and Updation)
Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown as 0.
Example :
# Python program to demonstrate accessing of# Counter elementsfrom collections import Counter  # Create a listz = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']col_count = Counter(z)print(col_count)  col = ['blue','red','yellow','green']  # Here green is not in col_count # so count of green will be zerofor color in col:    print (color, col_count[color])
Output:
Counter({'blue': 3, 'red': 2, 'yellow': 1})
blue 3
red 2
yellow 1
green 0

elements() :The elements() method returns an iterator that produces all of the items known to the Counter.Note : Elements with count <= 0 are not included.
Example :
# Python example to demonstrate elements() on# Counter (gives back list)from collections import Counter  coun = Counter(a=1, b=2, c=3)print(coun)  print(list(coun.elements()))
Output :
Counter({'c': 3, 'b': 2, 'a': 1})
['a', 'b', 'b', 'c', 'c', 'c']

most_common() :most_common() is used to produce a sequence of the n most frequently encountered input values and their respective counts.
# Python example to demonstrate most_elements() on# Counterfrom collections import Counter  coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219)  # This prints 3 most frequent charactersfor letter, count in coun.most_common(3):    print('%s: %d' % (letter, count))
Output :
f: 219
d: 120
c: 3

YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rqzSa8O97TM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Mayank Rawat .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.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Bigram formation from a given Python list - GeeksforGeeks

11 Dec, 2020
When we are dealing with text classification, sometimes we need to do certain kind of natural language processing and hence sometimes require to form bigrams of words for processing. In case of absence of appropriate library, its difficult and having to do the same is always quite useful. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using list comprehension + enumerate() + split()The combination of above three functions can be used to achieve this particular task. The enumerate function performs the possible iteration, split function is used to make pairs and list comprehension is used to combine the logic.
# Python3 code to demonstrate# Bigram formation# using list comprehension + enumerate() + split()   # initializing list test_list = ['geeksforgeeks is best', 'I love it']  # printing the original list print ("The original list is : " + str(test_list))  # using list comprehension + enumerate() + split()# for Bigram formationres = [(x, i.split()[j + 1]) for i in test_list        for j, x in enumerate(i.split()) if j < len(i.split()) - 1]  # printing resultprint ("The formed bigrams are : " + str(res))
Output :
The original list is : [‘geeksforgeeks is best’, ‘I love it’]The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]
 Method #2 : Using zip() + split() + list comprehensionThe task that enumerate performed in the above method can also be performed by the zip function by using the iterator and hence in a faster way. Let’s discuss certain ways in which this can be done.
# Python3 code to demonstrate# Bigram formation# using zip() + split() + list comprehension   # initializing list test_list = ['geeksforgeeks is best', 'I love it']  # printing the original list print ("The original list is : " + str(test_list))  # using zip() + split() + list comprehension# for Bigram formationres = [i for j in test_list        for i in zip(j.split(" ")[:-1], j.split(" ")[1:])]  # printing resultprint ("The formed bigrams are : " + str(res))
Output :
The original list is : [‘geeksforgeeks is best’, ‘I love it’]The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]
Natural-language-processing
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
PLSQL | LPAD Function - GeeksforGeeks

24 Sep, 2019
The PLSQL LPAD function is used for padding the left-side of a string with a specific set of characters. a prerequisite for this is that string shouldn’t be NULL. The LPAD function in PLSQL is useful for formatting the output of a query. The LPAD function accepts three parameters which are input_string, padded_length and the pad_string.
Both input_string and pad_string can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2 datatype if input_string is a character datatype. The argument padded_length must be a NUMBER integer or a value that can be implicitly converted to a NUMBER integer. If you do not specify pad_string, then the default is a single blank. If input_string is longer than padded_length, then this function returns the portion of input_string that fits in padded_length.
Syntax:
LPAD( input_string, padded_length, pad_string )
Parameters Used:
input_string – It is used to specify the string which needs to be formatted.
padded_length – It is used to specify the number of characters to return. If the padded_length is smaller than the original string, the LPAD function will truncate the string to the size of padded_length.
pad_string – It is an optional parameter which is used to specify the input_string that will be padded to the left-hand side of string. If this parameter is omitted, the LPAD function will pad spaces to the left-side of string1.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1:
DECLARE 
   Test_String string(20) := 'Geeksforgeeks';
   
BEGIN 
   dbms_output.put_line(LPAD(Test_String, '5')); 
   
END; 
Output:
Geeks 
Example-2:
DECLARE 
   Test_String string(20) := 'Geeksforgeeks';
   
BEGIN 
   dbms_output.put_line(LPAD(Test_String, '17')); 
   
END; 
Output:
Geeksforgeeks 
Example-3:
DECLARE 
   Test_String string(20) := 'Geeksforgeeks';
   
BEGIN 
   dbms_output.put_line(LPAD(Test_String, '17', '0')); 
   
END;  
Output:
0000Geeksforgeeks 
Example-4:
DECLARE 
   Test_String string(20) := 'Geeksforgeeks';
   
   
BEGIN 
   dbms_output.put_line(LPAD(Test_String, '12', '0')); 
   
END;   
Output:
Geeksforgeeks 
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL | GROUP BY
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between DELETE and TRUNCATE
SQL - ORDER BY
Build a COVID19 Vaccine Tracker Using Python - GeeksforGeeks

29 Dec, 2020
As we know the world is facing an unprecedented challenge with communities and economies everywhere affected by the COVID19. So, we are going to do some fun during this time by tracking their vaccine. Let’s see a simple Python script to improve for tracking the COVID19 vaccine.
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not comes built-in with Python. To install this type the below command in the terminal.
pip install bs4
requests:  Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests
Approach:
Extract data form given URL
Scrape the data with the help of requests and Beautiful Soup
Convert that data into html code.
Find the required details and filter them.
Let’s see the stepwise execution of the script
Step 1:   Import all dependence 
Python3
import requestsfrom bs4 import BeautifulSoup
Step 2: Create a URL get function
Python3
def getdata(url):    r = requests.get(url)    return r.text
Step 3: Now pass the URL into the getdata function and Convert that data into HTML code
Python3
htmldata = getdata("https://covid-19tracker.milkeninstitute.org/")soup = BeautifulSoup(htmldata, 'html.parser')res = soup.find_all("div", class_="is_h5-2 is_developer w-richtext")print(str(res))
Output:
Note: These scripts will give you only Raw data in String format you have to print your data with your needs. 
Complete code:
Python3
import requestsfrom bs4 import BeautifulSoup    def getdata(url):    r = requests.get(url)    return r.text  htmldata = getdata("https://covid-19tracker.milkeninstitute.org/")soup = BeautifulSoup(htmldata, 'html.parser')result = str(soup.find_all("div", class_="is_h5-2 is_developer w-richtext"))  print("NO 1 " + result[46:86])print("NO 2 "+result[139:226])print("NO 3 "+result[279:305])print("NO 4 "+result[358:375])print("NO 5 "+result[428:509])
Output:
Python web-scraping-exercises
Python-projects
Python-requests
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
TreeMap floorEntry() Method in Java With Examples - GeeksforGeeks

02 Sep, 2020
The java.util.TreeMap.floorEntry() method is used to return a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
Syntax:
tree_map.floorEntry(K key)
Parameters: This method takes one parameter key to be matched while mapping.
Return Value:  This method returns an entry with the greatest key less than or equal to key, or null if there is no such key.
Exceptions:  
 ClassCastException : This exception is thrown if the specified key cannot be compared with the keys currently in the map.
 NullPointerException : This exception is thrown if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.
Example 1: When there is a key
Java
// Java program to illustrate// TreeMap floorEntry() methodimport java.util.*;  public class GFG {    public static void main(String[] args)    {          // Creating an empty TreeMap        TreeMap<Integer, String> treemap            = new TreeMap<Integer, String>();                // Mapping string values to int keys         treemap.put(20, "Twenty");        treemap.put(10, "Ten");        treemap.put(13, "Thirteen");        treemap.put(60, "Sixty");        treemap.put(50, "Fifty");          System.out.println("The greatest key-value less than 18 is : "                           + treemap.floorEntry(18));    }}
The greatest key-value less than 18 is : 13=Thirteen

Example 2: When there is no such key
Java
// Java program to illustrate// TreeMap floorEntry() methodimport java.util.TreeMap;  public class GFG {    public static void main(String args[])    {           // Creating an empty TreeMap        TreeMap<Integer, String> treemap            = new TreeMap<Integer, String>();          // Mapping string values to int keys         treemap.put(10, "Akash");        treemap.put(20, "Pratik");        treemap.put(30, "Vaibhav");        treemap.put(40, "Sagar");        treemap.put(50, "Abhishek");          // Printing floor entry        System.out.println("The greatest key-value less than 5 is : "                           + treemap.floorEntry(5));    }}
The greatest key-value less than 5 is : null

Java-Collections
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Multithreading in Java
Collections in Java
Initializing a List in Java
Convert Double to Integer in Java

At first, initialize a double value −
double val = 978.65;
Now, convert the Double to Integer value using intValue() method −
Double d = new Double(val);
int res = d.intValue();
Following is the program to convert Double to Integer in Java −
public class Demo {
   public static void main(String args[]) {
      double val = 978.65;
      System.out.println("Double = "+val);
      Double d = new Double(val);
      int res = d.intValue();
      System.out.println("Double to Integer value = "+res);
   }
}
Double = 978.65
Double to Integer value = 978
How to Rename and Move a File in Golang?

02 Apr, 2020
In the Go language, you are allowed to rename and move the existing file to a new path with the help of the Rename() method. This method is used to rename and move a file from the old path to the new path.
If the given new path already exists and it is not in a directory, then this method will replace it. But OS-specific restrictions may apply when the given old path and the new path are in different directories.
If the given path is incorrect, then it will throw an error of type *LinkError.
It is defined under the os package so, you have to import os package in your program for accessing Remove() function.
Syntax:
func Rename(old_path, new_path string) error
Example 1:
// Go program to illustrate how to rename// and move a file in default directorypackage main    import (    "log"    "os")    func main() {       // Rename and Remove a file    // Using Rename() function    Original_Path := "GeeksforGeeks.txt"    New_Path := "gfg.txt"    e := os.Rename(Original_Path, New_Path)    if e != nil {        log.Fatal(e)    }      }
Output:
Before:
After:
Example 2:
// Go program to illustrate how to rename // and remove a file in the new directorypackage main    import (    "log"    "os")    func main() {       // Rename and Remove a file    // Using Rename() function    Original_Path := "/Users/anki/Documents/new_folder/GeeksforGeeks.txt"    New_Path := "/Users/anki/Documents/new_folder/myfolder/gfg.txt"    e := os.Rename(Original_Path, New_Path)    if e != nil {        log.Fatal(e)    }}
Output:
Before:
After:
Golang-File-Handling
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML5 | <details> tag

06 Jun, 2022
The <details> tag is used for the content/information which is initially hidden but could be displayed if the user wishes to see it. This tag is used to create an interactive widget that the user can open or close. The content of the details tag is visible when open the set attributes. The summary tag is used with the details tag for specifying visible heading. 
This tag is new in HTML5. 
Syntax: 
<details>
    <summary>  Text content  </summary>
    <div> Content . . . >
</details>
Attributes:
details open: The detail tag has an attribute called open which is used to display the hidden information by default.  Example: The below code explains the details tag.
HTML
<!DOCTYPE html><html>    <body>        <h1>GeeksforGeeks</h1>        <!-- details tag starts here -->        <details>            <summary>GeeksforGeeks</summary>               <p>A computer science portal for geeks</p>               <div>It is a computer science portal where you            can learn programming.</div>         <!-- details tag ends here -->        </details>    </body></html>
Output:  
Syntax: 
<details open>
    <summary>  Text content  </summary>
    <div> Content . . . >
</details>
Example: The below code explains the details open tag in details tag.
HTML
<!DOCTYPE html><html>    <body>        <h1>GeeksforGeeks</h1>        <!-- details open tag starts here -->        <details open>            <summary>GeeksforGeeks</summary>               <p>A computer science portal for geeks</p>               <div>It is a computer science portal where you            can learn programming.</div>         <!-- details open tag ends here -->        </details>    </body></html>                   
Output:  
Supported Browsers: 
Google Chrome 12.0 and above
Firefox 49.0 and above
Opera 15.0 and above
Safari 6.0 and above
shubham_singh
shubhamyadav4
avtarkumar719
hritikbhatnagar2182
HTML5
Picked
CSS
HTML
Web technologies Questions
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
Parsero – Tool for reading the Robots.txt file in Kali Linux

18 Jul, 2021
Parsero is a free and open-source tool available on GitHub.  Parsero is used to reading Robots.txt files of websites and web apps. This tool can be used to get information about our target(domain). We can target any domain using Parsero. It has an interactive console that provides a number of helpful features, such as command completion and contextual help. This tool is written in python, so you must have python installed in your Kali Linux to use this tool.
 It is a python script that is used to read Robots.txt file on a live web server in the disallowed entries. When the tool starts working, these disallowed entries tell the search engines what HTML files or static directories must or must not be indexed. Google spiders and crawlers play important roles in indexing a website according to the number of visitors. It is the responsibility of the administrator that they don’t share private and sensitive information with the search engines. But sometimes these developers mistakenly allow search engines to access Robots.txt file. Parsero helps in such situations by checking whether the Robots.txt file is visible or not.
Step 1: Use the following command to install the Parsero tool.
apt install parsero
Step 2: The tool has been downloaded and installed successfully. Now, run the tool using the following command.
parsero -h
The tool is running successfully. Now we will see an example to use the tool.
Example: Use the parsero tool to scan any website.
parsero -u <domain>
This is how you can search for your target. This tool is very useful for security researchers in the initial phases of Pentesting. You can target any domain of your choice.
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
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
FLOOR() AND CEIL() Function in MySQL

28 Sep, 2020
1. FLOOR() Function :FLOOR() function in MySQL is used to return the largest integer value which will be either equal to or less than from a given input number.
Syntax :
FLOOR(X)
Parameter : Required.X : A number whose floor value we want to calculate.Returns : It returns the closest integer which is <=X. So, if X is integer than it will return X. Otherwise, largest integer which is lesser than X.
Example-1 :Applying FLOOR() function to a +ve integer.
SELECT FLOOR(4) AS Floor_Value;
Output :
Example-2 :Applying FLOOR() function to a -ve integer.
SELECT FLOOR(-6) AS Floor_Value;
Output :
Example-3 :Applying FLOOR() function to a +ve floating number.
SELECT FLOOR(1.5) AS Floor_Value;
Output :
Example-4 :Applying FLOOR() function to a -ve floating number.
SELECT FLOOR(-1.5) AS Floor_Value;
Output :
Example-5 :FLOOR value of a numeric column in a table.
Table – Number
SELECT X, FLOOR(X) AS X_Floor FROM Number;
Output :
2. CEIL() Function :CEIL() function in MySQL is used to return the smallest integer value which is either greater than or equal to the given input number.
Syntax :
CEIL(X)
Parameter : Required.X : A number whose ceiling value we want to calculate.Returns : It returns the closest integer which is >=X. So, if X is integer than it will return X. Otherwise, next integer which is greater than X.
Example-1 :Applying CEIL() function to a +ve integer.
SELECT CEIL(5) AS Ceil_Value;
Output :
Example-2 :Applying CEIL() function to a -ve integer.
SELECT CEIL(-8) AS Ceil_Value;
Output :
Example-3 :Applying CEIL() function to a +ve floating number.
SELECT CEIL(1.5) AS Ceil_Value;
Output :
Example-4 :Applying CEIL() function to a -ve floating number.
SELECT CEIL(-1.5) AS Ceil_Value;
Output :
Example-5 :CEIL value of a numeric column in a table.
Table – Number
SELECT X, CEIL(X) AS X_Ceil FROM Number;
Output :
DBMS-SQL
mysql
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?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
PyQt5 – How to set text to progress bar ?

22 Apr, 2020
In this article we will see how to set text to progress bar. When we create a progress bar only progress percentage text is visible but we can also set some text on it.
Below is how normal progress bar vs progress bar with text looks like. 
In order to do this we will use setFormat method, although it is used to set the format i.e percentage indicator but if we pass normal text to it it will display it in process bar.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):        def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating progress bar        bar = QProgressBar(self)          # setting geometry to progress bar        bar.setGeometry(200, 150, 200, 30)          # set value to progress bar        bar.setValue(70)          # setting text         bar.setFormat('This is progress bar')          # setting alignment to centre        bar.setAlignment(Qt.AlignCenter)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Use of print() and say() in Perl

18 Jun, 2019
Perl uses statements and expressions to evaluate the input provided by the user or given as Hardcoded Input in the code. This evaluated expression will not be shown to the programmer as it’s been evaluated in the compiler. To display this evaluated expression, Perl uses print() function and say() function. These functions can display anything passed to them as arguments.
print operator in Perl is used to print the values of the expressions in a List passed to it as an argument. Print operator prints whatever is passed to it as an argument whether it be a string, a number, a variable or anything. Double-quotes(“”) is used as a delimiter to this operator.
Syntax:
print "";
Example:
#!/usr/bin/perl -w     # Defining a string $string1 = "Geeks For Geeks"; $string2 = "Welcomes you all";  print "$string1";print "$string2";
Geeks For GeeksWelcomes you all

Above example, prints both the strings with the help of print function but both the strings are printed in the same line. To avoid this and print them in different lines, we need to use a ‘\n’ operator that changes the line whenever used.
Example:
#!/usr/bin/perl -w     # Defining a string $string1 = "Geeks For Geeks"; $string2 = "Welcomes you all";  print "$string1\n";print "$string2";
Geeks For Geeks
Welcomes you all

If we use Single Quotes instead of double quotes, then the print() function will not print the value of the variables or the escape characters used in the statement like ‘\n’, etc. These characters will be printed as it is and will not be evaluated.
Example:
#!/usr/bin/perl -w     # Defining a string $string1 = 'Geeks For Geeks'; $string2 = 'Welcomes you all';  print '$string1\n';print '$string2';
$string1\n$string2

say() function in Perl works similar to the print() function but there’s a slight difference, say() function automatically adds a new line at the end of the statement, there is no need to add a newline character ‘\n’ for changing the line.
Example:
#!/usr/bin/perl -w use 5.010;  # Defining a string $string1 = "Geeks For Geeks"; $string2 = "Welcomes you all";  # say() function to printsay("$string1");say("$string2");
Geeks For Geeks
Welcomes you all

Here, we have used ‘use 5.010‘ to use the say() function because newer versions of Perl don’t support some functions of the older versions and hence, the older version is to be called to execute the say() function.
perl-basics
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Regular Expressions
Perl | Polymorphism in OOPs
Perl Tutorial - Learn Perl With Examples
Perl | Boolean Values
Perl | length() Function
Perl | Subroutines or Functions
Perl | Basic Syntax of a Perl Program
Introduction to Perl
Hello World Program in Perl
Perl | substitution Operator
Python program to count upper and lower case characters without using inbuilt functions

24 Nov, 2020
Given a string that contains both upper and lower case characters in it. The task is to count number of upper and lower case characters in it without using in-built functions.
Counting the upper and lower case characters of a string can be easily done using isupper() and islower() functions, refer this. But doing the same without help of any inbuilt function is quite exciting. Let’s see how this can be done :
Examples :
Input : Introduction to Python
Output : Lower Case characters : 18 Upper case characters : 2

Input :  Welcome to GeeksforGeeks
Output : Lower Case characters : 19  Upper case characters: 3

 Below is the implementation of above idea :
# Python3 program to count upper and# lower case characters without using# inbuilt functionsdef upperlower(string):      upper = 0    lower = 0      for i in range(len(string)):                  # For lower letters        if (ord(string[i]) >= 97 and            ord(string[i]) <= 122):            lower += 1          # For upper letters        elif (ord(string[i]) >= 65 and              ord(string[i]) <= 90):            upper += 1      print('Lower case characters = %s' %lower,          'Upper case characters = %s' %upper)  # Driver Codestring = 'GeeksforGeeks is a portal for Geeks'upperlower(string)
Lower case characters = 27 Upper case characters = 3

Alternative Method:-
s = "The Geek King"l,u = 0,0for i in s:    if (i>='a'and i<='z'):                  # counting lower case        l=l+1                     if (i>='A'and i<='Z'):                  #counting upper case        u=u+1             print('Lower case characters: ',l)print('Upper case characters: ',u)
Lower case characters:  8
Upper case characters:  3

Divyu_Pandey
Python string-programs
python-string
Python
Technical Scripter
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
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Count Number of List Elements in R

05 Apr, 2021
In this article, we are going to count the elements in a list and elements in a nested list in R Programming Language. So we are going to use length() and lengths() to find the elements count in a list.
Steps –
Create a list with vectors/list/range operator
Find the count of elements using the length and lengths function.
Syntax: list(value1,value2,...,value)
values can be range operator or vector.
Let’s create a list using the range, vector, and list.
R
# range from 10 to 50values = 10:50  # vector elements of character typenames = c("sravan", "bobby", "ojaswi", "gnanu")  # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5)  # give input to the data which is a listdata = list(values, names, data1)  # displayprint(data)
Output:
Example 1: Using length() function.
Length function is used to count the elements in the list
Syntax: length(listname)
return value: integer
Below is the implementation:
R
# range from 10 to 50values = 10:50  # vector elements of character typenames = c("sravan", "bobby", "ojaswi", "gnanu")  # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5)  # give input to the data which is a listdata = list(values, names, data1)  # displayprint(data)  # count elements using length functionprint(length(data))
Output:
Example 2: For finding the length of each data in a list (nested list) we will use lengths() function
Syntax: lengths(list_name)
Below is the implementation:
R
# range from 10 to 50values = 10:50  # vector elements of character typenames = c("sravan", "bobby", "ojaswi", "gnanu")  # data1 with list of elementsdata1 = list(1, 2, 3, 4, 5)  # give input to the data which is a listdata = list(a1 = values, a2 = names, a3 = data1)  # displayprint(data)  # count elements in each nested  using lengths functionprint(lengths(data))
Output:
Example 3: R program count elements in a nested list
R
# data1 with list of elementsdata1 = list(1, 2, 3, 4, 5)  # data2 with list of elementsdata2 = list("a", 'b', 'c')  # give input to the data which is a listdata = list(a1 = data1, a2 = data2)  # displayprint(data)  # count elements in each nested  using length functionprint(length(data))print("-----")  # count elements in each nested  using lengths functionprint(lengths(data))
Output:
Picked
R List-Programs
R-List
R Language
R Programs
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
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
Python – Remove dictionary from a list of dictionaries if a particular value is not present

When it is required to remove dictionary from a list of dictionaries if a particular value is not present, a simple iteration and the ‘del’ operator is used.
Below is a demonstration of the same −
my_list = [{"id" : 1, "data" : "Python"},
   {"id" : 2, "data" : "Code"},
   {"id" : 3, "data" : "Learn"}]

print("The list is :")
print(my_list)

for index in range(len(my_list)):
   if my_list[index]['id'] == 2:
      del my_list[index]
      break

print("The result is :")
print(my_list)
The list is :
[{'id': 1, 'data': 'Python'}, {'id': 2, 'data': 'Code'}, {'id': 3, 'data': 'Learn'}]
The result is :
[{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}]
A list of dictionary elements is defined and is displayed on the console.
A list of dictionary elements is defined and is displayed on the console.
The list of dictionary is iterated over, and the ‘value’ associated with every key is checked to equivalent to 2.
The list of dictionary is iterated over, and the ‘value’ associated with every key is checked to equivalent to 2.
If yes, that specific element is deleted.
If yes, that specific element is deleted.
The control breaks out of the loop.
The control breaks out of the loop.
In the end, this list of dictionary is displayed as output on the console.
In the end, this list of dictionary is displayed as output on the console.
wxPython - Environment

Prebuilt binaries for Windows OS (both 32 bit and 64 bit) are available on http://www.wxpython.org/download.php page. Latest versions of installers available are − wxPython3.0-win32-3.0.2.0-py27.exe for 32-bit Python 2.7 wxPython3.0-win64-3.0.2.0-py27.exe for 64-bit Python 2.7
wxPython demo, samples and wxWidgets documentation is also available for download on the same page.
wxPython3.0-win32-docs-demos.exe
wxPython binaries for many Linux distros can be found in their respective repositories. Corresponding package managers will have to be used to download and install. For instance on Debian Linux, following command should be able to install wxPython.
sudo apt-get install python-wxgtk3.0

Prebuilt binaries for MacOS in the form of disk images are available on the download page of the official website.
 Print
 Add Notes
 Bookmark this page
Batch Script - EXIT

This batch command exits the DOS console.
Exit

@echo off 
echo "Hello World" 
exit
The batch file will terminate and the command prompt window will close.
 Print
 Add Notes
 Bookmark this page
C++ program to find the sum of the series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!

In this tutorial, we will be discussing a program to find the sum of the given series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!.
For this, we will be given with the value of n and our task is to add up every term starting from the first one to find the sum of the given series.
#include <iostream>
using namespace std;
//calculating the sum of the series
double calc_sum(int n) {
   int i;
   double sum = 0, fact=1;
   for (i = 1; i <= n; i++)
   fact = fact * i;
   sum += i/fact;
   return sum;
}
int main() {
   int n = 6;
   double res = calc_sum(n);
   cout << res << endl;
   return 0;
}
0.00972222
Java Program to calculate area of a Tetrahedron

A Tetrahedron is a polyhedron composed of four triangular faces, six straight edges, and four vertex corners.
Following is the Java program to calculate area of a Tetrahedron −
 Live Demo
import java.io.*;
public class Demo{
   static double tetra_vol(int side){
      double my_vol = (Math.pow(side, 3) / (6 * Math.sqrt(2)));
      return my_vol;
   }
   public static void main(String[] args){
      int side = 4;
      double my_vol = tetra_vol(side);
      my_vol = (double)Math.round(my_vol * 100) / 100;
      System.out.println("The area of tetrahedron is");
      System.out.println(my_vol);
   }
}
The area of tetrahedron is
7.54
A class named Demo contains a static function named 'tetra_vol' which takes 'side' as a parameter. The formula to calculate area of a tetrahedron is ‘side’ cube/(6v2). This is computed and the output is returned. In the main function, the value of size is defined, and the function is called on this value. The output is printed on the console.
Inverse Factorial in Python

Suppose we have a number a, we have to find n, such that factorial of n (n!) is same as a. As we
know, the factorial n = n * (n - 1) * (n - 2) * ... * 1. If there is no such integer n then return -1.
So, if the input is like a = 120, then the output will be 5.
To solve this, we will follow these steps −
i := 0, num := 1
L:= a new list
while i < a, doi := factorial of numinsert i at the end of Lnum := num + 1
i := factorial of num
insert i at the end of L
num := num + 1
if a is in L, thenreturn the (index of a in L) +1
return the (index of a in L) +1
otherwise,return -1
return -1
Let us see the following implementation to get better understanding −
 Live Demo
import math
class Solution:
   def solve(self, a):
      i,num=0,1
      L=[]
      while i < a :
         i=math.factorial(num)
         L.append(i)
         num+=1
         if a in L :
            return L.index(a)+1
         else :
            return -1
ob = Solution()
print(ob.solve(120))
120
5
How to manipulate Date in PowerShell?

To add/remove date from the date string you need to use AddDay() method. For example,
We need to add 6 days to the current date.
(Get-Date).AddDays(6)
25 March 2020 22:40:36
To go back to the specific number of days, the same AddDays() method will be used but the numbers are negative.
 For example,
(Get-Date).AddDays(-6)
13 March 2020 22:45:34
Removing Duplicate or Similar Images in Python | by Angel Igareta | Towards Data Science

One of the most naive approaches to detecting duplicate images would be to compare pixel by pixel by checking that all values are the same. However, this becomes very inefficient when testing a large number of images.
A second very common approach would be to extract the cryptographic hash of both images and compare if they are the same, using popular hash algorithms such as MD5 or SHA-1. Although this approach is much more efficient, it would only detect identical images. In case one of the pixels differs (due to a slight change in lighting, for example) the hashes would be completely different.
The reason for this is that the data used by these cryptographic algorithms is based only on the pixels of the image and a random seed. The same data and the same seed will produce the same result, but different data will generate different results.
For our use case, it would make more sense for similar images to have similar hashes, right?
That is precisely the goal of image hashing algorithms. They focus on the structure of the image and its visual appearance to calculate the hash. Depending on your use case, some algorithms will be better than others.
For instance, if you want images with the same shape but different colors to have the same hash, perceptual or difference hashing could be used.
Keep in mind that there is always the possibility of using a larger image hash size and obtaining less similar images, which, depending on the use case, would have to be hyper-tuned.
For use in Python, I recommend the ImageHash library, which supports multiple image hashing algorithms, such as average, perceptual, difference, wavelet, HSV-color, and crop-resistant.
It can be easily installed with the following command:
pip install imagehash
As stated above, each algorithm can have its hash size adjusted, the higher this size is, the more sensitive to changes the hash is. Based on my experience, I recommend using the dhash algorithm with hash size 8 and the z-transformation available in the repository.
Below you can see the code needed to load an image, transform it and calculate the d-hash, which is encapsulated in the dhash_z_transformed method.
To apply it in a data pipeline, simply call the dhash_z_transformed method with the path of the image you want to hash. If the method produces the same hash for two images, it means that they are very similar. You can then choose to remove duplicates by keeping one copy or neither, depending on your use case.
I encourage you to adjust the sensitivity threshold by changing the hash_size for finer results to your use case.
In this short post, I have presented an important step to take into account when training machine learning models that receive images as input.
Instead of showing how to detect only identical images, I introduce image hashing algorithms to identify also similar images (different size but same image, slight changes in brightness...). Finally, I provide examples of how to compute these image hashes in Python using an external library.
If you want to discover more posts like this one, you can find me at:
What are the rules for a local variable in lambda expression in Java?

A lambda expression can capture variables like local and anonymous classes. In other words, they have the same access to local variables of the enclosing scope. We need to follow some rules in case of local variables in lambda expressions.
A lambda expression can't define any new scope as an anonymous inner class does, so we can't declare a local variable with the same which is already declared in the enclosing scope of a lambda expression.
Inside lambda expression, we can't assign any value to some local variable declared outside the lambda expression. Because the local variables declared outside the lambda expression can be final or effectively final.
The rule of final or effectively final is also applicable for method parameters and exception parameters.
The this and super references inside a lambda expression body are the same as their enclosing scope. Because lambda expressions can't define any new scope.
import java.util.function.Consumer;

public class LambdaTest {
   public int x = 1;
   class FirstLevel {
      public int x = 2;
      void methodInFirstLevel(int x) {
         Consumer<Integer> myConsumer = (y) -> {   // Lambda Expression
            System.out.println("x = " + x);
            System.out.println("y = " + y);
            System.out.println("this.x = " + this.x);
            System.out.println("LambdaTest.this.x = " + LambdaTest.this.x);
         };
         myConsumer.accept(x);
      }
   }
   public static void main(String args[]) {
      final LambdaTest outerClass = new LambdaTest();
      final LambdaTest.FirstLevel firstLevelClass = outerClass.new FirstLevel();
      firstLevelClass.methodInFirstLevel(10);
   }
}
x = 10
y = 10
this.x = 2
LambdaTest.this.x = 1
Frequency of each character in String in Python

Text processing has emerged as an important field in machine learning and AI. Python supports this filed with many available tools and libraries. In this article we will see how we can find the number of occurrence of each letter of a given string.
The Counter method counts the number of occurrences of an element in an iterable. So it is straight forward to use by passing the required string into it.
 Live Demo
from collections import Counter

# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

for keys in strA:
res[keys] = res.get(keys, 0) + 1

# Result
print("Frequency of each character :\n ",res)
Running the above code gives us the following result −
Given String: timeofeffort
Frequency of each character :
{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}
We can treat the string as a dictionary and count the keys for each character using get() in a for loop.
 Live Demo
# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

for keys in strA:
res[keys] = res.get(keys, 0) + 1

# Result
print("Frequency of each character :\n ",res)
Running the above code gives us the following result −
Given String: timeofeffort
Frequency of each character :
{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}
A set in python stores unique elements. So we can use it wisely by counting the number of times the same character is encountered again and again when looping through the string as an iterable.
 Live Demo
# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

res={n: strA.count(n) for n in set(strA)}

# Result
print("Frequency of each character :\n ",res)
Running the above code gives us the following result −
Given String: timeofeffort
Frequency of each character :
{'f': 3, 'r': 1, 'm': 1, 'o': 2, 'i': 1, 't': 2, 'e': 2}