code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.axes.Axes.plot() in Python

12 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library.
The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.Example:
import datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np  date1 = datetime.datetime(2000, 3, 2)date2 = datetime.datetime(2000, 3, 6)delta = datetime.timedelta(hours = 6)dates = drange(date1, date2, delta)  y = np.arange(len(dates))  fig, ax = plt.subplots()ax.plot_date(dates, y ** 2)  ax.set_xlim(dates[0], dates[-1])  ax.xaxis.set_major_locator(DayLocator())ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))ax.xaxis.set_major_formatter(DateFormatter('% Y-% m-% d'))  ax.fmt_xdata = DateFormatter('% Y-% m-% d % H:% M:% S')fig.autofmt_xdate()  plt.title("Matplotlib Axes Class Example")plt.show()
Output:
The Axes.plot() function in axes module of matplotlib library is used to plot y versus x as lines and/or markers.
Syntax: Axes.plot(self, *args, scalex=True, scaley=True, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x, y: These parameter are the horizontal and vertical coordinates of the data points. x values are optional.
fmt: This parameter is an optional parameter and it contains the string value.
data: This parameter is an optional parameter and it is an object with labelled data.
Returns: This returns the following:
lines:This returns the list of Line2D objects representing the plotted data.
Below examples illustrate the matplotlib.axes.Axes.plot() function in matplotlib.axes:
Example #1:
# Implementation of matplotlib function    import matplotlib.pyplot as pltimport numpy as np  # make an agg figurefig, ax = plt.subplots()ax.plot([1, 2, 3])ax.set_title('matplotlib.axes.Axes.plot() example 1')fig.canvas.draw()plt.show()
Output:
Example #2:
# Implementation of matplotlib function  import matplotlib.pyplot as pltimport numpy as np  # Fixing random state for reproducibilitynp.random.seed(19680801)  # create random dataxdata = np.random.random([2, 10])  # split the data into two partsxdata1 = xdata[0, :]xdata2 = xdata[1, :]  # sort the data so it makes clean curvesxdata1.sort()xdata2.sort()  # create some y data pointsydata1 = xdata1 ** 2ydata2 = 1 - xdata2 ** 3  # plot the datafig = plt.figure()ax = fig.add_subplot(1, 1, 1)ax.plot(xdata1, ydata1, color ='tab:blue')ax.plot(xdata2, ydata2, color ='tab:orange')    # set the limitsax.set_xlim([0, 1])ax.set_ylim([0, 1])  ax.set_title('matplotlib.axes.Axes.plot() example 2')  # display the plotplt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove random symbols in a dataframe in Pandas?

30 Jun, 2021
In this article, we will see how to remove random symbols in a dataframe in Pandas.
Method 1: Selecting columns
Syntax: dataframe[columns].replace({symbol:},regex=True)
First, select the columns which have a symbol that needs to be removed. And inside the method replace() insert the symbol example replace(“h”:””)
Python3
import pandas as pd  df = pd.DataFrame({'A': [1, 2, 3],                   'B': [4, 5, 6],                   'C': ['f;', 'd:', 'sda;sd'],                   'D': ['s', 'd;', 'd;p'],                   'E': [5, 3, 6],                   'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df[cols_to_check]) df[cols_to_check] = df[cols_to_check].replace({';': ''}, regex=True)print(df)
Output:
Method 2: Using dataframe.iloc
Syntax:
dataframe.iloc[].replace({character},regex=True)
In this method, you use dataframe.iloc[] to change the symbols.
Python3
import pandas as pd df = pd.DataFrame({'A': [1, 2, 3],                   'B': [4, 5, 6],                   'C': ['f;', 'd:', 'sda;sd'],                   'D': ['s', 'd;', 'd;p'],                   'E': [5, 3, 6],                   'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df.iloc[[0, 2]]) df.iloc[[0, 2]] = df.iloc[[0, 2]].replace({';': ''}, regex=True)print(df)
Output:
Method 3: Using dataframe.loc[]
Syntax:
dataframe.loc[].replace({character},regex=True)
Python3
import pandas as pd  df = pd.DataFrame({'A': [1, 2, 3],                   'B': [4, 5, 6],                   'C': ['f;', 'd:', 'sda;sd'],                   'D': ['s', 'd;', 'd;p'],                   'E': [5, 3, 6],                   'F': [7, 4, 3]}) print(df) cols_to_check = ['C', 'D', 'E']print(df.loc[:, cols_to_check])  df.loc[:, cols_to_check] = df.loc[  :, cols_to_check].replace({';': ''}, regex=True)print(df)
Output:
anikakapoor
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | json_decode() Function

09 May, 2019
The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.
Syntax:
json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )
Parameters: This function accepts four parameters as mentioned above and described below:
json: It holds the JSON string which need to be decode. It only works with UTF-8 encoded strings.
assoc: It is a boolean variable. If it is true then objects returned will be converted into associative arrays.
depth: It states the recursion depth specified by user.
options: It includes bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR.
Return values: This function returns the encoded JSON value in appropriate PHP type. If the json cannot be decoded or if the encoded data is deeper than the recursion limit then it returns NULL.
Below examples illustrate the use of json_decode() function in PHP:Example 1:
<?php  // Declare a json string$json = '{"g":7, "e":5, "e":5, "k":11, "s":19}';  // Use json_decode() function to// decode a stringvar_dump(json_decode($json));  var_dump(json_decode($json, true));  ?>
object(stdClass)#1 (4) {
  ["g"]=>
  int(7)
  ["e"]=>
  int(5)
  ["k"]=>
  int(11)
  ["s"]=>
  int(19)
}
array(4) {
  ["g"]=>
  int(7)
  ["e"]=>
  int(5)
  ["k"]=>
  int(11)
  ["s"]=>
  int(19)
}

Example 2:
<?php  // Declare a json string$json = '{"geeks": 7551119}';  // Use json_decode() function to// decode a string$obj = json_decode($json);  // Display the value of json objectprint $obj->{'geeks'};  ?>
7551119

Common Errors while using json_decode() function:
Used strings are valid JavaScript but not valid JSON.
Name and value must be enclosed in double quotes, single quotes are not allowed.
Trailing commas are not allowed.
Reference: http://php.net/manual/en/function.json-decode.php
shubham_singh
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Draw a Smiley in Java Applet

11 Mar, 2022
Given task is to draw a smiley face in Java Applet.Approach:  
Create three Ovals, one for the face, two for the eyes.Fill eyes oval with black color.Create an arc for the smile in the face.
Create three Ovals, one for the face, two for the eyes.
Fill eyes oval with black color.
Create an arc for the smile in the face.
Below is the implementation of the above approach:Applet Program: 
Java
// Java program to Draw a// Smiley using Java Appletimport java.applet.*;import java.awt.*;/*<applet code ="Smiley" width=600 height=600></applet>*/ public class Smiley extends Applet {    public void paint(Graphics g)    {         // Oval for face outline        g.drawOval(80, 70, 150, 150);         // Ovals for eyes        // with black color filled        g.setColor(Color.BLACK);        g.fillOval(120, 120, 15, 15);        g.fillOval(170, 120, 15, 15);         // Arc for the smile        g.drawArc(130, 180, 50, 20, 180, 180);    }}
Note: To run the applet in command line use the following commands  
> javac Smiley.java
> appletviewer Smiley.java
You can also refer https://www.geeksforgeeks.org/different-ways-to-run-applet-in-java to run applet program . 
sahilsulakhe3
java-applet
Technical Scripter 2018
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert list to dictionary in Python?

The list is a linear data structure containing data elements.
Example
1,2,3,4,5,6
Dictionary is a data structure consisting of key: value pairs. Keys are unique and each key has some value associated with it.
Example
1:2, 3:4, 5:6
Given a list, convert this list into the dictionary, such that the odd position elements are the keys and the even position elements are the values as depicted in the above example.
 Live Demo
def convert(l):
   dic={}
   for i in range(0,len(l),2):
      dic[l[i]]=l[i+1]

   return dic

ar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida']
print(convert(ar))
{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
Initialize an iterator to the variable i. After that zip together the key and values and typecast into a dictionary using dict().
 Live Demo
def convert(l):
   i=iter(l)
   dic=dict(zip(i,i))
   return dic

ar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida']
print(convert(ar))
{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
Pafy – Getting Dislike Count of the Video

20 Jul, 2020
In this article we will see how we can get the dislike count of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A YouTube video has a like and dislike count meter, but video owner can turn off this function any time.
We can get the pafy object with the help of new method, below is the command to get the pafy object for given video
video = pafy.new(url)
The video url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform.
In order to do this we use dislikes attribute with the pafy object of video
Syntax : video.dislikes
Argument : It takes no argument
Return : It returns integer
Below is the implementation
# importing pafyimport pafy     # url of video url = "https://www.youtube.com / watch?v = vG2PNdI8axo"    # getting videovideo = pafy.new(url)     # getting dislikes of the videovalue = video.dislikes  # printing the valueprint(value)
Output :
17

Another example
# importing pafyimport pafy     # url of video url = "https://www.youtube.com / watch?v = i6rhnSoK_gc"    # getting videovideo = pafy.new(url)   # getting dislikes of the videovalue = video.dislikes  # printing the valueprint(value)
Output :
2388

Python-Pafy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python | Check possible bijection between sequence of characters and digits

20 Jun, 2019
Given a string ‘char_seq'(sequence of characters) and a positive integer ‘dig_seq'(sequence of digits), Write a Python program to find possible bijection or one-one onto relationship between ‘char_seq’ and ‘dig_seq’ such that each character matches to one and only one digit.
Examples:
Input : char_seq = 'bxdyxb'
        dig_seq = 123421
Output : True

Input : char_seq = 'bxdyxb'
        dig_seq = 123321
Output : False

 Method #1 : Using zip method
This method simply zips the ‘char_seq’ and ‘dig_seq’ and checks if corresponding digits and characters matches or not.
# Python3 program to Check possible bijection # between sequence of characters and digits  def is_bijection(char_seq, dig_seq):    z = zip(str(char_seq), str(dig_seq))    res = all(    (z1[0] == z2[0]) == (z1[1] == z2[1]) for z1 in z for z2 in z)          return res      # Driver codechar_seq = 'bxdyxb'dig_seq = 123421print(is_bijection(char_seq, dig_seq))
True

 Method #2 : Using itertools.groupby method
This method uses the same approach with a slight difference, it uses itertools.groupby to match characters with digits.
# Python3 program to Check possible bijection # between sequence of characters and digitsimport itertools  def is_bijection(char_seq, dig_seq):    z = sorted(zip(str(char_seq), str(dig_seq)))    res = all(gx == gy          for k, g in itertools.groupby(z, key = lambda res: res[0])          for gx in g for gy in g)          return res      # Driver codechar_seq = 'bxdyxb'dig_seq = 123421print(is_bijection(char_seq, dig_seq))
True

Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Transparent window in Tkinter

19 Nov, 2020
Prerequisite: Python GUI – tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.
To create a transparent window, we will use the attributes() method.
Syntax:
root.attributes('-alpha',transparency value)


To create a transparent background, we need to use the -alpha argument in the attributes() method. The alpha is Used for transparency.
If the transparency value is 0.0 it means fully transparent, 1.0 means fully opaque The range is [0.0,1.0].  This isn’t supported on all systems, Tkinter always uses 1.0. Note that in this release, this attribute must be given as -alpha.
Below is a program that creates a normal Tkinter window.
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop()
Output:
Non-transparent Window
Now, the below program creates a transparent window using tkinter module.
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Create transparent windowroot.attributes('-alpha',0.5) # Execute tkinterroot.mainloop()
Output:
 
Transparent Window
 
abhigoya
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream of() method in Java

08 Oct, 2018
Stream of(T t) returns a sequential Stream containing a single element.Syntax :
static Stream of(T t)

Parameters: This method accepts a mandatory parameter t which is the single element in the Stream.
Return Value: Stream of(T t) returns a sequential Stream containing the single specified element.
Example :
// Java code for Stream of(T t)// to get a sequential Stream// containing a single element.  import java.util.*;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an Stream having single element only        Stream stream = Stream.of("Geeks");          // Displaying the Stream having single element        stream.forEach(System.out::println);    }}
Geeks

Stream of(T... values) returns a sequential ordered stream whose elements are the specified values.
Syntax :
static Stream of(T... values)

Parameters: This method accepts a mandatory parameter values which are the elements of the new stream.
Return Value : Stream of(T... values) returns a sequential ordered stream whose elements are the specified values.
Example:
// Java code for Stream of(T... values)// to get a sequential ordered stream whose// elements are the specified values.  import java.util.*;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an Stream        Stream stream = Stream.of("Geeks", "for", "Geeks");          // Displaying the sequential ordered stream        stream.forEach(System.out::println);    }}
Geeks
for
Geeks

Java - util package
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split a column in 2 columns using comma as separator - MySQL

For this, you can use substring_index() in MySQL. Let us create a table −
mysql> create table demo79
   -> (
   -> fullname varchar(50)
   -> );
Query OK, 0 rows affected (0.64
Insert some records into the table with the help of insert command −
mysql> insert into demo79 values("John,Smith");
Query OK, 1 row affected (0.09

mysql> insert into demo79 values("David,Miller");
Query OK, 1 row affected (0.11

mysql> insert into demo79 values("Chris,Brown");
Query OK, 1 row affected (0.07
Display records from the table using select statement −
mysql> select *from demo79;
This will produce the following output −
+--------------+
| fullname     |
+--------------+| John,Smith   |
| David,Miller || Chris,Brown  |
+--------------+3 rows in set (0.00 sec)
+--------------+
| David,Miller |
+--------------+
Following is the query to split a column in 2 columns using comma as separator −
mysql> select
   -> fullname,
   -> substring_index(fullname, ',', 1) First_Name,
   -> substring_index(fullname, ',', -1) Last_Name
   -> from demo79;
This will produce the following output −
| fullname     | First_Name | Last_Name |+--------------+------------+-----------+
| John,Smith   | John       | Smith     || David,Miller | David      | Miller    |
| Chris,Brown  | Chris      | Brown     |+--------------+------------+-----------+
3 rows in set (0.00 sec)
| fullname     | First_Name | Last_Name |
| John,Smith   | John       | Smith     |
| Chris,Brown  | Chris      | Brown     |
3 rows in set (0.00 sec)
Simple Genetic Algorithm (SGA)

07 Apr, 2021
Prerequisite – Genetic Algorithm
Introduction :
Simple Genetic Algorithm (SGA) is one of the three types of strategies followed in Genetic algorithm.
SGA starts with the creation of an initial population of size N.Then, we evaluate the goodness/fitness of each of the solutions/individuals.
SGA starts with the creation of an initial population of size N.
Then, we evaluate the goodness/fitness of each of the solutions/individuals.
After that, the convergence criterion is checked, if it meets then we converge the algorithm otherwise go for the next steps –
Select Np individuals from the previous population.Create the mating pool randomly.Perform Crossover.Perform Mutation in offspring solutions.Perform inversion in offspring solutions.Replace the old solutions of the last generation with the newly created solutions and go to step (2).
Select Np individuals from the previous population.
Create the mating pool randomly.
Perform Crossover.
Perform Mutation in offspring solutions.
Perform inversion in offspring solutions.
Replace the old solutions of the last generation with the newly created solutions and go to step (2).
Simple Genetic Algorithm Block Diagram
Important Parameters while solving problems in Simple Genetic Algorithm : 
Initial Population NMating pool size NpConvergence thresholdCrossoverMutationInversion
Initial Population N
Mating pool size Np
Convergence threshold
Crossover
Mutation
Inversion
Features :
Computationally Expensive
Biased towards more highly fit individuals
Performs well when the initial population is large enough.
Applications :
Learning robot behaviour using Simple Genetic Algorithm.
In the finance industry.
Neural networks.
Soft computing Applications like Fuzzy logic, Neurocomputing.
Optimization problems.
Genetic Algorithms
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UInt32.MaxValue Field in C# with Examples

01 May, 2019
The MaxValue field of UInt32 Struct is used to represent the maximum value of the 32-bit unsigned integer. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 4294967295. Its hexadecimal value is 0xFFFFFFFF. It is used to avoid the OverflowException at run-time by verifying that an Int64 value is within the range of the UInt32 type before a type conversion.
Syntax:
public const uint MaxValue = 4294967295;
Return Value: This field always returns 4294967295.
Example:
// C# program to illustrate the// UInt32.MaxValue fieldusing System;  class GFG {      // Main Method    static public void Main()    {        // display the Maximum value        // of UInt32 struct        Console.WriteLine("Maximum Value is: " + UInt32.MaxValue);           // Taking an array of the         // unsigned long integer         // i.e UInt64 data type        ulong[] num = {3422146, 732443, 42343535776, 2342534654756123};          // taking variable of UInt32 type        uint mynum;          foreach(long n in num)        {              if (n >= UInt32.MinValue && n <= UInt32.MaxValue)             {                  // using the method of Convert class                // to convert Int64 to UInt32                mynum = Convert.ToUInt32(n);                  Console.WriteLine("Conversion is Possible.");            }              else            {                Console.WriteLine("Not Possible");            }        }    }}
Output:
Maximum Value is: 4294967295
Conversion is Possible.
Conversion is Possible.
Not Possible
Not Possible

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.uint32.maxvalue?view=netstandard-2.1
CSharp-UInt32-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
How to Find Standard Deviation in R?

07 Apr, 2021
In this article, we will discuss how to find the Standard Deviation in R Programming Language. Standard deviation is the measure of the dispersion of the values. It can also be defined as the square root of variance.
Formula of sample standard deviation:
where, 
s = sample standard deviation
N = Number of entities
 = Mean of entities
Basically, there are two different ways to calculate standard Deviation in R Programming language, both of them are discussed below.
In this method of calculating the standard deviation, we will be using the above standard formula of the sample standard deviation in R language. 
Example 1:
R
v <- c(12,24,74,32,14,29,84,56,67,41)  s<-sqrt(sum((v-mean(v))^2/(length(v)-1)))  print(s)
Output:
[1] 25.53886
Example 2:
R
v <- c(1.8,3.7,9.2,4.7,6.1,2.8,6.1,2.2,1.4,7.9)  s<-sqrt(sum((v-mean(v))^2/(length(v)-1)))  print(s)
Output:
[1] 2.676004
The sd() function is used to return the standard deviation.
Syntax: sd(x, na.rm = FALSE)
Parameters:
x: a numeric vector, matrix or data frame.
na.rm: missing values be removed?
Return: The sample standard deviation of x.
Example 1:
R
v <- c(12,24,74,32,14,29,84,56,67,41)  s<-sd(v)  print(s)
Output:
[1] 25.53886
Example 2:
R
v <- c(71,48,98,65,45,27,39,61,50,24,17)  s1<-sqrt(sum((v-mean(v))^2/(length(v)-1)))print(s1)  s2<-sd(v)print(s2)
Output:
[1] 23.52175
Example 3:
R
v <- c(1.8,3.7,9.2,4.7,6.1,2.8,6.1,2.2,1.4,7.9)  s1<-sqrt(sum((v-mean(v))^2/(length(v)-1)))print(s1)  s2<-sd(v)print(s2)
Output:
[1] 2.676004
Picked
R-Mathematics
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
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?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Python - Rename column names by index in a Pandas DataFrame without using rename()

We can easily rename a column by index i.e. without using rename(). Import the required library −
import pandas as pd
Create a DataFrame with 3 columns −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130]
   }
)
Let us now rename all the columns using columns.values[0[ by setting the index of the column to be changed in the square brackets −
dataFrame.columns.values[0] = "Car Names"
dataFrame.columns.values[1] = "Registration Cost"
dataFrame.columns.values[2] = "Units_Sold"
Following is the code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130]
   }
)

print"DataFrame ...\n",dataFrame

# Renaming columns name
dataFrame.columns.values[0] = "Car Names"
dataFrame.columns.values[1] = "Registration Cost"
dataFrame.columns.values[2] = "Units_Sold"

print"\nUpdated DataFrame with new column names...\n",dataFrame
This will produce the following output −
DataFrame ...
        Car   Reg_Price   Units
0       BMW       7000      90
1     Lexus       1500     120
2     Tesla       5000     100
3   Mustang       8000     150
4  Mercedes       9000     200
5    Jaguar       6000     130

Updated DataFrame with new column names...
   Car Names   Registration Cost   Units_Sold
0       BMW                7000           90
1     Lexus                1500          120
2     Tesla                5000          100
3   Mustang                8000          150
4  Mercedes                9000          200
5    Jaguar                6000          130
Comb Sort

The basic idea of comb sort and the bubble sort is same. In other words, comb sort is an improvement on the bubble sort. In the bubble sorting technique, the items are compared with the next item in each phase. But for the comb sort, the items are sorted in a specific gap. After completing each phase, the gap is decreased. The decreasing factor or the shrink factor for this sort is 1.3. It means that after completing each phase the gap is divided by 1.3.
Time Complexity: O(n log n) for the best case. O(n^2/2^p) (p is a number of increment) for average case and O(n^2) for the worst case.
Space Complexity: O(1)
Input:
A list of unsorted data: 108 96 23 74 12 56 85 42 13 47
Output:
Array before Sorting: 108 96 23 74 12 56 85 42 13 47
Array after Sorting: 12 13 23 42 47 56 74 85 96 108
CombSort(array, size)
Input − An array of data, and the total number in the array
Output − The sorted Array
Begin
   gap := size
   flag := true
   while the gap ≠ 1 OR flag = true do
      gap = floor(gap/1.3) //the the floor value after division
      if gap < 1 then
         gap := 1
      flag = false

      for i := 0 to size – gap -1 do
         if array[i] > array[i+gap] then
            swap array[i] with array[i+gap]
            flag = true;
      done
   done
End
#include<iostream>
#include<algorithm>
using namespace std;

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

void combSort(int *array, int size) {
   int gap = size; //initialize gap size with size of array
   bool flag = true;

   while(gap != 1 || flag == true) {
      gap = (gap*10)/13; //minimize gap by shrink factor
      if(gap<1)
         gap = 1;
      flag = false;

      for(int i = 0; i<size-gap; i++) { //compare elements with gap
         if(array[i] > array[i+gap]) {
            swap(array[i], array[i+gap]);
            flag = true;
         }
      }
   }
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   combSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 10
Enter elements:
108 96 23 74 12 56 85 42 13 47
Array before Sorting: 108 96 23 74 12 56 85 42 13 47
Array after Sorting: 12 13 23 42 47 56 74 85 96 108
How to Install Selenium WebDriver on MacOS?

21 Sep, 2021
In this article, we will learn how to install Selenium WebDriver in Python on macOS. Selenium WebDriver is a web framework that permits you to execute cross-browser tests. This tool is used for automating web-based application testing to verify that it performs expectedly.
Follow the below steps to install Selenium WebDriver on macOS:
Step 1: Install the latest Python3 in MacOS
Step 2: Download and install the latest Chrome and check your Chrome version from “chrome://settings/help“
Step 3: Download the Chrome WebDriver Zip File matching with your Chrome version and Apple Chip from here and extract the chromedriver.
Step 4: Copy the chromedriver and paste it to “/usr/local/bin” (If this folder doesn’t exist then create one)
Step 5: Open a terminal inside the bin folder and run the following command so that MacOS can verify the app.
xattr -d com.apple.quarantine chromedriver
Step 6: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 7: Install selenium library via pip.
pip3 install selenium
Run the python code below in your system and it should open up “https://geeksforgeeks.org” in your chrome browser automatically.
Python3
from selenium import webdriverimport time  # Main Functionif __name__ == '__main__':      options = webdriver.ChromeOptions()    options.add_argument("--start-maximized")    options.add_argument('--log-level=3')      # Provide the path of chromedriver present on your system.    driver = webdriver.Chrome(executable_path="chromedriver",                              chrome_options=options)    driver.set_window_size(1920,1080)      # Send a get request to the url    driver.get('https://www.geeksforgeeks.org/')    time.sleep(60)    driver.quit()    print("Done")
Browser Output:
Chrome Browser
Terminal Output:
Terminal
Blogathon-2021
how-to-install
Picked
Python-selenium
Blogathon
How To
Installation Guide
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | gmdate() Function

05 Jul, 2018
The gmdate() is an inbuilt function in PHP which is used to format a GMT/UTC date and time and return the formatted date strings. It is similar to the date() function but it returns the time in Greenwich Mean Time (GMT).
Syntax:
string gmdate ( $format, $timestamp )
Parameters: The gmdate() function accepts two parameters as mentioned above and described below:
$format: It is a mandatory parameter which specifies the format of returned date and time.
$timestamp: Timestamp is an optional parameter, if it is not included then current date and time will be used.
Return Value: This function Returns a formatted date string on success and FALSE on failure and an E_WARNING.
Below programs illustrate the gmdate() function.
Program 1:
<?php// PHP program to illustrate gmdate function  // display date Jun 25 2018 23:21:50echo gmdate("M d Y H:i:s",        mktime(23, 21, 50, 6, 25, 2018)) ."\n";  // display date  World Wide Web Consortium// 2018-06-25T23:21:50+00:00echo gmdate(DATE_W3C,        mktime(23, 21, 50, 6, 25, 2018)). "\n";    // display date as ISO-8601 formatecho gmdate(DATE_ISO8601,        mktime(23, 21, 50, 6, 25, 2018)). "\n";          ?>
Jun 25 2018 23:21:50
2018-06-25T23:21:50+00:00
2018-06-25T23:21:50+0000

Program 2: Passing one parameter, then it will return the current local time (time()).
<?php// PHP program to illustrate gmdate function  // display current date and time // Jun 28 2018 14:52:50echo gmdate("M d Y H:i:s") ."\n";  // display date  World Wide Web Consortiumecho gmdate(DATE_W3C). "\n";    // display date as ISO-8601 formatecho gmdate(DATE_ISO8601). "\n";          ?>
Jun 29 2018 06:32:34
2018-06-29T06:32:34+00:00
2018-06-29T06:32:34+0000

Similar Article:
PHP | Date and Time
PHP | time() Function
Reference: http://php.net/manual/en/function.gmdate.php
PHP-date-time
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.str.encode()

27 Mar, 2019
Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.encode() function is used to encode character string in the Series/Index using indicated encoding. Equivalent to str.encode().
Syntax: Series.str.encode(encoding, errors=’strict’)
Parameter :encoding : strerrors : str, optional
Returns : encoded : Series/Index of objects
Example #1: Use Series.str.encode() function to encode the character strings present in the underlying data of the given series object. Use ‘raw_unicode_escape’ for encoding.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich'])  # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.encode() function to encode the character strings present in the underlying data of the given series object.
# use 'raw_unicode_escape' encodingresult = sr.str.encode(encoding = 'raw_unicode_escape')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.encode() function has successfully encoded the strings in the given series object.
Example #2 : Use Series.str.encode() function to encode the character strings present in the underlying data of the given series object. Use ‘punycode’ for encoding.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney'])  # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.encode() function to encode the character strings present in the underlying data of the given series object.
# use 'punycode' encodingresult = sr.str.encode(encoding = 'punycode')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.encode() function has successfully encoded the strings in the given series object.
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are reserved keywords in C#?

Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers. If you want to use these keywords as identifiers, you may prefix the keyword with the @ character.
In C#, some identifiers have special meaning in the context of code, such as get and set are called contextual keywords.
The following table lists the reserved keywords −
Let us see an example of using bool reserved keyword in C# −
 Live Demo
using System;
using System.Collections;

class Demo {
   static void Main() {
      bool[] arr = new bool[5];
      arr[0] = true;
      arr[1] = true;
      arr[2] = false;
      arr[3] = false;

      BitArray bArr = new BitArray(arr);

      foreach (bool b in bArr) {
         Console.WriteLine(b);
      }

      bool str = arr[1];
      Console.WriteLine("Value of 2nd element:"+str);
   }
}
True
True
False
False
False
Value of 2nd element:True
Python | Check if any element occurs n times in given list

08 Sep, 2020
Given a list, the task is to find whether any element occurs ‘n’ times in given list of integers. It will basically check for the first element that occurs n number of times. Examples:  
Input: l =  [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3
Output :  2

Input: l =  [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4
Output :  1



Below are some methods to do the task in Python – Method 1: Using Simple Iteration and Sort  
Python3
# Python code to find occurrence of any element# appearing 'n' times # Input Initialisationinput = [1, 2, 3, 0, 4, 3, 4, 0, 0] # Sort Inputinput.sort() # Constants Declarationn = 3prev = -1count = 0flag = 0 # Iteratingfor item in input:    if item == prev:        count = count + 1    else:        count = 1    prev = item         if count == n:        flag = 1        print("There are {} occurrences of {} in {}".format(n, item, input))        break # If no element is not found.if flag == 0:    print("No occurrences found")
Output :  
There are 3 occurrences of 0 in [0, 0, 0, 1, 2, 3, 3, 4, 4]


  Method 2: Using Count 
Python3
# Python code to find occurrence of any element# appearing 'n' times # Input list initialisationinput = [1, 2, 3, 4, 0, 4, 3, 4] # Constant declarationn = 3 # printprint("There are {} occurrences of {} in {}".format(input.count(n), n, input))
Output :  
There are 2 occurrences of 3 in [1, 2, 3, 4, 0, 4, 3, 4]


  Method 3: Using defaultdictWe first populate item of list in a dictionary and then we find whether count of any element is equal to n. 
Python3
# Python code to find occurrence of any element# appearing 'n' times # importingfrom collections import defaultdict # Dictionary declarationdic = defaultdict(int) # Input list initialisationInput = [9, 8, 7, 6, 5, 9, 2] # Dictionary populatefor i in Input:    dic[i]+= 1 # constant declarationn = 2flag = 0 # Finding from dictionaryfor element in Input:    if element in dic.keys() and dic[element] == n:        print("Yes, {} has {} occurrence in {}.".format(element, n, Input))        flag = 1        break # if element not found.if flag == 0:    print("No occurrences found")
Output :  
Yes, 9 has 2 occurrence in [9, 8, 7, 6, 5, 9, 2]


 
alukas07
askudlarek
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How to submit a form on Enter button using jQuery ?

18 Aug, 2020
Given an HTML form and the task is to submit the form after clicking the ‘Enter’ button using jQuery. To submit the form using ‘Enter’ button, we will use jQuery keypress() method and to check the ‘Enter’ button is pressed or not, we will use ‘Enter’ button key code value.
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <script src="https://code.jquery.com/jquery-3.5.1.min.js"integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="         crossorigin="anonymous">    </script>    <meta name="viewport" content=        "width=device-width, initial-scale=1.0"></head>  <body>    <h3 style="color: green;font-size: 28px;">        GeeksforGeeks    </h3>      <form class="info">        <input name="fname" /><br>        <input name="lname" /><br>        <button type="submit">Submit</button>    </form></body>  </html>
JavaScript Code:
<script>      // Wait for document to load    $(document).ready(() => {        $('.info').on('submit', () => {              // prevents default behaviour            // Prevents event propagation            return false;        });    });    $('.info').keypress((e) => {          // Enter key corresponds to number 13        if (e.which === 13) {            $('.info').submit();            console.log('form submitted');        }    })</script>
Explanation:We use the jQuery event.which to check the keycode on the keypress. The keycode for the enter key is 13, so if the keycode matches to thirteen then we use the .submit() method on the form element to submit the form.
Complete Code:
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <script src="https://code.jquery.com/jquery-3.5.1.min.js"        integrity=        "sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="         crossorigin="anonymous">    </script>    <meta name="viewport" content=        "width=device-width, initial-scale=1.0"></head>  <body>    <h3 style="color: green;font-size: 28px;">        GeeksforGeeks    </h3>    <form class="info">        <input name="fname" /><br><br>        <input name="lname" /><br><br>        <button type="submit">Submit</button>    </form>      <script>        $(document).ready(() => {            $('.info').on('submit', () => {                return false;            });        });        $('.info').keypress((e) => {            if (e.which === 13) {                $('.info').submit();                alert('Form submitted successfully.')            }        })    </script></body>  </html>
Output:
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Plot Multiple Columns of Pandas Dataframe on Bar Chart with Matplotlib

24 Jan, 2021
Prerequisites: 
Pandas
Matplotlib
In this article, we will learn how to plot multiple columns on bar chart using Matplotlib. Bar Plot is used to represent categories of data using rectangular bars. We can plot these bars with overlapping edges or on same axes. Different ways of plotting bar graph in the same chart are using matplotlib and pandas are discussed below.
The trick here is to pass all the data that has to be plotted together as a value to ‘y’ parameter of plot function.
Syntax: 
matplotlib.pyplot.plot(\*args, scalex=True, scaley=True, data=None, \*\*kwargs) 
Approach:
Import module 
Create or load data
Pass data to plot()
Plot graph
Example:
Python3
# importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt  # creating dataframedf = pd.DataFrame({    'Name': ['John', 'Sammy', 'Joe'],    'Age': [45, 38, 90],    'Height(in cm)': [150, 180, 160]})  # plotting graphdf.plot(x="Name", y=["Age", "Height(in cm)"], kind="bar")
Output:
Plotting all separate graph on the same axes, differentiated by color can be one alternative. Here again plot() function is employed.
Approach:
Import module
Create or load data
Plot first graph
Plot all other graphs on the same axes 
Example:
Python3
# importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt  # creating dataframedf = pd.DataFrame({    'Name': ['John', 'Sammy', 'Joe'],    'Age': [45, 38, 90],    'Height(in cm)': [150, 180, 160]})  # plotting Heightax = df.plot(x="Name", y="Height(in cm)", kind="bar")# plotting age on the same axisdf.plot(x="Name", y="Age", kind="bar", ax=ax, color="maroon")
Output:
Another way of creating such a functionality can be plotting multiple subplots and displaying them as one. This can be done using subplot() function.
Syntax:
subplot(nrows, ncols, index, **kwargs)
Approach:
Import module
Create or load data
Create multiple subplots 
Plot on single axes
Example:
Python3
# importing pandas libraryimport pandas as pd# import matplotlib libraryimport matplotlib.pyplot as plt  # creating dataframedf = pd.DataFrame({    'Name': ['John', 'Sammy', 'Joe'],    'Age': [45, 38, 90],    'Height(in cm)': [150, 180, 160]})  # creating subplots and plotting them togetherax = plt.subplot()ax.bar(df["Name"], df["Height(in cm)"])ax.bar(df["Name"], df["Age"], color="maroon")
Output:
Picked
Python-matplotlib
Python-pandas
Technical Scripter 2020
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Select Only Numeric Columns from DataFrame in R

23 Sep, 2021
In this article, we will discuss how to select only numeric columns from dataframe in R Programming Language.
We can use select_if() function to get numeric columns by calling the function with the dataframe name and isnumeric() function that will check for numeric columns.
Syntax:
select_if(dataframe, is.numeric)
where,
dataframe is the input dataframe
is.numeric is sued to get the numeric columns
Example: R program to get numeric columns from dataframe using dplyr
R
# load the package dplyrlibrary("dplyr")  # create  a dataframe with 4 columns and 3 rowsdata=data.frame("webtechnologies"=c("php","html","js"),                 marks=c(98,89,90),                age=c(12,23,21),                name=c("bobby","ojaswi","ramya"))        # get numeric columns using dplyr() function             print(select_if(data, is.numeric))
Output:
Example: R program to get numeric columns from dataframe using dplyr
R
# load the package dplyrlibrary("dplyr")  # create  a dataframe with 4 columns and 3 rowsdata=data.frame(id=c(1,2,3),                 marks=c(98,89,90),                age=c(12,23,21),                name=c("bobby","ojaswi","ramya"))        # get numeric columns using dplyr() function             print(select_if(data, is.numeric))
Output:
we will use lapply() function to get the numeric columns. Here, lapply() function is called with unlist() and the dataframe name and isnumeric() function are passed to it as parameters.
Syntax:
unlist(lapply(dataframe, is.numeric))
where,
dataframe is the input dataframe
is.numeric is used to check each dataframe column is numeric or not
unlist function is used to unlist the dataframe
Finally, pass this lapply() to the dataframe index
Syntax:
dataframe[,unlist(lapply(data, is.numeric))]
Where, dataframe is the input dataframe
Example: R program to get numeric columns from dataframe using base R
R
# create  a dataframe with 4 columns and 3 rowsdata=data.frame(id=c(1,2,3),                 marks=c(98,89,90),                age=c(12,23,21),                name=c("bobby","ojaswi","ramya"))        # get numeric columns using dplyr() function             print(data[,unlist(lapply(data, is.numeric))])
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Creating a Simple Chat with netcat in Linux

02 Feb, 2021
Firstly, We should know that what is netcat, which is also known as TCP/IP swiss army knife a feature-rich network utility. netcat can do port scanning, transfer files, create a listener, or stream media, and many more. The netcat utility program supports a wide range of commands to manage networks and monitor the flow of traffic data between systems.
Install netcat in Linux:
sudo apt-get install netcat
Compile Netcat From Source:
1. Download Netcat from an official source
2. To decompress it run the following command,
gunzip netcat-0.7.1.tar.gz
Here, “netcat-0.7.1.tar.gz” is the name of the file.
3. untar the file.
tar -xf netcat-0.7.1.tar
4. Change the directory.
cd netcat-0.7.1 / 
5. by using the command configure the source code.
./configure
6. Compile the program by using.
make
7. Now install it.
make install
We will follow these steps for configuring a chat.
Steps 1: To create a simple chat you need two devices, d1 and d2.
Step 2: Open a terminal in Linux and install Netcat on both devices.
Step 3: type $ifconfig in d1 and note down your localhost IP address, ifconfig is used to get our device’s IP address.
Step 4: Now in d1 run command $nc -nvlp 1234 where “1234” is port number, d1 will now act as a listener.
Where:
-n: nodns, Do not resolve hostname vis DNS
-v: verbose, set verbosity level
-l: listener, binds and listen for incoming connection
-p: source-port port, Specify source port to use
Step 5: in d2 type $nc <localhost IP> 1234 and hit enter.
Step 6: Simple chat is now created.
Picked
Technical Scripter 2020
Linux-Unix
Technical Scripter
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
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting