code-rag-bench/online-tutorials huggingface dataset:
Difference between ++*p, *p++ and *++p

11 Oct, 2021
Predict the output of following C programs. 
C
// PROGRAM 1#include <stdio.h>int main(void){    int arr[] = {10, 20};    int *p = arr;    ++*p;    printf("arr[0] = %d, arr[1] = %d, *p = %d",                          arr[0], arr[1], *p);    return 0;}
C
// PROGRAM 2#include <stdio.h>int main(void){    int arr[] = {10, 20};    int *p = arr;    *p++;    printf("arr[0] = %d, arr[1] = %d, *p = %d",                          arr[0], arr[1], *p);    return 0;}
C
// PROGRAM 3#include <stdio.h>int main(void){    int arr[] = {10, 20};    int *p = arr;    *++p;    printf("arr[0] = %d, arr[1] = %d, *p = %d",                          arr[0], arr[1], *p);    return 0;}
The output of above programs and all such programs can be easily guessed by remembering following simple rules about postfix ++, prefix ++ and * (dereference) operators 1) Precedence of prefix ++ and * is same. Associativity of both is right to left. 2) Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.(Refer: Precedence Table)The expression ++*p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as ++(*p). Therefore the output of first program is “arr[0] = 11, arr[1] = 20, *p = 11“.The expression *p++ is treated as *(p++) as the precedence of postfix ++ is higher than *. Therefore the output of second program is “arr[0] = 10, arr[1] = 20, *p = 20 “.The expression *++p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as *(++p). Therefore the output of third program is “arr[0] = 10, arr[1] = 20, *p = 20“.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
srinam
tarya461
brishabh786
C-Operators
cpp-operator
cpp-pointer
C Language
Difference Between
cpp-operator
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Perl | sleep() Function

07 May, 2019
sleep() function in Perl is an inbuilt function which is used to delay the execution of the current script for a specified number of seconds or forever if parameter is not specified. The sleep( ) function accepts seconds as a parameter and returns the same on success.
Syntax: sleep(seconds)
Returns: seconds passed to it as parameter, on success
Example 1:
#!/usr/bin/perl -w  # Using localtime() function# to print the timeprint scalar localtime();  # calling the sleep functionsleep(5);  print "\n";  print scalar localtime();
Thu Mar 28 06:02:21 2019
Thu Mar 28 06:02:26 2019

Example 2:
#!/usr/bin/perl -w  # Using localtime() function# to print the timeprint scalar localtime();  # Using rand() to generate random delaysleep(rand(7));  print "\n";  print scalar localtime();
Thu Mar 28 06:02:26 2019
Thu Mar 28 06:02:27 2019

Perl-function
Perl-Inbuilt-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RxJS - Join Operator forkJoin

This operator will take in an array or dict object as an input and will wait for the observable to complete and return the last values emitted from the given observable.
forkJoin(value: array or dict object): Observable

value − The value is the input which can be an array or dict object.
An observable is returned with last values emitted from the given observable.
import { of, forkJoin } from 'rxjs';
import { concat } from 'rxjs/operators';

let list1 = of(2, 3, 4, 5, 6);
let list2 = of(4, 9, 16, 25, 36)
let final_val = forkJoin([list1, list2]);
final_val.subscribe(x => console.log(x));
[6,36]


    51 Lectures 
     4 hours 

 Daniel Stern
 Print
 Add Notes
 Bookmark this page
Python | Split and Pass list as separate parameter - GeeksforGeeks

05 Sep, 2019
With the advent of programming paradigms, there has been need to modify the way one codes. One such paradigm is OOPS. In this, we have a technique called modularity, which stands for making different modules/functions which perform independent tasks in program. In this, we need to pass more than just variable, but a list as well. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple()This task can be performed using the tuple(). In this, we convert the pair list to tuple and by this way we separate individual elements as variables, ready to be sent to function.
# Python3 code to demonstrate working of# Split and Pass list as separate parameter# using tuple()  # Helper function for demonstrationdef pass_args(arg1, arg2):    print("The first argument is : " +  str(arg1))    print("The second argument is : " +  str(arg2))  # initialize listtest_list = [4, 5]  # printing original listprint("The original list is : " + str(test_list))  # Split and Pass list as separate parameter# using tuple()one, two = tuple(test_list)pass_args(one, two)
The original list is : [4, 5]
The first argument is : 4
The second argument is : 5

 
Method #2 : Using * operatorUsing * operator is the most recommended method to perform this task. The * operator unpacks the dual list into args and hence solving our problem.
# Python3 code to demonstrate working of# Split and Pass list as separate parameter# using * operator  # Helper function for demonstrationdef pass_args(arg1, arg2):    print("The first argument is : " +  str(arg1))    print("The second argument is : " +  str(arg2))  # initialize listtest_list = [4, 5]  # printing original listprint("The original list is : " + str(test_list))  # Split and Pass list as separate parameter# using * operatorpass_args(*test_list)
The original list is : [4, 5]
The first argument is : 4
The second argument is : 5

Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() 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
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
sum() function in Python
Setting the same axis limits for all subplots in Matplotlib

To set the same axis limits for all subplots in matplotlib we can use subplot() method to create 4 subplots where nrows=2, ncols=2 having share of x and y axes.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Add a subplot to the current figure at index 1.
Add a subplot to the current figure at index 1.
Set the x and y axes view limit using set_xlim() and set_ylim() methods.
Set the x and y axes view limit using set_xlim() and set_ylim() methods.
Plot a line on axis 1 (step 2).
Plot a line on axis 1 (step 2).
Add a subplot to the current figure at index 2 with the same limit (step 3).
Add a subplot to the current figure at index 2 with the same limit (step 3).
Plot a line on axis 2.
Plot a line on axis 2.
Add a subplot to the current figure at index 3 with the same limit (step 3).
Add a subplot to the current figure at index 3 with the same limit (step 3).
Plot a line on axis 3.
Plot a line on axis 3.
Add a subplot to the current figure at index 4 with the same limit (step 3).
Add a subplot to the current figure at index 4 with the same limit (step 3).
Plot a line on axis 4.
Plot a line on axis 4.
To show the figure, use show() method.
To show the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
ax1 = plt.subplot(2, 2, 1)
ax1.set_xlim(left=0, right=5)
ax1.set_ylim(bottom=0, top=5)
ax1.plot([1, 4, 3])
ax2 = plt.subplot(2, 2, 2, sharey=ax1, sharex=ax1)
ax2.plot([3, 4, 1])
ax3 = plt.subplot(2, 2, 4, sharey=ax1, sharex=ax1)
ax3.plot([2, 4, 2])
ax4 = plt.subplot(2, 2, 3, sharey=ax1, sharex=ax1)
ax4.plot([4, 0, 4])
plt.show()
pthread_self() in C

Here we will see what will be the effect of pthread_self() in C. The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* func(void* p) {
   printf("From the function, the thread id = %d\n", pthread_self()); //get current thread id
      pthread_exit(NULL);
   return NULL;
}
main() {
   pthread_t thread; // declare thread
   pthread_create(&thread, NULL, func, NULL);
   printf("From the main function, the thread id = %d\n", thread);
   pthread_join(thread, NULL); //join with main thread
}
From the main function, the thread id = 1
From the function, the thread id = 1
C# | IsNullOrEmpty() Method - GeeksforGeeks

01 Apr, 2019
In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.Empty (A constant for empty strings).
Syntax:
public static bool IsNullOrEmpty(String str)  

Explanation: This method will take a parameter which is of type System.String and this method will returns a boolean value. If the str parameter is null or an empty string (“”) then return True otherwise return False.
Example:
Input : str  = null         // initialize by null value
        String.IsNullOrEmpty(str)
Output: True

Input : str  = String.Empty  // initialize by empty value
        String.IsNullOrEmpty(str)
Output: True

Program: To demonstrate the working of the IsNullOrEmpty() Method :
// C# program to illustrate // IsNullOrEmpty() Methodusing System;class Geeks {        // Main Method    public static void Main(string[] args)    {        string s1 = "GeeksforGeeks";              // or declare String s2.Empty;        string s2 = "";           string s3 = null;          // for String value Geeks, return true        bool b1 = string.IsNullOrEmpty(s1);          // For String value Empty or "", return true        bool b2 = string.IsNullOrEmpty(s2);          // For String value null, return true        bool b3 = string.IsNullOrEmpty(s3);          Console.WriteLine(b1);        Console.WriteLine(b2);        Console.WriteLine(b3);    }}
False
True
True

Note: IsNullOrEmpty method enables to check whether a String is null or its value is Empty and its alternative code can be as follows:
return  s == null || s == String.Empty;

Program: To demonstrate IsNullOrEmpty() method’s alternative
// C# program to illustrate the // similar method for IsNullOrEmpty()using System;class Geeks {      // to make similar method as IsNullOrEmpty    public static bool check(string s)    {        return (s == null || s == String.Empty) ? true : false;    }      // Main Method    public static void Main(string[] args)    {        string s1 = "GeeksforGeeks";          // or declare String s2.Empty;        string s2 = "";         string s3 = null;          bool b1 = check(s1);        bool b2 = check(s2);        bool b3 = check(s3);          // same output as above program        Console.WriteLine(b1);        Console.WriteLine(b2);        Console.WriteLine(b3);    }}
False
True
True

Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorempty(v=vs.110).aspx
AlanFitzgerald
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Delegates
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
tac command in Linux with Examples - GeeksforGeeks

27 May, 2019
tac command in Linux is used to concatenate and print files in reverse. This command will write each FILE to standard output, the last line first. When no file is specified then this command will read the standard input.
Syntax:
tac [OPTION]... [FILE]...

Example: It will print files in reverse.
Options:
tac -b: This option attach the separator before instead of after.Example:tac -b concat.txt tacexample.txt
Example:
tac -b concat.txt tacexample.txt
tac -r: This option will interpret the separator as a regular expression.Example:tac -r concat.txt tacexample.txt
Example:
tac -r concat.txt tacexample.txt
tac -s : This option use STRING as the separator instead of newline.Example:tac -s concat.txt tacexample.txt
Example:
tac -s concat.txt tacexample.txt
tac –help : This option will display the help text and exit.tac --help
tac --help
tac –version: This option will give the version information and exit.tac --version
tac --version
linux-command
Linux-file-commands
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
Matplotlib.figure.Figure.get_edgecolor() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The get_edgecolor() method figure module of matplotlib library is used to get the edge color of the Figure rectangle.
Syntax: get_edgecolor(self)
Parameters: This method does not accept any parameters.
Returns: This method return the edge color of the Figure rectangle.
Below examples illustrate the matplotlib.figure.Figure.get_edgecolor() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np     fig = plt.figure(edgecolor ="green")      ax = Subplot(fig, 111) fig.add_subplot(ax)        w = fig.get_edgecolor()ax.text(0.2, 0.5, "Value Return by get_edgecolor() :\n"         +str(w),        fontweight ="bold")    fig.canvas.draw()fig.suptitle('matplotlib.figure.Figure.get_edgecolor() \function Example', fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np         fig = plt.figure(edgecolor = "red", figsize =(7, 6))       ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])    xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))   w = fig.get_edgecolor()ax.text(2, 0, "Value Return by get_edgecolor() :\n"         + str(w),        fontweight ="bold")    fig.canvas.draw()fig.suptitle('matplotlib.figure.Figure.get_edgecolor()\ function Example', fontweight ="bold")   plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Python math function | sqrt()
Python | Output Formatting
Python - Pandas dataframe.append()
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Lex program to take input from file and remove multiple spaces, lines and tabs - GeeksforGeeks

30 Apr, 2019
FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.
Prerequisite: FLEX (Fast Lexical Analyzer Generator)
Example:
Input:
hello      how
    are       
you?

Output:
hellohowareyou?

Input:
Welcome      to
Geeks    for
      Geeks

Output:
WelcometoGeeksforGeeks

Approach:Open input file in read mode and whenever parser encounters newline (\n), space ( ) or tab (\t) remove it and write all the other characters in output file.
Input File: Input.txt (Input File used in this program)
Below is the implementation program:
/*Lex program to take input from file and remove multiple spaces, newline and taband write output in a separate file*/  % {    /*Definition section */    %}  /* Rule: whenever space, tab or newline is encounterd, remove it*/% %[ \n\t]+ {fprintf(yyout, "");}.       { fprintf(yyout, "%s", yytext); }% %  int yywrap(){}  // driver code int main(){      /* yyin and yyout as pointer    of File type */    extern FILE *yyin, *yyout;      /* yyin points to the file input.txt    and opens it in read mode*/    yyin = fopen("Input.txt", "r");      /* yyout points to the file output.txt    and opens it in write mode*/    yyout = fopen("Output.txt", "w");      yylex();    return 0;}
Output:
Lex program
C Language
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Converting Strings to Numbers in C/C++
Function Pointer in C
Compiler Design | Syntax Directed Definition
Predictive Parser in Compiler Design
Difference between Source Code and Object Code
Lex program to identify the identifier
Optimization of Basic Blocks
Python - Conditional String Append - GeeksforGeeks

01 Mar, 2020
Sometimes, while working with data, we have a problem in which we need to perform append operation in string on a particular condition. This kind of problem is common in web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force way to perform this task. In this, we run a loop and check for the condition and according to that append the string to original string.
# Python3 code to demonstrate # Conditional String Append# using loop  def append_str(item, boy_str, girl_str):    if len(item) > 4 and item[-5] == ' ':        return item + girl_str    return item + boy_str      # initializing list test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']  # initializing append string boy_str = " Boy"girl_str = " Girl"  # printing original listprint ("The original list is : " + str(test_list))  # Conditional String Append# using loopres = [append_str(item, boy_str, girl_str) for item in test_list]  # printing result print ("The filtered strings are : " + str(res))
The original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
The filtered strings are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']

 
Method #2 : Using list comprehensionList comprehension is shorthand to longer method of loops. This solved problem in similar way but in shorter constructs.
# Python3 code to demonstrate # Conditional String Append# using list comprehension  # initializing list test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']  # initializing append string boy_str = " Boy"girl_str = " Girl"  # printing original listprint ("The original list is : " + str(test_list))  # Conditional String Append# using list comprehensionres = [ele + girl_str if ele[-5] == ' ' else ele + boy_str for ele in test_list]  # printing result print ("The filtered strings are : " + str(res))
The original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
The filtered strings are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']

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

17 Sep, 2018
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 nlargest() method is used to get n largest values from a data frame or a series.
Syntax:
DataFrame.nlargest(n, columns, keep='first')
Parameters:
n: int, Number of values to selectcolumns: Column to check for values or user can select column while calling too. [For example: data[“age”].nsmallest(3) OR data.nsmallest(3, “age”)]
keep: object to set which value to select if duplicates exit. Options are ‘first’ or ‘last’
To download the CSV file used, Click Here.
Code #1: Extracting Largest 5 valuesIn this example, Largest 5 values are extracted and then compared to the other sorted by the sort_values() function. NaN values are removed before trying this method.
Refer sort_values and dropna() function.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # removing null valuesdata.dropna(inplace = True)  # extracting greatest 5large5 = data.nlargest(5, "Salary")  # displaylarge5
Output:
 
Code #2: Sorting by sort_values()
# importing pandas packageimport pandas as pd  # making data frame from csv file data = pd.read_csv("employees.csv")  # removing null valuesdata.dropna(inplace = True)  # sorting in descending orderdata.sort_values("Salary", ascending = False, inplace = True)  # displaying top 5 valuesdata.head()
Output:
As shown in the output image, the values returned by both functions is similar.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
PyQt5 - Setting current index in ComboBox - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can select the item at the specific index. By default when we create a combo box it shows the first item to be selected but we can change the index, in order to do this we will use setCurrentIndex method.
Syntax : combo_box.setCurrentIndex(index)
Argument : It takes integer as argument
Action performed : It will set item of given index
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 120, 30)          # geek list        geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # setting current index        self.combo_box.setCurrentIndex(2)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
isupper(), islower(), lower(), upper() in Python and their applications
Python Classes and Objects
Python | Pandas dataframe.cummax() - GeeksforGeeks

16 Nov, 2018
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 dataframe.cummax() is used to find the cumulative maximum value over any axis. Each cell is populated with the maximum value seen so far.
Syntax: DataFrame.cummax(axis=None, skipna=True, *args, **kwargs)
Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns: cummax : Series
Example #1: Use cummax() function to find the cumulative maximum value along the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                   "B":[11, 2, 4, 3],                   "C":[4, 3, 8, 5],                    "D":[5, 4, 2, 8]})  # Print the dataframedf
Output :
Now find the cumulative maximum value over the index axis
# To find the cumulative maxdf.cummax(axis = 0)
Output :
 
Example #2: Use cummax() function to find the cumulative maximum value along the column axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4],                   "B":[11, 2, 4, 3],                   "C":[4, 3, 8, 5],                    "D":[5, 4, 2, 8]})  # To find the cumulative max along column axisdf.cummax(axis = 1)
Output :
 
Example #3: Use cummax() function to find the cumulative maximum value along the index axis in a data frame with NaN value.
# importing pandas as pdimport pandas as pd  # Creating the dataframedf = pd.DataFrame({"A":[5, 3, None, 4],                   "B":[None, 2, 4, 3],                   "C":[4, 3, 8, 5],                    "D":[5, 4, 2, None]})  # To find the cumulative maxdf.cummax(axis = 0, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists
string at() in C++ - GeeksforGeeks

08 Jul, 2021
std::string::at can be used to extract characters by characters from a given string. It supports two different syntaxes both having similar parameters: Syntax 1:  
char& string::at (size_type idx)
Syntax 2:  
const char& string::at (size_type idx) const

idx : index number
Both forms return the character that has the index idx (the first character has index 0).
For all strings, an index greater than or equal to length() as value is invalid.
If the caller ensures that the index is valid, she can use operator [], which is faster.

Return value : Returns character at the specified position in the string.

Exception : Passing an invalid index (less than 0 
or greater than or equal to size()) throws an out_of_range exception.
 
CPP
// CPP code to demonstrate std::string::at #include <iostream>using namespace std; // Function to demonstrate std::string::atvoid atDemo(string str){    cout << str.at(5);     // Below line throws out of    // range exception as 16 > length()    // cout << str.at(16);} // Driver codeint main(){    string str("GeeksForGeeks");    atDemo(str);    return 0;}
Output:  
F
 
Application
std::string::at can be used for extracting characters from string. Here is the simple code for the same.  
CPP
// CPP code to extract characters from a given string #include <iostream>using namespace std; // Function to demonstrate std::string::atvoid extractChar(string str){    char ch;     // Calculating the length of string    int l = str.length();    for (int i = 0; i < l; i++) {        ch = str.at(i);        cout << ch << " ";    }} // Driver codeint main(){    string str("GeeksForGeeks");    extractChar(str);    return 0;}
Output:  
G e e k s F o r G e e k s 
This article is contributed by Pushpanjali Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
anikaseth98
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
JavaScript program to merge two objects into a single object and adds the values for same keys

We have to write a function that takes in two objects, merges them into a single object, and adds the values for same keys. This has to be done in linear time and constant space, means using at most only one loop and merging the properties in the pre-existing objects and not creating any new variable.
So, let’s write the code for this function −
const obj1 = {
   value1: 45,
   value2: 33,
   value3: 41,
   value4: 4,
   value5: 65,
   value6: 5,
   value7: 15,
};
const obj2 = {
   value1: 34,
   value3: 71,
   value5: 17,
   value7: 1,
   value9: 9,
   value11: 11,
};
const mergeObjects = (obj1, obj2) => {
   for(key in obj1){
      if(obj2[key]){
         obj1[key] += obj2[key];
      };
   };
   return;
};
mergeObjects(obj1, obj2);
console.log(obj1);
The output in the console will be −
{
   value1: 79,
   value2: 33,
   value3: 112,
   value4: 4,
   value5: 82,
   value6: 5,
   value7: 16
}
What are static member functions in C#?

Static functions can access only static variables. The static functions exist even before the object is created.
Set static functions as −
public static int getNum() {}
The following is an example demonstrating the use of static functions −
 Live Demo
using System;

namespace Demo {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }

      public static int getNum() {
         return num;
      }
   }

   class StaticTester {
      static void Main(string[] args) {
         StaticVar s = new StaticVar();

         s.count();
         s.count();
         s.count();

         Console.WriteLine("Variable num: {0}", StaticVar.getNum());
         Console.ReadKey();
      }
   }
}
Variable num: 3
Get all methods of any object JavaScript

We are required to write a program (function) that takes in an object reference and returns an array of all the methods (member functions) that lives on that object.We are only required to return the methods in the array and not any other property that might have value of type other than a function.
We will use the Object.getOwnPropertyNames function
The Object.getOwnPropertyNames() method returns an array of all properties (enumerable or not) found directly upon a given object. And then we will filter the array to contain property of data type 'function' only.
const returnMethods = (obj = {}) => {
   const members = Object.getOwnPropertyNames(obj);
   const methods = members.filter(el => {
      return typeof obj[el] === 'function';
   })
   return methods;
};
console.log(returnMethods(Array.prototype));
And the output in the console will be −
[
   'constructor', 'concat', 'copyWithin',
'fill', 'find', 'findIndex', 'lastIndexOf', 'pop', 'push',
   'reverse', 'shift', 'unshift', 'slice', 'sort', 'splice',
   'includes', 'indexOf', 'join',
   'keys', 'entries', 'values',
   'forEach', 'filter', 'flat',
   'flatMap', 'map', 'every',
   'some', 'reduce', 'reduceRight',
   'toLocaleString', 'toString'
]
OpenCV - Gaussian Blur

In Gaussian Blur operation, the image is convolved with a Gaussian filter instead of the box filter. The Gaussian filter is a low-pass filter that removes the high-frequency components are reduced.
You can perform this operation on an image using the Gaussianblur() method of the imgproc class. Following is the syntax of this method −
GaussianBlur(src, dst, ksize, sigmaX)

This method accepts the following parameters −
src − A Mat object representing the source (input image) for this operation.
src − A Mat object representing the source (input image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
ksize − A Size object representing the size of the kernel.
ksize − A Size object representing the size of the kernel.
sigmaX − A variable of the type double representing the Gaussian kernel standard deviation in X direction.
sigmaX − A variable of the type double representing the Gaussian kernel standard deviation in X direction.
The following program demonstrates how to perform the Gaussian blur operation on an image.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class GaussianTest {
   public static void main(String args[]) {
      // Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

      // Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat src = Imgcodecs.imread(file);

      // Creating an empty matrix to store the result
      Mat dst = new Mat();
    
      // Applying GaussianBlur on the Image
      Imgproc.GaussianBlur(src, dst, new Size(45, 45), 0);

      // Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap9/Gaussian.jpg", dst);
      System.out.println("Image Processed");
   }
}
Assume that following is the input image sample.jpg specified in the above program.
On executing the program, you will get the following output −
Image Processed

If you open the specified path, you can observe the output image as follows −

    70 Lectures 
     9 hours 

 Abhilash Nelson

    41 Lectures 
     4 hours 

 Abhilash Nelson

    20 Lectures 
     2 hours 

 Spotle Learn

    12 Lectures 
     46 mins

 Srikanth Guskra

    19 Lectures 
     2 hours 

 Haithem Gasmi

    67 Lectures 
     6.5 hours 

 Gianluca Mottola
 Print
 Add Notes
 Bookmark this page
How to convert character to ASCII code using JavaScript ? - GeeksforGeeks

15 Sep, 2020
The purpose of this article is to get the ASCII code of any character by using JavaScript charCodeAt() method. This method is used to return the number indicating the Unicode value of the character at the specified index.
Syntax:
string.charCodeAt(index); 
Example: Below code illustrates that they can take character from the user and display the ASCII code of that character.
HTML Code:
HTML
<!DOCTYPE html><html>  <body style="text-align:center;">    <h2>        GeeksForGeeks    </h2>    <h2>        How to convert character to        ASCII code in JavaScript    </h2>      <p>        Enter any character:        <input type="text" id="id1"             name="text1" maxLength="1">    </p>      <button onclick="myFunction()">        Get ASCII code    </button>      <p id="demo" style="color:red;"></body>  </html>
JavaScript Code: The following code snippet illustrates the JavaScript code used in the above HTML code.
function myFunction() {    var str = document.getElementById("id1");    if (str.value == "") {        str.focus();        return;    }    var a = "ASCII Code is == >  ";    document.getElementById("demo").innerHTML        = a + str.value.charCodeAt(0);}
Final Code: The following example is the combination of the above two code snippets.
<!DOCTYPE html><html>  <body style="text-align:center;">    <h2>        GeeksForGeeks    </h2>    <h2>        How to convert character to         ASCII code in JavaScript    </h2>      <script>        function myFunction() {            var str = document.getElementById("id1");            if (str.value == "") {                str.focus();                return;            }            var a = "ASCII Code is == >  ";            document.getElementById("demo").innerHTML                = a + str.value.charCodeAt(0);        }    </script>      <p>        Enter any character:        <input type="text" id="id1"             name="text1" maxLength="1">    </p>      <button onclick="myFunction()">        Get ASCII code    </button>      <p id="demo" style="color:red;"></body>  </html>
Output:
Before Clicking on Button:
Before Clicking on Button:
After Clicking On Button:Supported browsers:Google ChromeInternet ExplorerFirefoxOperaSafariMy Personal Notes
arrow_drop_upSave
After Clicking On Button:
Supported browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Python String split() Method

Python string  method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
Following is the syntax for split() method −
str.split(str="", num=string.count(str)).

str − This is any delimeter, by default it is space.
str − This is any delimeter, by default it is space.
num − this is number of lines minus one
num − this is number of lines minus one
This method returns a list of lines.
The following example shows the usage of split() method.
#!/usr/bin/python

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( )
print str.split(' ', 1 )
When we run above program, it produces following result −
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Data Structure - Circular Linked List

Circular Linked List is a variation of Linked list in which the first element points to the last element and the last element points to the first element. Both Singly Linked List and Doubly Linked List can be made into a circular linked list.
In singly linked list, the next pointer of the last node points to the first node.
In doubly linked list, the next pointer of the last node points to the first node and the previous pointer of the first node points to the last node making the circular in both directions.
As per the above illustration, following are the important points to be considered.
The last link's next points to the first link of the list in both cases of singly as well as doubly linked list.
The last link's next points to the first link of the list in both cases of singly as well as doubly linked list.
The first link's previous points to the last of the list in case of doubly linked list.
The first link's previous points to the last of the list in case of doubly linked list.
Following are the important operations supported by a circular list.
insert − Inserts an element at the start of the list.
insert − Inserts an element at the start of the list.
delete − Deletes an element from the start of the list.
delete − Deletes an element from the start of the list.
display − Displays the list.
display − Displays the list.
Following code demonstrates the insertion operation in a circular linked list based on single linked list.
insertFirst(data):
Begin
   create a new node
   node -> data := data
   if the list is empty, then
      head := node
      next of node = head
   else
      temp := head
      while next of temp is not head, do
      temp := next of temp
      done
      next of node := head
      next of temp := node
      head := node
   end if
End
Following code demonstrates the deletion operation in a circular linked list based on single linked list.
deleteFirst():
Begin
   if head is null, then
      it is Underflow and return
   else if next of head = head, then
      head := null
      deallocate head
   else
      ptr := head
      while next of ptr is not head, do
         ptr := next of ptr
      next of ptr = next of head
      deallocate head
      head := next of ptr
   end if
End
Following code demonstrates the display list operation in a circular linked list.
display():
Begin
   if head is null, then
      Nothing to print and return
   else
      ptr := head
      while next of ptr is not head, do
         display data of ptr
         ptr := next of ptr
      display data of ptr
   end if
End
To know about its implementation in C programming language, please click here.

    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: HTML table - hover rows
Why should you be careful about String concatenation (+) operator in loops using Java?

Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.
You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).
Public class Sample{
   Public static void main(String args[]){
      String str1 = "Hello";
      String str2 = "how are you";
   }
}
Strings are immutable in Java i.e. once you create a String literal it cannot be modified.
Since all the String values we define are objects of the String class they are stored on the heap area. But, unlike other objects in a separate memory location known as String Constant pool is allotted for the String objects.
Whenever you define a String value JVM creates a String object with the given value in the String constant pool. Therefore, if you run the above program two String values are created in the String constant pool.
If you try to concatenate these two String values as −
str1 = str2 + str2;
Since Strings are immutable in java, instead of modifying str1 a new (intermediate) String object is created with the concatenated value and it is assigned to the reference str1.
If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues. Therefore, concatenating strings in loops as shown in the following example is not recommended.
public class StringExample {
   public static void main(String args[]) {
      String stringArray[] = {"Java", "JavaFX", "HBase", "Oracle"};
      String singleString = new String();
      for (int i=0; i<stringArray.length; i++) {
         singleString = singleString+stringArray[i]+" ";
      }
      System.out.println(singleString);
   }
}
Java JavaFX HBase Oracle
If you have a scenario to add String values in loops it is recommended to use StringBuilder instead of Strings −
public class StringExample {
   public static void main(String args[]) {
      String stringArray[] = {"Java", "JavaFX", "HBase", "Oracle"};
      StringBuilder singleString = new StringBuilder();
      for (int i=0; i<stringArray.length; i++) {
         singleString.append(stringArray[i]);
         singleString.append(" ");
      }
      System.out.println(singleString);
   }
}
Java JavaFX HBase Oracle
Shell Script to Check Hard Disk Revolutions Per Minute (RPM) Speed

30 Jun, 2021
RPM is an acronym for Revolution Per Minute. RPM is the number of revolutions a hard disk makes in a single minute. Normally, the higher the RPM of a disk the better it is, however with higher RPM comes higher cost. Below is a shell script to check the RPM of a hard disk.
hdparm is an acronym for hard disk parameter. hdparm is a command-line utility widely used for performing analysis on the disks that a user system has. It can help us to get statistics about the hard disk, modify writing intervals, and DMA settings. It is used to display and alter the SATA/IDE device parameters.
Syntax: 
hdparm [option] [device]
Here, in our case, our hard disk is at “/dev/sda”.  It is just the Linux/Unix way of naming disks just like Windows has C: D: drives. Similarly, in Linux, we have sda, sdc,sdb, etc and /dev is the directory for where these drives are.
To list all the disks that you have in your system, run the following command:
sudo lsblk
Output:
Marked HDD
Here, marked one is my hard disk drive, and you can see the name of the drive is assigned as sda.
Script:
#!/bin/sh

# shell script to find the RPM speed of a Hard disk

# storing hard disk name into variable disk
disk="/dev/sda"

# finding the Rotation speed of the hard disk 
# fetching the integer value 
# i.e. the speed of the hard disk 
# and saving it into another variable
output=$(sudo hdparm -I $disk | grep Rotation | grep --only-matching --extended-regexp '[0-9]+' )

# Displaying the RPM speed of the hard disk
echo "The RPM speed of the Hard disk is: $output rpm"
Note: You have to enter your password after running this script. And ‘-I’ flag in the hdparm means that we are fetching information from the disk live and in this statement “grep –only-matching –extended-regexp ‘[0-9]+'”,  “–only-matching” will fetch the rotation speed with the extra string output with it by using “–only-matching” with “–extended-regexp” with the pattern “[0-9]+” we are ensuring only the numerical value to display i.e. the rpm speed, “[0-9]+” will fetch any numerical value in the pattern it will match for any integer value from 0-9 and the “+” symbol shows that it can match any number of occurrences more than 1.
Speed of the Hard disk
Linux-Shell-Commands
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting