code-rag-bench/online-tutorials huggingface dataset:
How to prevent Cloning to break a Singleton Class Pattern?

A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below −
public class Tester{
   public static void main(String[] args)
   throws CloneNotSupportedException {
      A a = A.getInstance();
      A b = (A)a.clone();

      System.out.println(a.hashCode());
      System.out.println(b.hashCode());
   }
}

class A implements Cloneable {
   private static A a;
   private A(){}

   public static A getInstance(){
      if(a == null){
         a = new A();
      }
      return a;
   }

   @Override
   protected Object clone()
   throws CloneNotSupportedException {
      return super.clone();
   }
}
705927765
366712642
Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −
Return the same object in the clone method as well.
@Override
protected Object clone()
throws CloneNotSupportedException {
   return getInstance();
}
705927765
705927765
Capitalize first letter of a column in Pandas dataframe - GeeksforGeeks

06 Dec, 2018
Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important.
One might encounter a situation where we need to capitalize any specific column in given dataframe. Let’s see how can we capitalize first letter of a column in Pandas dataframe.
Let’s create a dataframe from the dict of lists.
# Create a simple dataframe   # importing pandas as pdimport pandas as pd     # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'],                  'B': ['masters', 'graduate', 'graduate',                                   'Masters', 'Graduate'],                  'C': [27, 23, 21, 23, 24]})   df
Output:
There are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we capitalize first letter of columns using capitalize() method.
Method #1:
# Create a simple dataframe   # importing pandas as pdimport pandas as pd     # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'],                  'B': ['masters', 'graduate', 'graduate',                                   'Masters', 'Graduate'],                  'C': [27, 23, 21, 23, 24]})   df['A'] = df['A'].str.capitalize()  df
Output: Method #2: Using lambda with capitalize() method
# Create a simple dataframe   # importing pandas as pdimport pandas as pd     # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'],                  'B': ['masters', 'graduate', 'graduate',                                   'Masters', 'Graduate'],                  'C': [27, 23, 21, 23, 24]})   df['A'].apply(lambda x: x.capitalize())
Output:
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
HTML | <iframe> marginwidth Attribute - GeeksforGeeks

07 Nov, 2019
The HTML <iframe> margin width Attribute is used to specifies the left and right margin of the content in an Iframe Element.
Syntax:
<iframe marginwidth="pixels">
Attribute Values:
pixels: It contains the value i.e pixel which specifies the right and left a margin of the content in an Iframe Element.
Note: This attribute is not supported in HTML 5, as a replacement you can use CSS.Below example illustrate the <iframe> marginwidth Attribute:Example:
<!DOCTYPE html><html><head>    <title>     HTML <iframe> marginwidth Attribute    </title></head><body>    <center>        <h1 style="color:green;">          GeeksforGeeks        </h1>        <h2>        HTML Iframe marginwidth Attribute    </h2>          <p>Content goes here</p>          <iframe src="https://ide.geeksforgeeks.org/tryit.php"                 height="200"                width="400"                marginwidth="50">        </iframe>  </center>  </body>  </html>
Output:
Supported Browsers: The browsers supported by HTML <iframe> marginwidth 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.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Default value of Vector in C++ STL - GeeksforGeeks

23 Apr, 2020
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. By default, the size of the vector automatically changes when appending elements.
To initialize the map with a random default value below is the approach:Approach:
Declare a vector.Set the size of the vector to the user defined size N
Declare a vector.
Set the size of the vector to the user defined size N
Default value of the Vector:
The default value of a vector is 0.
Syntax:
// For declaring 
vector v1(size); 

// For Vector with default value 0
vector v1(5);

Below is the implementation of the above approach:
// C++ program to create an empty// vector with default value  #include <bits/stdc++.h>using namespace std;  int main(){    int n = 3;      // Create a vector of size n with    // all values as 0.    vector<int> vect(n);      for (int x : vect)        cout << x << " ";      return 0;}
0 0 0

Specifying a default value for the Vector:
We can also specify a random default value for the vector. Inorder to do so, below is the approach:
Syntax:
// For declaring 
vector v(size, default_value);

// For Vector with a specific default value
// here 5 is the size of the vector
// and  10 is the default value
vector v1(5, 10);

Below is the implementation of the above approach:
// C++ program to create an empty vector// and with a specific default value  #include <bits/stdc++.h>using namespace std;  int main(){    int n = 3;    int default_value = 10;      // Create a vector of size n with    // all values as 10.    vector<int> vect(n, default_value);      for (int x : vect)        cout << x << " ";      return 0;}
10 10 10

cpp-vector
C++
C++ Programs
Write From Home
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL
How to Compress and Extract Files Using the tar Command on Linux - GeeksforGeeks

29 Jun, 2021

An archive is a special file that contains any number of files inside. It can be restored via special programs, for example, tar.inside.
.tar – archive files are usually not compressed.
.tar.gz – archive file compressed with gzip tool
.tar.bz2 – archive file compressed with bzip2 tool
Syntax: 
tar options [archive_name.tar] files_to_archive
The tar command does not create a compressed archive, instead, it uses external utilities like gzip and bzip2.
Command functionality:
–diff
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
–delete
Showing the difference between archives
Delete file from the archive
Command parameters:
–verbose
–total
Show process information
Show final result 
1) Compress one file using the tar command:
tar -czvf one-file-compressed.tar.gz hello_world
2) Compress directory using the tar command:
tar -czvf dir-compressed.tar.gz test_directory/
3) Show the archive content:
tar -tf archive.tar.gz
4) Add content to the existing archive:
tar -rvf existing-archive-name.tar file-directory-to-compress/
5) Update content in an archive: 
6) Compress with bzip2:
tar -cjvf one-file-compressed.tar.bz2 hello_world
7) Extract files from a .tar archive:
tar -xf archive.tar.gz
The same with .tar.gz and .tar.bz2

Linux-file-commands


Picked


Linux-Unix

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
C# | Count the number of key/value pairs in the Hashtable - GeeksforGeeks

01 Feb, 2019
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Count Property is used to get the total number of the key/value pairs contained in the Hashtable.
Syntax:
myTable.Count

Here, myTable is the name of the Hashtable.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to get the number of key-and-value// pairs contained in the Hashtable.using System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Hashtable        Hashtable myTable = new Hashtable();          // Adding elements in Hashtable        myTable.Add("2", "Even & Prime");        myTable.Add("3", "Odd & Prime");        myTable.Add("4", "Even & non-prime");        myTable.Add("9", "Odd & non-prime");          // To get the number of key-and-value        // pairs contained in the Hashtable.        Console.WriteLine(myTable.Count);    }}
4

Example 2:
// C# code to get the number of key-and-value// pairs contained in the Hashtable.using System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating an empty Hashtable        Hashtable myTable = new Hashtable();          // To get the number of key-and-value        // pairs contained in the Hashtable.        Console.WriteLine(myTable.Count);    }}
0

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.count?view=netframework-4.7.2
CSharp-Collections-Hashtable
CSharp-Collections-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
C# | Arrays
Python | Pandas Series.nbytes - GeeksforGeeks

28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.nbytes attribute is return the number of bytes required to store the underlying data in the given Series object.
Syntax:Series.nbytes
Parameter : None
Returns : number of bytes
Example #1: Use Series.nbytes attribute is used to find the number of bytes required to store the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])  # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # Print the seriesprint(sr)
Output :
Now we will use Series.nbytes attribute to find the number of bytes required to store the underlying data of the given Series object.
# return the number of bytessr.nbytes
Output :
As we can see in the output, the Series.nbytes attribute has returned 40 indicating that the memory needed to store the given series object is 40 bytes. Example #2 : Use Series.nbytes attribute is used to find the number of bytes required to store the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018'])  # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4']  # Print the seriesprint(sr)
Output :
Now we will use Series.nbytes attribute to find the number of bytes required to store the underlying data of the given Series object.
# return the number of bytessr.nbytes
Output :As we can see in the output, the Series.nbytes attribute has returned 32 indicating that the memory needed to store the given series object is 32 bytes.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
File Handling in C#

A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.
In C#, you need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows −
FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>,
<FileAccess Enumerator>, <FileShare Enumerator>);
Here, the file operations are also included as shown below −
The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are −
Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
Create − It creates a new file.
Create − It creates a new file.
CreateNew − It specifies to the operating system, that it should create a new file.
CreateNew − It specifies to the operating system, that it should create a new file.
Open − It opens an existing file.
Open − It opens an existing file.
OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
Truncate − It opens an existing file and truncates its size to zero bytes.
Truncate − It opens an existing file and truncates its size to zero bytes.
FileAccess − The FileAccess enumerators have members: Read, ReadWrite and Write.
FileShare − The FileShare enumerators have the following members −
Inheritable − It allows a file handle to pass inheritance to the child processes
Inheritable − It allows a file handle to pass inheritance to the child processes
None − It declines sharing of the current file
None − It declines sharing of the current file
Read − It allows opening the file for readin.
Read − It allows opening the file for readin.
ReadWrite − It allows opening the file for reading and writing
ReadWrite − It allows opening the file for reading and writing
Write− It allows opening the file for writing
Write− It allows opening the file for writing
Let us see an example to get the directories.
//creating a DirectoryInfo object
DirectoryInfo mydir = new DirectoryInfo(@"d:\Demo");

// getting the files in the directory, their names and size
FileInfo [] f = mydir.GetFiles();

foreach (FileInfo file in f) {
   Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length);
}
Style options for the HTML5 Date picker

The date picker in HTML5 basically works very similar to how the JavaScript Libraries did, when we focus on the field a calendar will pop out, and then we can navigate through the months and years to select the date.
Therefore, if you want the date input to use more spacing and a color scheme you could add the following to your code.
::-webkit-datetime-edit { padding: 2 em; }
::-webkit-datetime-edit-fields-wrapper { background:green; }
::-webkit-datetime-edit-text { color: blue; padding: 0 0.3em; }
::-webkit-datetime-edit-month-field { color: red; }
::-webkit-datetime-edit-day-field { color: orange; }
::-webkit-datetime-edit-year-field { color: red; }
<input type = "date">
How do I find an element that contains specific text in Selenium WebDriver (Python)?

We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element.
The function text() in xpath is used to locate a webelement depending on the text visible on the page. Another function contains() in xpath is used to locate a webelement with the sub-text of actual text visible on the page.
Let us try to identify the element having the specific text - Privacy Policy.
l = driver.find_element_by_xpath("//a[text()='Privacy Policy']")
m = driver.find_element_by_xpath("//a[contains(text(), 'Privacy')]")
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element with text() xpath
l = driver.find_element_by_xpath("//a[text()='Privacy Policy']")
#identify element with contains xpath
m = driver.find_element_by_xpath("//a[contains(text(), 'Privacy')]")

#get element text

print('Text obtained with text(): ' + l.text)

print('Text obtained with contains(): ' + m.text)

#close browser

driver.quit()
How to set the size of the background image with JavaScript?

To set the size of the background image in JavaScript, use the backgroundSize property. It allows you to set the image size for the background.
You can try to run the following code to learn how to set the size of the background image:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         #box {
            border: 2px dashed blue;
            width: 600px;
            height: 400px;
            background: url('https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg') no-repeat;
         }
      </style>
   </head>
   <body>
      <button onclick="display()">Set size of background image</button>
      <div id="box">
      </div>
      <script>
         function display() {
            document.getElementById("box").style.backgroundSize = "150px 200px";
         }
      </script>
   </body>
</html>
Cohesion in C#

Cohesion in C# shows the relationship within modules. It shows the functional strength of the modules. The greater the cohesion, the better will be the program design.
It is the dependency between the modules internal elements like methods and internal modules. High cohesion will allow you to reuse classes and method.
An example of High cohesion can be seen in System.Math class i.e.it has Mathematical constants and static methods −
Math.Abs
Math.PI
Math.Pow

A class that does a lot of things at a time is hard to understand and maintain. This is what we call low cohesion and should be avoided. If a class will provide functions for email, print, copy, etc time, then it would be hard to maintain and reuse.
Always try to achieve strong i.e. high cohesion in your code.
Program to find the Discount Percentage in C++

In this problem, we are given two numbers that define the marked price(M) and selling price(S) of a certain product. Our task is to create a program to
find the Discount Percentage in C++.
Discount is the amount that is deducted from the actual price (marked price) on a product.
The formula for discount is,
discount = marked price - selling price
Discount percentage is the percentage of the price that is deducted from the actual price of the product.
The formula for discount percentage is,
discount percentage = (discount / marked price ) * 100
Let’s take an example to understand the problem,
240, 180
25%
Discount = (240 - 180) = 60
Discount percentage = (60/240)*100 = 25%
The formulas for discount and discount percentage are −
Discount = marked price - selling price
Discount percentage = (discount / marked price ) * 100
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
int main() {
   float MP = 130, SP = 120;
   float DP = (float)(((MP - SP) * 100) / MP);
   printf("The discount percentage on the given product is %.2f\n", DP);
   return 0;
}
The discount percentage on the given product is 7.69
Count ways to express a number as sum of consecutive numbers in C++

Given an integer n as input. The goal is to find the number of ways in which we can represent ‘num’ as the sum of two or more consecutive natural numbers. For example, if n is 3 it can be represented as sum ( 1+2 ) so total 1 way.
For Example
num=6
Count of ways to express a number as sum of consecutive numbers are: 1
The ways in which we can express ‘num’ as sum of consecutive natural
numbers: 1+2+3
num=19
Count of ways to express a number as sum of consecutive numbers are: 1
The ways in which we can express ‘num’ as sum of consecutive natural
numbers: 9+10
Approach used in the below program is as follows −
In this approach we will represent the number as the sum of ( a + a+1 + a+2.....+ a+i ).
Which becomes (a)(L+1) times + 1+2+3+4...+i = a*(i+1) + i*(i+1)/2. (sum of i natural numbers) num=a*(i+1) + i*(i+1)/2.a= [ num − (i)*(i+1)/2 ] / (i+1)
We will do this for i=1 to i*(i+1)/2 is less than num.
Take an integer num as input.
Take an integer num as input.
Function sum_consecutive(int num) takes a num and returns the count of ways to express ‘num’ as sum of consecutive natural numbers.
Function sum_consecutive(int num) takes a num and returns the count of ways to express ‘num’ as sum of consecutive natural numbers.
Take the initial count as 0.
Take the initial count as 0.
Take temporary variable res as float.
Take temporary variable res as float.
Using for loop traverse from i=1 to i*(i+1)/2 < num.
Using for loop traverse from i=1 to i*(i+1)/2 < num.
Calculate the value [ num − (i)*(i+1)/2 ] / (i+1) and store in res.
Calculate the value [ num − (i)*(i+1)/2 ] / (i+1) and store in res.
If res is integer ( res − (int)res is 0 ) then increment count.
If res is integer ( res − (int)res is 0 ) then increment count.
At the end we have count as ways in which num can be represented as the sum of consecutive natural numbers.
At the end we have count as ways in which num can be represented as the sum of consecutive natural numbers.
Return count as result.
Return count as result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int sum_consecutive(int num){
   int count = 0;
   int temp = num * 2;
   float res;
   for (int i = 1; i * (i + 1) < temp; i++){
      int store = i + 1;
      res = (1.0 * num−(i * (i + 1)) / 2) / store;
      float check = res − (int)res;
      if(check == 0.0){
         count++;
      }
   }
   return count;
}
int main(){
   int num = 20;
   cout<<"Count of ways to express a number as sum of consecutive numbers are: "<<sum_consecutive(num) << endl;
   return 0;
}
If we run the above code it will generate the following output −
Count of ways to express a number as sum of consecutive numbers are: 1
How to write functions in Python that accept any number of arguments

You want to write a function that accepts any number of input arguments.
The * argument in python can accepts any number of arguments. We will understand this with an example of finding out the average of any given two or more numbers. In the below example, rest_arg is a tuple of all the extra arguments (in our case numbers) passed. The function treats the arguments as a sequence in performing average calculation.
# Sample function to find the average of the given numbers
def define_average(first_arg, *rest_arg):
average = (first_arg + sum(rest_arg)) / (1 + len(rest_arg))
print(f"Output \n *** The average for the given numbers {average}")

# Call the function with two numbers
define_average(1, 2)
*** The average for the given numbers 1.5
# Call the function with more numbers
define_average(1, 2, 3, 4)
*** The average for the given numbers 2.5
To accept any number of keyword arguments, use an argument that starts with **.
def player_stats(player_name, player_country, **player_titles):
print(f"Output \n*** Type of player_titles - {type(player_titles)}")
titles = ' AND '.join('{} : {}'.format(key, value) for key, value in player_titles.items())

print(f"*** Type of titles post conversion - {type(titles)}")
stats = 'The player - {name} from {country} has {titles}'.format(name = player_name,
country=player_country,
titles=titles)
return stats

player_stats('Roger Federer','Switzerland', Grandslams = 20, ATP = 103)
*** Type of player_titles - <class 'dict'>
*** Type of titles post conversion - <class 'str'>
'The player - Roger Federer from Switzerland has Grandslams : 20 AND ATP : 103'
Here in above example, player_titles is a dictionary that holds the passed keyword arguments.
If you want a function that can accept both any number of positional and keyword-only arguments, use * and ** together
def func_anyargs(*args, **kwargs):
print(args) # A tuple
print(kwargs) # A dict
With this function, all of the positional arguments are placed into a tuple args, and all of the keyword arguments are placed into a dictionary kwargs.
Erlang - spawn

This is used to create a new process and initialize it.
spawn(Function)

Function − The function which needs to be spawned.
Function − The function which needs to be spawned.
This method returns a process id.
-module(helloworld). 
-export([start/0]). 

start() ->
   spawn(fun() -> server("Hello") end). 

server(Message) ->
   io:fwrite("~p",[Message]).
When we run the above program, we will get the following result.
“Hello”

 Print
 Add Notes
 Bookmark this page
Algorithms | Sorting | Question 1 - GeeksforGeeks

28 Jun, 2021
What is recurrence for worst case of QuickSort and what is the time complexity in Worst case?(A) Recurrence is T(n) = T(n-2) + O(n) and time complexity is O(n^2)(B) Recurrence is T(n) = T(n-1) + O(n) and time complexity is O(n^2)(C) Recurrence is T(n) = 2T(n/2) + O(n) and time complexity is O(nLogn)(D) Recurrence is T(n) = T(n/10) + T(9n/10) + O(n) and time complexity is O(nLogn)Answer: (B)Explanation: The worst case of QuickSort occurs when the picked pivot is always one of the corner elements in sorted array. In worst case, QuickSort recursively calls one subproblem with size 0 and other subproblem with size (n-1). So recurrence is
T(n) = T(n-1) + T(0) + O(n)
The above expression can be rewritten as
T(n) = T(n-1) + O(n)
void exchange(int *a, int *b){  int temp;  temp = *a;  *a   = *b;  *b   = temp;}   int partition(int arr[], int si, int ei){  int x = arr[ei];  int i = (si - 1);  int j;     for (j = si; j <= ei - 1; j++)  {    if(arr[j] <= x)    {      i++;      exchange(&arr[i], &arr[j]);    }  }     exchange (&arr[i + 1], &arr[ei]);  return (i + 1);}   /* Implementation of Quick Sortarr[] --> Array to be sortedsi  --> Starting indexei  --> Ending index*/void quickSort(int arr[], int si, int ei){  int pi;    /* Partitioning index */  if(si < ei)  {    pi = partition(arr, si, ei);    quickSort(arr, si, pi - 1);    quickSort(arr, pi + 1, ei);  }}
Quiz of this Question
Algorithms-Sorting-Quiz
Sorting Quiz
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Backtracking | Question 1
Algorithms | Dynamic Programming | Question 2
Algorithms | Greedy Algorithms | Question 1
Algorithms | Dynamic Programming | Question 3
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Dynamic Programming | Question 7
Algorithms | Graph Traversals | Question 12
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Graph Traversals | Question 8
Algorithms | Dynamic Programming | Question 7
Convert to Strictly increasing integer array with minimum changes in C++

In this tutorial, we will be discussing a program to convert to strictly increasing integer array with minimum changes.
For this we will be provided with an array. Our task is to change the elements of the array to be in strictly increasing order by minimum number of changes in the elements.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//calculating number of changes required
int remove_min(int arr[], int n){
   int LIS[n], len = 0;
   for (int i = 0; i < n; i++)
   LIS[i] = 1;
   for (int i = 1; i < n; i++) {
      for (int j = 0; j < i; j++) {
         if (arr[i] > arr[j] && (i-j)<=(arr[i]-arr[j])){
            LIS[i] = max(LIS[i], LIS[j] + 1);
         }
      }
         len = max(len, LIS[i]);
   }
   //returning the changes required
   return n - len;
}
int main(){
   int arr[] = { 1, 2, 6, 5, 4 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << remove_min(arr, n);
   return 0;
}
2
Kibana - Environment Setup

To start working with Kibana we need to install Logstash, Elasticsearch and Kibana. In this chapter, we will try to understand the installation of the ELK stack here.
We would discuss the following installations here −
Elasticsearch Installation
Logstash Installation
Kibana Installation
A detailed documentation on Elasticsearch exists in our library. You can check here for elasticsearch installation. You will have to follow the steps mentioned in the tutorial to install Elasticsearch.
Once done with the installation, start the elasticsearch server as follows −
For Windows
> cd kibanaproject/elasticsearch-6.5.4/elasticsearch-6.5.4/bin
> elasticsearch

Please note for windows user, the JAVA_HOME variable has to be set to the java jdk path.
For Linux
$ cd kibanaproject/elasticsearch-6.5.4/elasticsearch-6.5.4/bin
$ elasticsearch

The default port for elasticsearch is 9200. Once done, you can check the elasticsearch at port 9200 on localhost http://localhost:9200/as shown below −
For Logstash installation, follow this elasticsearch installation which is already existing in our library.
Go to the official Kibana site −https://www.elastic.co/products/kibana
Click the downloads link on the top right corner and it will display screen as follows −
Click the Download button for Kibana. Please note to work with Kibana we need 64 bit machine and it will not work with 32 bit.
In this tutorial, we are going to use Kibana version 6. The download option is available for Windows, Mac and Linux. You can download as per your choice.
Create a folder and unpack the tar/zip downloads for kibana. We are going to work with sample data uploaded in elasticsearch. Thus, for now let us see how to start elasticsearch and kibana. For this, go to the folder where Kibana is unpacked.
For Windows
> cd kibanaproject/kibana-6.5.4/kibana-6.5.4/bin
> kibana

For Linux
$ cd kibanaproject/kibana-6.5.4/kibana-6.5.4/bin
$ kibana

Once Kibana starts, the user can see the following screen −
Once you see the ready signal in the console, you can open Kibana in browser using http://localhost:5601/.The default port on which kibana is available is 5601.
The user interface of Kibana is as shown here −
In our next chapter, we will learn how to use the UI of Kibana. To know the Kibana version on Kibana UI, go to Management Tab on left side and it will display you the Kibana version we are using currently.
 Print
 Add Notes
 Bookmark this page
Difference between regular functions and arrow functions in JavaScript

According to MDN, An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.
There are 3 subtle differences in regular functions and arrow functions in JavaScript.
Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.
this.a = 100;
let arrowFunc = () => {this.a = 150};
function regFunc() {
   this.a = 200;
}
console.log(this.a)
arrowFunc()
console.log(this.a)
regFunc()
console.log(this.a)
100
150
150
See that the arrow function changed the this object outside its scope. The regular function just made the changes within its own this.
In JS arguments array in functions is a special object that can be used to get all the arguments passed to the function. Similar to this, arrow functions do not have their own binding to a arguments object, they are bound to arguments of enclosing scope.
If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).
Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable. class constructors are only constructable.
If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.
let arrowFunc = () => {}
new arrowFunc()
This code gives the error:
arrowFunc is not a constructor
Remove duplicates from a dataframe in PySpark

16 Dec, 2021
In this article, we are going to drop the duplicate data from dataframe using pyspark in Python
Before starting we are going to create Dataframe for demonstration:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list  of employee datadata =[["1","sravan","company 1"],       ["2","ojaswi","company 1"],       ["3","rohith","company 2"],       ["4","sridevi","company 1"],       ["1","sravan","company 1"],       ["4","sridevi","company 1"]] # specify column namescolumns = ['Employee ID','Employee NAME','Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print('Actual data in dataframe')dataframe.show()
Output:
It will remove the duplicate rows in the dataframe
Syntax: dataframe.distinct()
Where, dataframe is the dataframe name created from the nested lists using pyspark
Example 1: Python program to drop duplicate data using distinct() function
Python3
print('distinct data after dropping duplicate rows') # display distinct datadataframe.distinct().show()
Output:
Example 2: Python program to select distinct data in only two columns.
We can use select () function along with distinct function to get distinct values from particular columns
Syntax: dataframe.select([‘column 1′,’column n’]).distinct().show()
Python3
# display distinct data in# Employee ID and Employee NAMEdataframe.select(['Employee ID',                  'Employee NAME']).distinct().show()
Output:
Syntax: dataframe.dropDuplicates()
where, dataframe is the dataframe name created from the nested lists using pyspark
Example 1: Python program to remove duplicate data from the employee table.
Python3
# remove duplicate data# using dropDuplicates()functiondataframe.dropDuplicates().show()
Output:
Example 2: Python program to remove duplicate values in specific columns
Python3
# remove duplicate data# using dropDuplicates()function# in two columnsdataframe.select(['Employee ID',                  'Employee NAME']).dropDuplicates().show()
Output:
sagar0719kumar
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Schedule Python Scripts As Cron Jobs With Crontab

18 Jul, 2021
In this article, we will discuss how to schedule Python scripts with crontab.
The Cron job utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. One can schedule scripts to be executed periodically. The crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. cron is the system process that will automatically perform tasks for you according to a set schedule.
Below is a simple Python script that sends a notification message to remind the user to drink water. We will be scheduling this script to send a notification every 2 hours. (the script is tested for Linux-based systems only, but the scheduling process will be similar with any script)
Python3
#!/usr/bin/env python3#-*- coding: utf-8 -*-  import subprocess  def sendmessage(message="drink water"):    subprocess.Popen(['notify-send', message])    return  if __name__ == '__main__':    sendmessage()
Note:  #!/usr/bin/python3 (specifying the path of script interpreter) is necessary if wish to make the script executable. Assuming we have saved this script as my_script.py under our home directory, we can make it executable by entering the following command in our terminal:
$ sudo chmod +x my_script.py
We can test our script if it is working properly:
./my_script.py
This will send a notification as the message “drink water”.
The crontab scheduling expression has the following parts:
To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:
crontab -e
You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:
* */2 * * * /home/$(USER)/my_script.py
where $(USER) can be replaced with your username. Save changes and exit. This will schedule our Python script to run every 2 hours.
It will list all the scheduled jobs.
crontab -l
There are a few things to keep in mind before scheduling cron jobs:
All cron jobs are scheduled in the local time zone in which the system where the jobs are being scheduled operates. This could be troublesome if jobs are being scheduled on servers with multinational personnel using it. Especially if the users also belong to countries that follow Daylight Savings Time practice.
All cron jobs run in their own isolated, anonymous shell sessions and their output to STDOUT (if any) must be directed to a file if we wish to see them.
All cron jobs run in the context of the user for which they were scheduled. It is therefore always good practice to provide an absolute path to scripts and output files to avoid any confusion and cluttering.
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a DataFrame in Python?

Dataframe is a 2D data structure. Dataframe is used to represent data in tabular format in rows and columns. It is like a spreadsheet or a sql table. Dataframe is a Pandas object.
To create a dataframe, we need to import pandas. Dataframe can be created using dataframe() function. The dataframe() takes one or two parameters. The first one is the data which is to be filled in the dataframe table. The data can be in form of list of lists or dictionary of lists. In case of list of lists data, the second parameter is the columns name.
import pandas as pd

data={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]}

df=pd.dataframe(data)

df #print the dataframe
The output will be a table having two columns named ‘Name’ and ‘Age’ with the provided data fed into the table.
import pandas as pd

data=[[‘Karan’,23],[‘Rohit’,22],[‘Sahil’,21],[‘Aryan’,24]]

df=pd.dataframe(data,columns=[‘Name’,’Age’])

df
This also gives the same output. The only difference is in the form in which the data is provided. Since the columns names are not specified earlier, it is needed to pass column names as arguments in the dataframe() function.
import pandas as pd

data={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]}

df=pd.dataframe(data,index=[‘No.1’,’No.2’,’No.3’,’No.4’])

df
This creates the same dataframe with indexes as mentioned in the index list.
How to skip over an element in .map() ?

23 Jul, 2020
The map() function in JavaScript is used to generate a new array by calling function for every array element.
Note:
map() method calls the function for every array element in order.
map() does not execute for array element that has no values.
map() does not change the original array.
There are various ways to skip over an element in the map:
Using if loop inside the function to be executed to add the constraints to skip over that element.
Using the filter method.
Using the arrow function.
Example 1: Adding the constraints inside the loop.
HTML
<!DOCTYPE html><html>  <body>    <p style="color: green;         font-size: 30px;">        GeeksforGeeks    </p>      <p>[1,-1,-2,6,7,8]</p>      <button onclick="myFunction()">        Click to skip negative values    </button>          <p id="demo"></p>      <script>        function display(num) {            if (num > 0) {                return num;            }            else {                return "null";            }        }        var values = [1, -1, -2, 6, 7, 8]        var filtered = values.map(display)        function myFunction() {            x = document.getElementById("demo")            x.innerHTML = filtered;        }    </script></body>  </html>
Output:
Example 2: Using the filter method.
HTML
<!DOCTYPE html><html>  <body>    <p style="color: green;         font-size: 30px;">        GeeksforGeeks    </p>      <p>[1,-1,-2,6,7,8]</p>      <button onclick="myFunction()">        Click to skip negative values    </button>          <p id="demo"></p>      <script>        function isPositive(value) {            return value > 0;        }        function display(num) {            return num;        }        var values = [1, -1, -2, 6, 7, 8]        var filtered =             values.map(display).filter(isPositive);                      function myFunction() {            x = document.getElementById("demo")            x.innerHTML = filtered;        }    </script></body>  </html>
Output:
Example 3: Using the arrow function.
HTML
<!DOCTYPE html><html>  <body>    <p style="color: green;         font-size: 30px;">        GeeksforGeeks    </p>        <p>Given<br>images = [{src: 1}, {src: 2},         {src: 3}, {src: 4}]<br>Skip src=3</p>      <button onclick="myFunction()">Skip</button>    <p id="demo"><br></p>      <script>        let images = [{ src: 1 }, { src: 2 },                         { src: 3 }, { src: 4 }];        let sources = images.filter(            img => img.src != 3).map(img => img.src);                      function myFunction() {            x = document.getElementById("demo")            x.innerHTML = sources;        }    </script></body>  </html>
Output: 
Before Clicking the Button:
Before clicking
After Clicking the Button:
After clicking the button
HTML-Misc
JavaScript-Misc
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Use of realloc()

28 May, 2017
Size of dynamically allocated memory can be changed by using realloc().
As per the C99 standard:
void *realloc(void *ptr, size_t size);
realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object is identical to that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.
The point to note is that realloc() should only be used for dynamically allocated memory. If the memory is not dynamically allocated, then behavior is undefined.For example, program 1 demonstrates incorrect use of realloc() and program 2 demonstrates correct use of realloc().
Program 1:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
#include <stdio.h>#include <stdlib.h>int main(){   int arr[2], i;   int *ptr = arr;   int *ptr_new;        arr[0] = 10;    arr[1] = 20;              // incorrect use of new_ptr: undefined behaviour   ptr_new = (int *)realloc(ptr, sizeof(int)*3);   *(ptr_new + 2) = 30;        for(i = 0; i < 3; i++)     printf("%d ", *(ptr_new + i));     getchar();   return 0;}
Output:Undefined Behavior
Program 2:
#include <stdio.h>#include <stdlib.h>int main(){   int *ptr = (int *)malloc(sizeof(int)*2);   int i;   int *ptr_new;        *ptr = 10;    *(ptr + 1) = 20;        ptr_new = (int *)realloc(ptr, sizeof(int)*3);   *(ptr_new + 2) = 30;   for(i = 0; i < 3; i++)       printf("%d ", *(ptr_new + i));     getchar();   return 0;}
Output:10 20 30
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Dynamic Memory Allocation
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs
C Language Introduction
Power Function in C/C++