code-rag-bench/online-tutorials huggingface dataset:
Create multiple regression lines in a single plot using ggplot2 in R.

To create multiple regression lines in a single plot using ggplot2, we can use geom_jitter function along with geom_smooth function. The geom_smooth function will help us to different regression line with different colors and geom_jitter will differentiate the points.
Check out the below Example to understand how it can be done.
Following snippet creates a sample data frame −
x1<-rpois(20,1)
y1<-rpois(20,5)
x2<-rpois(20,2)
y2<-rpois(20,8)
x3<-rpois(20,2)
y3<-rpois(20,4)
df<-data.frame(x1,y1,x2,y2,x3,y3)
df
The following dataframe is created
  x1 y1 x2 y2 x3 y3
 1 2  2  0  6  1 6
 2 3  4  0  9  1 7
 3 2  4  3  7  2 3
 4 0 12  2 11  0 1
 5 0  2  0  6  1 1
 6 1  7  2  7  1 3
 7 0  4  0  4  1 5
 8 0  3  2  5  0 1
 9 1  4  3  3  0 9
10 0  2  0  8  3 5
11 0  7  4 11  2 4
12 0  4  3  8  2 1
13 0  6  0  6  2 4
14 1  6  1  9  2 2
15 2  3  1  9  6 2
16 1  3  1 10  5 2
17 0  5  1  8  2 6
18 1  2  4  7  2 4
19 0  5  2 11  0 7
20 2  8  4  8  2 4
To load the ggplot2 package and create regression lines for multiple models in single plot on the above created data frame, add the following code to the above snippet −
x1<-rpois(20,1)
y1<-rpois(20,5)
x2<-rpois(20,2)
y2<-rpois(20,8)
x3<-rpois(20,2)
y3<-rpois(20,4)
df<-data.frame(x1,y1,x2,y2,x3,y3)
library(ggplot2)

ggplot(df)+geom_jitter(aes(x1,y1),colour="red")+geom_smooth(aes(x1,y1,col="red"
),method="lm",se=FALSE)+
+
geom_jitter(aes(x2,y2),colour="green")+geom_smooth(aes(x2,y2,col="green"),metho
d="lm",se=FALSE)+
+
geom_jitter(aes(x3,y3),colour="blue")+geom_smooth(aes(x3,y3,col="blue"),method=
"lm",se=FALSE)
`geom_smooth()` using formula 'y ~ x'
`geom_smooth()` using formula 'y ~ x'
`geom_smooth()` using formula 'y ~ x'
If you execute all the above given snippets as a single program, it generates the following Output −
Abundant Number in C ?

An abundant Number (also known as excessive number) is a number in the number theory which itself is smaller than the sum of all its proper divisors. For example,12 is an abundant Number : divisors 1,2,3,4,6 , sum =16 >12.
The difference between the sum of divisors and the number is called abundance. For above example abundance = 4 => 16 - 12 .
To check for abundant number we will find all the factors of the number and add them up. This sum compared with the number show that if the number is abundant or not.
#include >stdio.h>
#include <math.h>
int main(){
   int n = 56, sum = 0;
   for (int i=1; i<=sqrt(n); i++){
      if (n%i==0){
         if (n/i == i)
      sum = sum + i;
      {
         sum = sum + i;
         sum = sum + (n / i);
         }
      }
   }
   sum = sum - n;
   if(sum > n){
      printf("The number is abundant number");
   }
   else
      printf("The number is not abundant number");
   return 0;
}
get_screenshot_as_file driver method - Selenium Python - GeeksforGeeks

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

To demonstrate, get_screenshot_as_file method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get screenshot,
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")    # get Screenshotprint(driver.get_screenshot_as_file("foo.png"))
Output –Screenshot added –
Akanksha_Rai
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Program to find length of longest consecutive sequence in Python

Suppose we have an unsorted array of numbers, we have to find the length of the longest
sequence of consecutive elements.
So, if the input is like nums = [70, 7, 50, 4, 6, 5], then the output will be 4, as the longest
sequence of consecutive elements is [4, 5, 6, 7]. so we return its length: 4.
To solve this, we will follow these steps −
nums := all unique elements of nums
nums := all unique elements of nums
max_cnt := 0
max_cnt := 0
for each num in nums, doif num - 1 not in nums, thencnt := 0while num is present in nums, donum := num + 1cnt := cnt + 1max_cnt := maximum of max_cnt and cnt
for each num in nums, do
if num - 1 not in nums, thencnt := 0while num is present in nums, donum := num + 1cnt := cnt + 1max_cnt := maximum of max_cnt and cnt
if num - 1 not in nums, then
cnt := 0
cnt := 0
while num is present in nums, donum := num + 1cnt := cnt + 1
while num is present in nums, do
num := num + 1
num := num + 1
cnt := cnt + 1
cnt := cnt + 1
max_cnt := maximum of max_cnt and cnt
max_cnt := maximum of max_cnt and cnt
return max_cnt
return max_cnt
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      nums = set(nums)
      max_cnt = 0
      for num in nums:
         if num - 1 not in nums:
            cnt = 0
            while num in nums:
               num += 1
               cnt += 1
            max_cnt = max(max_cnt, cnt)
      return max_cnt
ob = Solution()
nums = [70, 7, 50, 4, 6, 5]
print(ob.solve(nums))
[70, 7, 50, 4, 6, 5]
4
Simple Ways to Read TSV Files in Python - GeeksforGeeks

23 Nov, 2021
In this article, we will discuss how to read TSV files in Python.
We will be using the same input file in all various implementation methods to see the output. Below is the input file from which we will read data.
 We will read data from TSV file using pandas read_csv(). Along with the TSV file, we also pass separator as ‘\t’ for the tab character because, for tsv files, the tab character will separate each field. 
Syntax :
data=pandas.read_csv('filename.tsv',sep='\t')
Example: Program Using Pandas
Python3
# Simple Way to Read TSV Files in Python using pandas# importing pandas libraryimport pandas as pd # Passing the TSV file to# read_csv() function# with tab separator# This function will# read data from fileinterviews_df = pd.read_csv('GeekforGeeks.tsv', sep='\t') # printing dataprint(interviews_df)
Output:
 We use csv.reader() to convert the TSV file object to csv.reader object. And then pass the delimiter as ‘\t’ to the csv.reader. The delimiter is used to indicate the character which will be separating each field.
Syntax:
with open("filename.tsv") as file:
    tsv_file = csv.reader(file, delimiter="\t")
Example: Program Using csv
Python3
# Simple Way to Read TSV Files in Python using csv# importing csv libraryimport csv # open .tsv filewith open("GeekforGeeks.tsv") as file:           # Passing the TSV file to     # reader() function    # with tab delimiter    # This function will    # read data from file    tsv_file = csv.reader(file, delimiter="\t")         # printing data line by line    for line in tsv_file:        print(line)
Output:
The very simple way to read data from TSV File in Python is using split(). We can read a given TSV file and store its data into a list.
Syntax: 
with open("filename.tsv") as file:
  for line in file:
    l=line.split('\t')
Example: Program Using split() 
Python3
# Simple Way to Read TSV Files in Python using splitans = [] # open .tsv filewith open("GeekforGeeks.tsv") as f:     # Read data line by line  for line in f:         # split data by tab    # store it in list    l=line.split('\t')         # append list to ans    ans.append(l) # print data line by linefor i in ans:    print(i)
Output:
rushi_javiya
Picked
python-file-handling
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
Convert string to DateTime and vice-versa in Python

Python has extensive date and time manipulation capabilities.In this article we'll see in how is string with proper format can we converted to a datetime and the vice versa.
This strptime function from datetime module can do the conversion from string to datetime by taking appropriate format specifiers.
 Live Demo
import datetime
dt_str = 'September 19 2019 21:02:23 PM'
#Given date time
print("Given date time: \n",dt_str)
#Type check
print("Data Type: ",type(dt_str))
#Format
dtformat = '%B %d %Y %H:%M:%S %p'
datetime_val = datetime.datetime.strptime(dt_str, dtformat)
print("After converting to date time: \n",datetime_val)
#Type check
print("Data type: ",type(datetime_val))
# Reverting to string
dtstr_new=str(datetime_val)
print("The string Date time ",dtstr_new)
print("Data type: ",type(dtstr_new))
Running the above code gives us the following result −
Given date time:
September 19 2019 21:02:23 PM
Data Type:
After converting to date time:
2019-09-19 21:02:23
Data type:
The string Date time 2019-09-19 21:02:23
Data type:
The str function will convert its parameter to a string. So here we take a datetime value by using the today function and supply it as a parameter to the str function.
 Live Demo
import datetime
print("Date time data type: \n",datetime.datetime.today())
print("Data type: \n",type(datetime.datetime.today()))
dtstr= str(datetime.datetime.today())
print("String Date time:\n ",dtstr)
print("Data type: \n",type(dtstr))
Running the above code gives us the following result −
Date time data type:
2020-05-18 11:09:40.986027
Data type:

String Date time:
2020-05-18 11:09:40.986027
Data type:
Powershell - Copy File

Copy-Item cmdlet is used to copy a file by passing the path of the file to be copied and destination path where the file is to be copied.
In this example, we'll copy a folder D:\Temp\Test Folder\Test File.txt to D:\Temp\Test Folder1
Type the following command in PowerShell ISE Console
Copy-Item 'D:\temp\Test Folder\Test File.txt' 'D:\temp\Test Folder1\Test File1.txt'
You can see the Test File1.txt in Test Folder1 with content of Test File.txt. Test Folder1 folder should be present before running this command.
In this example, we'll copy all text file recursively D:\Temp\Test Folder to D:\Temp\Test Folder1
Type the following command in PowerShell ISE Console
Copy-Item -Filter *.txt -Path 'D:\temp\Test Folder' -Recurse -Destination 'D:\temp\Test Folder1'
You can see the content of Test Folder1 in Windows Explorer where it contains both the Test Folder and only text based file(s).

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
How to convert PHP array to JavaScript or JSON ? - GeeksforGeeks

30 Sep, 2019
PHP provides a json_encode() function that converts PHP arrays into JavaScript. Technically, it is in JSON format. JSON stands for JavaScript Object Notation.
Statement: If you have a PHP array and you need to convert it into the JavaScript array so there is a function provided by PHP that will easily convert that PHP array into the JavaScript array. But before using this function you need few things that first make sure you are using PHP version 5.2 or above. Next, use the library function json_encode() to convert the PHP array to JavaScript array.
Syntax:
json_encode( $my_array );
Example 1: This example uses json_encode() function to convert PHP array to JavaScript JSON object.
<?php  // Array in php$myArr = array('Geeks', 'GeeksforGeeks@geeks.com');?>  <!-- Converting PHP array into JavaScript array --><script>var arr = <?php echo json_encode($myArr); ?>;document.write(arr[1]);</script>  <?php  ?>
Output:
GeeksforGeeks@geeks.com

Example 2: Here you will see converting single dimensional PHP array into javaScript array by using json_encode($myArr). Passing the php array and then using json_encode, we convert it into javascript array.
<?php  ?><script type='text/javascript'><?php$php_array = array('geeks', 'for', 'geeks');$js_array = json_encode($php_array);echo "var javascript_array = ". $js_array . ";\n";?>document.write(javascript_array[0]);</script>  <?php  ?>
Output:
geeks
Example 3: Here you will see converting multi-dimensional PHP array into javaScript array by using json_encode($myArr). Passing the php array and then using json_encode, we convert it into javascript array.
<?php  ?>  <script type='text/javascript'>  <?php$php_array = array(   array('Geeks', 'for@example.com'),   array('for', 'gfg@example.com'),);$js_array = json_encode($php_array);echo "var javascript_array = ". $js_array . ";\n";?>  document.write(javascript_array[0][1]);</script>  <?php  ?>
Output:
for@example.com
Note:It should be noted that json_encode() function is only available in PHP 5.2 or after versions.
Akanksha_Rai
JSON
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
Python 3 - Tkinter Relief styles

The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget. Here is a screenshot of a row of buttons exhibiting all the possible relief styles −
Here is list of possible constants which can be used for relief attribute −
FLAT
RAISED
SUNKEN
GROOVE
RIDGE
# !/usr/bin/python3
from tkinter import *
import tkinter

top = Tk()

B1 = Button(top, text = "FLAT", relief = FLAT )
B2 = Button(top, text = "RAISED", relief = RAISED )
B3 = Button(top, text = "SUNKEN", relief = SUNKEN )
B4 = Button(top, text = "GROOVE", relief = GROOVE )
B5 = Button(top, text = "RIDGE", relief = RIDGE )

B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
When the above code is executed, it produces the following result −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
HTML | <input> autofocus Attribute - GeeksforGeeks

29 Apr, 2019
The HTML <input> autofocus Attribute is used to specify that the input field must get automatically get focus when the page loads. It is a Boolean attribute.
Syntax:
<input autofocus> 
Example: This Example that illustrates the use of autofocus attribute in <input> element.
<!DOCTYPE html><html>  <head>    <title>        HTML |       <input>autofocus Attribute    </title></head>  <body style="text-align:center">      <h1 style="color: green;">         GeeksforGeeks     </h1>      <h2>         HTML |       <input>autofocus  Attribute     </h2> Name:    <input type="text" autofocus>    <br>    <br>    <!-- Assign id to the Button. -->    <button id="GFG">        Submit    </button>      <br></body>  </html>
Output:
Supported Browsers: The browser supported by HTML | <input>autofocus Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Installation of Node.js on Linux
Java - toString() Method

The method is used to get a String object representing the value of the Number Object.
If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned.
If the method takes two arguments, then a String representation of the first argument in the radix specified by the second argument will be returned.
Following are all the variants of this method −
String toString()
static String toString(int i)

Here is the detail of parameters −
i − An int for which string representation would be returned.
i − An int for which string representation would be returned.
toString() − This returns a String object representing the value of this Integer.
toString() − This returns a String object representing the value of this Integer.
toString(int i) − This returns a String object representing the specified integer.
toString(int i) − This returns a String object representing the specified integer.
public class Test { 

   public static void main(String args[]) {
      Integer x = 5;

      System.out.println(x.toString());  
      System.out.println(Integer.toString(12)); 
   }
}
This will produce the following result −
5
12


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Contained Interval in C++

Suppose we have a two-dimensional list of intervals where each interval has two values [start, end]. We have to find whether there's an interval which contains another interval.
So, if the input is like [[2,4],[5,11],[5,9],[10,10]], then the output will be true as [5,11] is containing [5,9].
To solve this, we will follow these steps −
sort the array v
sort the array v
Define one 2D array ret
Define one 2D array ret
for each interval it in v −if ret is empty, then −insert it at the end of retotherwise when last element of ret >= it[0], then −return trueOtherwiseinsert it at the end of ret
for each interval it in v −
if ret is empty, then −insert it at the end of ret
if ret is empty, then −
insert it at the end of ret
insert it at the end of ret
otherwise when last element of ret >= it[0], then −return true
otherwise when last element of ret >= it[0], then −
return true
return true
Otherwiseinsert it at the end of ret
Otherwise
insert it at the end of ret
insert it at the end of ret
return false
return false
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool static cmp(vector<int> &a, vector<int> &b) {
      return a[1] == b[1] ? a[0] > b[0] : a[1] < b[1];
   }
   bool solve(vector<vector<int>> &v) {
      sort(v.begin(), v.end(), cmp);
      vector<vector<int>> ret;
      for (auto &it : v) {
         if (ret.empty())
         ret.push_back(it);
         else if (ret.back()[0] >= it[0])
         return true;
         else
         ret.push_back(it);
      }
      return false;
   }
};
main() {
   Solution ob;
   vector<vector<int>> v = {{2,4},{5,11},{5,9},{10,10}};
   cout << (ob.solve(v));
}
{{2,4},{5,11},{5,9},{10,10}}
1
How to check whether a particular key exist in javascript object or array?

There are different ways to check for existence of an object/key in an array and an object. Let us look at the Object case first.
To look if a key exists in a object, we need to use the in operator.
let obj = {
   name: "John",
   age: 22
}
console.log('name' in obj);
console.log('address' in obj);
true
false
Note −The in operator returns true if the specified property is in the specified object or its prototype chain.
For checking if an object exists in an array, we need to use the indexOf method on the array. If the object is not found, -1 is returned, else its index is returned.
let arr = ["test", 1, 2, "hello", 23.5];
console.log(arr.indexOf({}))
console.log(arr.indexOf("hello"))
console.log(arr.indexOf(23.5))
-1
3
4
How to find MongoDB documents with a specific string?

To find documents with a specific string, use find() and in that search for a string with regex. Let us create a collection with documents −
> db.demo409.insertOne({"Name":"John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e4e515dc524f7022767c")
}
> db.demo409.insertOne({"Name":"Chris Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e4ec15dc524f7022767d")
}
> db.demo409.insertOne({"Name":"Robert Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e4f415dc524f7022767e")
}
> db.demo409.insertOne({"Name":"David Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70e4fe15dc524f7022767f")
}
Display all documents from a collection with the help of find() method −
> db.demo409.find();
This will produce the following output −
{ "_id" : ObjectId("5e70e4e515dc524f7022767c"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e70e4ec15dc524f7022767d"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e70e4f415dc524f7022767e"), "Name" : "Robert Doe" }
{ "_id" : ObjectId("5e70e4fe15dc524f7022767f"), "Name" : "David Brown" }
Following is the query to find documents with a specific string in MongoDB −
> db.demo409.find({Name: /Doe/});
This will produce the following output −
{ "_id" : ObjectId("5e70e4e515dc524f7022767c"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e70e4f415dc524f7022767e"), "Name" : "Robert Doe" }
Applications of Pointers in C/C++

We can access array elements by using pointers.
 Live Demo
#include <stdio.h>
int main() {
   int a[] = { 60, 70, 20, 40 };
   printf("%d\n", *(a + 1));
   return 0;
}
70
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a[] = { 60, 70, 20, 40 };
   cout<<*(a + 1);
   return 0;
}
70
To dynamically allocate memory we use pointers.
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
   int i, *ptr;
   ptr = (int*) malloc(3 * sizeof(int));
   if(ptr == NULL) {
      printf("Error! memory not allocated.");
      exit(0);
   }
   *(ptr+0)=1;
   *(ptr+1)=2;
   *(ptr+2)=3;
   printf("Elements are:");
   for(i = 0; i < 3; i++) {
      printf("%d ", *(ptr + i));
   }
   free(ptr);
   return 0;
}
Elements are:1 2 3
 Live Demo
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
   int i, *ptr;
   ptr = (int*) malloc(3 * sizeof(int));
   if(ptr == NULL) {
      cout<<"Error! memory not allocated.";
      exit(0);
   }
   *(ptr+0)=1;
   *(ptr+1)=2;
   *(ptr+2)=3;
   cout<<"Elements are:";
   for(i = 0; i < 3; i++) {
      cout<< *(ptr + i);
   }
   free(ptr);
   return 0;
}
Elements are:1 2 3
We can use pointers to pass arguments by reference in functions to increase efficiency.
 Live Demo
#include <stdio.h>
void swap(int* a, int* b) {
   int t= *a;
   *a= *b;
   *b = t;
}
int main() {
   int m = 7, n= 6;
   swap(&m, &n);
   printf("%d %d\n", m, n);
   return 0;
}
6 7
 Live Demo
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
   int t= *a;
   *a= *b;
   *b = t;
}
int main() {
   int m = 7, n= 6;
   swap(&m, &n);
   cout<< m<<n;
   return 0;
}
67
To implement data structures like linked list, tree we can use pointers also.
Convert an Iterator to Stream in Java

11 Dec, 2018
Given an Iterator, the task is to convert it into Stream in Java.
Examples:
Input: Iterator = {1, 2, 3, 4, 5}
Output: {1, 2, 3, 4, 5}

Input: Iterator = {'G', 'e', 'e', 'k', 's'}
Output: {'G', 'e', 'e', 'k', 's'}

Approach:
Get the Iterator.Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.Return the stream.
Get the Iterator.
Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.
Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.
Return the stream.
Below is the implementation of the above approach:
// Java program to get a Stream// from a given Iterator  import java.util.*;import java.util.stream.*;  class GFG {      // Function to get the Stream    public static <T> Stream<T>    getStreamFromIterator(Iterator<T> iterator)    {          // Convert the iterator to Spliterator        Spliterator<T>            spliterator = Spliterators                              .spliteratorUnknownSize(iterator, 0);          // Get a Sequential Stream from spliterator        return StreamSupport.stream(spliterator, false);    }      // Driver code    public static void main(String[] args)    {          // Get the Iterator        Iterator<Integer>            iterator = Arrays.asList(1, 2, 3, 4, 5)                           .iterator();          // Get the Stream from the Iterator        Stream<Integer>            stream = getStreamFromIterator(iterator);          // Print the elements of stream        stream.forEach(s -> System.out.println(s));    }}
1
2
3
4
5

Java - util package
Java-Iterator
java-stream
Java-Stream-programs
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Add image on a Tkinter button

25 Apr, 2019
Tkinter is a Python module which is used to create GUI (Graphical User Interface) applications with the help of varieties of widgets and functions. Like any other GUI module it also supports images i.e you can use images in the application to make it more attractive.
Image can be added with the help of PhotoImage() method. This is a Tkinter method which means you don’t have to import any other module in order to use it.
Important: If both image and text are given on Button, the text will be dominated and only image will appear on the Button. But if you want to show both image and text then you have to pass compound in button options.
Button(master, text = "Button", image = "image.png", compound=LEFT)
compound = LEFT -> image will be at left side of the buttoncompound = RIGHT -> image will be at right side of buttoncompound = TOP -> image will be at top of buttoncompound = BOTTOM -> image will be at bottom of button
Syntax:
photo = PhotoImage(file = "path_of_file")
path_of_file is any valid path available on your local machine.
Code #1:
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import *  # creating tkinter windowroot = Tk()  # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =(  'Verdana', 15)).pack(side = TOP, pady = 10)  # Creating a photoimage object to use imagephoto = PhotoImage(file = r"C:\Gfg\circle.png")  # here, image option is used to# set image on buttonButton(root, text = 'Click Me !', image = photo).pack(side = TOP)  mainloop()
Output:In output observe that only image is shown on the button and the size of the button is also bigger than the usual size it is because we haven’t set the size of the image. Code #2: To show both image and text on Button.
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import *  # creating tkinter windowroot = Tk()  # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =(  'Verdana', 15)).pack(side = TOP, pady = 10)  # Creating a photoimage object to use imagephoto = PhotoImage(file = r"C:\Gfg\circle.png")  # Resizing image to fit on buttonphotoimage = photo.subsample(3, 3)  # here, image option is used to# set image on button# compound option is used to align# image on LEFT side of buttonButton(root, text = 'Click Me !', image = photoimage,                    compound = LEFT).pack(side = TOP)  mainloop()
Output:Observe that both text and image are appearing as well as size of the image is also small.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
logical_or in C++

05 Sep, 2018
logical_or in C++ is a binary function object class which returns the result of the logical “or” operation between its two arguments (as returned by operator ||).
Syntax:
template  struct logical_or : binary_function  
{
  T operator() (const T& a, const T& b) const {return a||b;}
};

Parameters: (T)Type of the arguments and return type of the function call. The type shall support the operation (binary operator||).
Member types:
a: Type of the first argument in member operator()
b: Type of the second argument in member operator()
result_type: Type returned by member operator()
Below is the program to implement logical_and using std::transform():
#include <bits/stdc++.h>using namespace std;  int main(){    // First array    int z[] = { 1, 0, 1, 0 };      // Second array    int y[] = { 1, 1, 0, 0 };    int n = 4;    // Result array    int result[n];      // transform applies logical_or    // on both the array    transform(z, z + n, y,            result, logical_or<int>());      cout<< "Logical OR:\n";    for (int i = 0; i < n; i++)          // Printing the result array        cout << z[i] << " OR " << y[i]              << " = " << result[i] << "\n";    return 0;}
Logical OR:
1 OR 1 = 1
0 OR 1 = 1
1 OR 0 = 1
0 OR 0 = 0

CPP-Functions
CPP-Library
C++
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++
Unordered Sets in C++ Standard Template Library
Pair in C++ Standard Template Library (STL)
std::string class in C++
Friend class and function in C++
Queue in C++ Standard Template Library (STL)
List in C++ Standard Template Library (STL)
Inline Functions in C++
vector insert() function in C++ STL
Python program to solve quadratic equation


29 Aug, 2020

Given a quadratic equation the task is solve the equation or find out the roots of the equation. Standard form of quadratic equation is –
ax2 + bx + c
where,
a, b, and c are coefficient and real numbers and also a ≠ 0.
If a is equal to 0 that equation is not valid quadratic equation.

Examples:
Input :a = 1, b = 2, c = 1 
Output : 
Roots are real and same
-1.0

Input :a = 2, b = 2, c = 1
Output :
Roots are complex
-0.5  + i 2.0
-0.5  - i 2.0

Input :a = 1, b = 10, c = -24 
Output : 
Roots are real and different
2.0
-12.0

Method 1: Using the direct formula 
Using the below quadratic formula we can find the root of the quadratic equation.
There are following important cases.
If b*b < 4*a*c, then roots are complex
(not real).
For example roots of x2 + x + 1, roots are
-0.5 + i1.73205 and -0.5 - i1.73205

If b*b == 4*a*c, then roots are real 
and both roots are same.
For example, roots of x2 - 2x + 1 are 1 and 1

If b*b > 4*a*c, then roots are real 
and different.
For example, roots of x2 - 7x - 12 are 3 and 4
 

 
 










# Python program to find roots of quadratic equation 
import math  
  
  
# function for finding roots 
def equationroots( a, b, c):  
  
    # calculating discriminant using formula 
    dis = b * b - 4 * a * c  
    sqrt_val = math.sqrt(abs(dis))  
      
    # checking condition for discriminant 
    if dis > 0:  
        print(" real and different roots ")  
        print((-b + sqrt_val)/(2 * a))  
        print((-b - sqrt_val)/(2 * a))  
      
    elif dis == 0:  
        print(" real and same roots")  
        print(-b / (2 * a))  
      
    # when discriminant is less than 0 
    else: 
        print("Complex Roots")  
        print(- b / (2 * a), " + i", sqrt_val)  
        print(- b / (2 * a), " - i", sqrt_val)  
  
# Driver Program  
a = 1
b = 10
c = -24
  
# If a is 0, then incorrect equation 
if a == 0:  
        print("Input correct quadratic equation")  
  
else: 
    equationroots(a, b, c) 






Output:
real and different roots
2.0
-12.0

Method 2: Using the complex math module
First, we have to calculate the discriminant and then find two solution of quadratic equation using cmath module.
 

 
 










# import complex math module 
import cmath 
  
a = 1
b = 4
c = 2
  
# calculating  the discriminant 
dis = (b**2) - (4 * a*c) 
  
# find two results 
ans1 = (-b-cmath.sqrt(dis))/(2 * a) 
ans2 = (-b + cmath.sqrt(dis))/(2 * a) 
  
# printing the results 
print('The roots are') 
print(ans1) 
print(ans2) 






Output:
The roots are
(-3.414213562373095+0j)
(-0.5857864376269049+0j)


Python Cmath-library


Python math-library


Python


Python Programs

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
Java Program to Check Whether the Character is Vowel or Consonant


17 Mar, 2021

For any given character, we need to check if it is a vowel or a consonant. As we know, vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ and all the other characters (i.e. ‘b’, ‘c’, ‘d’, ‘f’ .....) are consonants.
Examples:  
Input : char = 'r'
Output : Consonant

Input : char = 'e'
Output : Vowel
Here, in the below implementation we will check if the stated character corresponds to any of the five vowels. And if it matches, “Vowel” is printed, else “Consonant” is printed.
Example 1:
Java
 

 
 










// java program to check whether input 
// character is a vowel or consonant 
  
import java.io.*; 
  
public class geek { 
  
    // Function to find whether an input 
    // character is vowel or not 
    static void Vowel_Or_Consonant(char y) 
    { 
        if (y == 'a' || y == 'e' || y == 'i' || y == 'o'
            || y == 'u') 
            System.out.println("It is a Vowel."); 
        else
            System.out.println("It is a Consonant."); 
    } 
  
    // The Driver code 
    static public void main(String[] args) 
    { 
        Vowel_Or_Consonant('b'); 
        Vowel_Or_Consonant('u'); 
    } 
}






It is a Consonant.
It is a Vowel.
Example 2:
Alteration for capital letters.
Java
 

 
 










// java program to check whether input 
// character is a vowel or consonant 
  
import java.io.*; 
  
public class geek { 
  
    // Function to find whether an input 
    // character is vowel or not 
    static void Vowel_Or_Consonant(char y) 
    { 
        if (y == 'a' || y == 'e' || y == 'i' || y == 'o'
            || y == 'u' || y == 'A' || y == 'E' || y == 'I'
            || y == 'O' || y == 'U') 
            System.out.println("It is a Vowel."); 
        else
            System.out.println("It is a Consonant."); 
    } 
  
    // The Driver code 
    static public void main(String[] args) 
    { 
        Vowel_Or_Consonant('W'); 
        Vowel_Or_Consonant('I'); 
    } 
}






It is a Consonant.
It is a Vowel.
Example 3:
indexOf() Method
Java
 

 
 










// java program to check whether input 
// character is a vowel or consonant 
  
import java.io.*; 
  
class GFG { 
    // Function to find whether an input 
    // character is vowel or not 
    static String isVowel(char ch) 
    { 
        // Make the list of vowels 
        String str = "aeiouAEIOU"; 
        return (str.indexOf(ch) != -1) ? "Vowel"
                                       : "Consonant"; 
    } 
  
    // Driver Code 
    public static void main(String[] args) 
    { 
        System.out.println("It is a " + isVowel('a')); 
        System.out.println("It is a " + isVowel('x')); 
    } 
}






It is a Vowel
It is a Consonant


java-basics


Java


Java Programs


Strings

Strings
Java
Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
How to add a list item in HTML?

The HTML <li> tag is used to add a list item is ordered, unordered, directory, and menu lists. The tag also supports the following additional attributes −
You can try to run the following code to add a list item in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML li Tag</title>
   </head>
   <body>
      <p>Rank</p>
      <ul>
         <li>India</li>
         <li>Australia</li>
         <li>South Africa</li>
      </ul>
   </body>
</html>
Lodash _.toString() Method - GeeksforGeeks

06 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.toString() method is used to convert the given value to a string. An empty string is returned for null and undefined values. The sign of the value -0 is preserved.
Syntax:
_.toString( value )
Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to convert.
Return Value: This method returns the converted string.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");        // Use of _.toString() method console.log(_.toString(-0)); console.log(_.toString(['html', 'css', 'javascript']));
Output:
'-0'
'html,css,javascript'

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");        // Use of _.toString() method  // Will print an empty stringconsole.log(_.toString(null)); console.log(_.toString([1, 2, 3]));
 Output:
''
'1,2,3'

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to read a local text file using JavaScript?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python | numpy.array_split() method - GeeksforGeeks

17 Sep, 2019
With the help of numpy.array_split() method, we can get the splitted array of having different dimensions by using numpy.array_split() method.
Syntax : numpy.array_split()
Return : Return the splitted array of one dimension.
Example #1 :In this example we can see that by using numpy.array_split() method, we are able to split the array in the number of subarrays by passing it as a parameter.
# import numpyimport numpy as np  array = np.arange(9)  # using numpy.array_split() methodgfg = np.array_split(array, 4)  print(gfg)
Output :
[array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]
Example #2 :
# import numpyimport numpy as np  array = [[1, 2, 3],         [4, 5, 6],         [7, 8, 9]]  # using numpy.array_split() methodgfg = np.array_split(array, 3)  print(gfg)
Output :
[array([[1, 2, 3]]), array([[4, 5, 6]]), array([[7, 8, 9]])]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
How to highlight a row in a table with Java Swing?

To highlight a row in a table, you can use the addRowSelectionInterval() method. At first create a table −
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
Add some columns −
tableModel.addColumn("Language/ Technology");
tableModel.addColumn("Text Tutorial");
tableModel.addColumn("Video Tutorial");
tableModel.addColumn("Views");
Now, add rows to the table −
tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "2350"});
tableModel.addRow(new Object[] { "MVC", "Yes", "No", "1500"});
tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "3400"});
tableModel.addRow(new Object[] { "F#", "Yes", "No", "7890"});
tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "10600"});
tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "4900"});
Highlight a single row by adding interval of rows. Set the same index for both the parameters since we want only a single row to be highlighted −
table.addRowSelectionInterval(4, 4);
The following is an example to highlight a row in JTable −
package my;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel();
      JTable table = new JTable(tableModel);
      tableModel.addColumn("Language/ Technology");
      tableModel.addColumn("Text Tutorial");
      tableModel.addColumn("Video Tutorial");
      tableModel.addColumn("Views");
      tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "2350"});
      tableModel.addRow(new Object[] { "MVC", "Yes", "No", "1500"});
      tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "3400"});
      tableModel.addRow(new Object[] { "F#", "Yes", "No", "7890"});
      tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "10600"});
      tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "4900"});
      tableModel.addRow(new Object[] { "AWS", "No", "Yes", "8900"});
      tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "1300"});
      tableModel.addRow(new Object[] { "Java", "Yes", "No", "9686"});
      tableModel.addRow(new Object[] { "jQuery", "Yes", "Yes", "4500"});
      tableModel.addRow(new Object[] { "Python", "Yes", "No", "6789"});
      tableModel.addRow(new Object[] { "Scala", "Yes", "No", "3400"});
      tableModel.addRow(new Object[] { "Swift", "No", "Yes", "9676"});
      table.addRowSelectionInterval(4, 4);
      table.setBackground(Color.white);
      table.setForeground(Color.BLUE);
      Font font = new Font("Verdana", Font.CENTER_BASELINE, 12);
      table.setFont(font);
      JFrame frame = new JFrame();
      frame.setSize(600, 400);
      frame.add(new JScrollPane(table));
      frame.setVisible(true);
   }
}
How to remove the label on the left side in matplotlib.pyplot pie charts?

To remove the label on the left side in a matplotlib pie chart, we can take the following steps −
Create lists of hours, activities, and colors.
Create lists of hours, activities, and colors.
Plot a pie chart using pie() method.
Plot a pie chart using pie() method.
To hide the label on the left side in matplotlib, we can use plt.ylabel("") with ablank string.
To hide the label on the left side in matplotlib, we can use plt.ylabel("") with ablank string.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
hours = [8, 1, 11, 4]
activities = ['sleeping', 'exercise', 'studying', 'working']
colors = ["grey", "green", "orange", "blue"]
plt.pie(hours, labels=activities, colors=colors, autopct="%.2f")
plt.ylabel("")
plt.show()
Unix / Linux Shell - The while Loop

The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.
while command
do
   Statement(s) to be executed if command is true
done

Here the Shell command is evaluated. If the resulting value is true, given statement(s) are executed. If command is false then no statement will be executed and the program will jump to the next line after the done statement.
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh

a=0

while [ $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9

Each time this loop executes, the variable a is checked to see whether it has a value that is less than 10. If the value of a is less than 10, this test condition has an exit status of 0. In this case, the current value of a is displayed and later a is incremented by 1.

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.6 - Show Python

#the required first parameter of the 'get' method is the 'url':
x = requests.get('https://w3schools.com/python/demopage.htm')
​
#print the response text (the content of the requested file):