code-rag-bench/online-tutorials huggingface dataset:
Python - Grouping columns in Pandas Dataframe

To group columns in Pandas dataframe, use the groupby(). At first, let us create Pandas dataframe −
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"],
      "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
   }
)
Let us now group according to Car column −
res = dataFrame.groupby("Car")
After grouping, we will use functions to find the means Registration prices (Reg_Price) of grouped car names −
res.mean()
This calculates mean of the Registration price according to column Car.
Following is the code −
import pandas as pd

# dataframe with one of the columns as Reg_Price
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"],
      "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
   }
)

print"DataFrame...\n",dataFrame

# grouped according to Car
res = dataFrame.groupby("Car")

print"\nMean of Registration Price grouped according to Car names...\n",res.mean()
This will produce the following output −
DataFrame...
      Car    Reg_Price
0     Audi        1000
1    Lexus        1400
2     Audi        1100
3 Mercedes         900
4     Audi        1700
5    Lexus        1800
6 Mercedes        1300
7    Lexus        1150
8 Mercedes        1350
Mean of Registration Price grouped according to Car names...
           Reg_Price
    Car
    Audi   1266.666667
   Lexus   1450.000000
Mercedes   1183.333333
Use of fflush(stdin) in C

The function fflush(stdin) is used to flush the output buffer of the stream. It returns zero, if successful otherwise, returns EOF and feof error indicator is set.
Here is the syntax of fflush(stdin) in C language,
int fflush(FILE *stream);
Here is an example of fflush(stdin) in C language,
 Live Demo
#include
#include
int main() {
   char s[20] = "Helloworld";
   printf("The string : %s", s);
   fflush(stdin);
   return 0;
}
The string : Helloworld
What to press ctrl +f on a page in Selenium with python?

We can perform the action of pressing ctrl+f keys in Selenium. There are multiple special Keys available that enable the act of pressing keys via a keyboard like ctrl+c, ctrl+v, ctrl+f and many more. These special Keys are a part of selenium.webdriver.common.keys.Keys class.
key_up() – This method releases a modifier key. The key_up() method is a part of
Action Chains class and used to release a key pressed via key_down(). This method
is widely used for coping and pasting actions via (ctrl+c, ctrl+v).
In order to carry out this action, we need to first press the ctrl key downwards and
simultaneously press the F key. These two steps can be automated by key_up()
method and can only be used along with Shift, Alt and Control keys.
key_up(args1, args2)
Here args1 is the key to be sent. The key is defined in Keys class.
The args2 parameter is the element to send keys. If omitted, it shall send a key to
the element which is presently in focus.
Code Implementation to press ctrl+f.
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# action chain object creation
a = ActionChains(driver)
# perform the ctrl+f pressing action
a.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perfo
rm()
#to close the browser
driver.close()
Triangle in C++

Suppose we have a triangle. We have to find the minimum path sum from top to the bottom. In each step, we can move to adjacent numbers on the row below.
For example, if the following triangle is like
[
      [2],
     [3,4],
    [6,5,7],
   [4,1,8,3]
]
The minimum path sum from top to bottom is 11 (2 + 3 + 5 + 1 = 11).
Let us see the steps −
Create one table to use in Dynamic programming approach.
Create one table to use in Dynamic programming approach.
n := size of triangle
n := size of triangle
for i := n – 2 down to 0for j := 0 to idp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]
for i := n – 2 down to 0
for j := 0 to idp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]
for j := 0 to i
dp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]
dp[j] := triangle[i, j] + minimum of dp[j] and dp[j + 1]
return dp[0]
return dp[0]
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int minimumTotal(vector<vector<int>>& triangle) {
      vector <int> dp(triangle.back());
      int n = triangle.size();
      for(int i = n - 2; i >= 0; i--){
         for(int j = 0; j <= i; j++){
            dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);
         }
      }
      return dp[0];
   }
};
main(){
   Solution ob;
   vector<vector<int> > v = {{2},{3,4},{6,5,7},{4,1,8,3}};
   cout << ob.minimumTotal(v);
}
[[2],[3,4],[6,5,7],[4,1,8,3]]
11
Amazon Internship Interview Experience | On-Campus 2021 - GeeksforGeeks

11 Oct, 2021
Amazon arrived for hiring in the last week of Sept 2021 on our campus for the 6 months Software Development Engineer Role. We had a total of 3 rounds (1 Online Coding on Amazon’s Assessment Portal + 2 Technical Interviews).
Round 1: Online Assessment Round
The coding round comprised of 4 sections:
Debugging: We had to choose a language and debug up to 10 questions most probably. Codes were very basic like sorting, etc.
Coding: There were two medium-hard level questions.
Work-style Assessment
Aptitude: 25 aptitude questions (most probably)
Round 2: Technical Interview Round 1
Next Greater Frequency of Element: same as next greater element but print greater frequency instead. I was asked to write only the function.
Eg - 1 1 2 1 3 2  ->  -1 -1 1 -1 1 -1
Design a data structure that does insert, delete, max, min deletes max, delete min operations in less time complexity preferred O(1) (with duplicate elements),.I answered accordingly as given in GFG using a doubly-linked list and min and max heaps. But he asked for a more optimized delete min/max operation in O(1) but I wasn’t able to come up. He explained to me that we could use one more data structure to store addresses of the elements in the heaps. I was asked only the intuition.
Round 3: Technical Interview Round 2
Clone a Binary tree having random pointers The structure of the node was already provided.Tell me about any technology that you have started learning or have worked on recently – Use the STAR method to explain. I was from ECE so I was also allowed to speak about any technology which may be related to ECE too.
Clone a Binary tree having random pointers The structure of the node was already provided.
Tell me about any technology that you have started learning or have worked on recently – Use the STAR method to explain. I was from ECE so I was also allowed to speak about any technology which may be related to ECE too.
Tips:
Start from brute force and keep on optimizing when asked.
Speak while coding or thinking.
Repeat the question how you have understood it.
Keep track of edge cases.
Use STAR method for behavioral questions.
I guess they didn’t ask me any theory as I was from ECE and also not much time was left. Don’t take it for granted, it’s just an assumption of mine.
Verdict: Selected
Amazon
Marketing
On-Campus
Internship
Interview Experiences
Amazon
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Zoho Interview Experience (Off-Campus ) 2022
OLX Interview Experience (On-Campus)
Zoho Corporation (Internship cum Offer Experience )
Difference Between ON Page and OFF Page SEO
Amazon Interview Questions
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience for SDE-1
Difference between ANN, CNN and RNN
DAX Time Intelligence - TOTALYTD function

Evaluates the year-to-date value of the expression in the current context.
TOTALYTD (<expression>, <dates>, [<filter>], [<year_end_date>]) 

expression
An expression that returns a scalar value.
dates
A column that contains dates.
filter
Optional.
An expression that specifies a filter to apply to the current context.
year_end_date
Optional.
A literal string with a date that defines the year-end date. If omitted, the default is December 31.
A scalar value.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
The filter parameter can be a Boolean expression or a table expression that defines a filter.
If the data has been filtered, the function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter parameter, any existing filters on that column are removed, and the filter used in the filter parameter is applied instead.
The year_end_date parameter is a string literal of a date, in the locale where the workbook was created. The year portion of the date is ignored.
Year Running Sum:= TOTALYTD (SUM (Sales[Sales Amount]),Sales[Date]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to center a popup window on screen? - GeeksforGeeks

28 Mar, 2022
JavaScript window.open() method is used to open a popup window. This popup window will place into the center of the screen.
popupWinHeight: The height of pop up window on the screen.
popupWinWidth: The width of pop up window on the screen.
Example 1: This example creates the pop up window without placing it into center. 
html
<!DOCTYPE html><html>     <head>     <title>         Non-centered popup window        on the screen    </title></head> <body>    <h1>GeeksforGeeks</h1>         <p>        Non-centered popup window        on the screen    </p>         <script>        function createPopupWin(pageURL, pageTitle,                    popupWinWidth, popupWinHeight) {            var left = (screen.width ) ;            var top = (screen.height ) ;            var myWindow = window.open(pageURL, pageTitle,                    'resizable=yes, width=' + popupWinWidth                    + ', height=' + popupWinHeight + ', top='                    + top + ', left=' + left);        }    </script>         <button onclick = "createPopupWin('https://www.geeksforgeeks.org',            'GeeksforGeeks Website', 1200, 650);">        GeeksforGeeks    </button></body> </html>
Output:
Before Clicking the button: 
After Clicking the button: 
Center popup window: To center the popup window we are changing the values of parameters of open() method as follows:
left = (screen.width – popupWinWidth) / 2
top = (screen.height – popupWinHeight) / 4
Example 2: This example creates the pop up window and placing it into center. 
html
<!DOCTYPE html><html>     <head>     <title>         Centered popup window        on the screen    </title></head> <body>    <h1>GeeksforGeeks</h1>         <p>        Centered popup window        on the screen    </p>         <script>        function createPopupWin(pageURL, pageTitle,                    popupWinWidth, popupWinHeight) {            var left = (screen.width - popupWinWidth) / 2;            var top = (screen.height - popupWinHeight) / 4;                         var myWindow = window.open(pageURL, pageTitle,                    'resizable=yes, width=' + popupWinWidth                    + ', height=' + popupWinHeight + ', top='                    + top + ', left=' + left);        }    </script>         <button onclick = "createPopupWin('https://www.geeksforgeeks.org',            'GeeksforGeeks Website', 1200, 650);">        GeeksforGeeks    </button></body> </html>
Output:
Before Clicking the button: 
After Clicking the button: 
simranarora5sos
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
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 ?
How to insert spaces/tabs in text using HTML/CSS?
How to lowercase column names 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 lowercase each letter in any specific column in given dataframe. Let’s see how to lowercase column names 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 lowercase column names in Pandas dataframe using lower() 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.lower()  df
Output: Method #2:
# 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.lower())
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.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
GATE 2017 Mock - GeeksforGeeks

28 Jun, 2021
Time Remaining ::
 In the present-day world, no individual or organization even 
think to plough a lonely furrow.
The plane _______ by the time we arrive at the airport in this slow traffic.
Call the doctor at once.
A    B    C    D (fix pen 2 in A)
2    1    4    3
2    4    1    3
2    3    4    1 - 3 cases

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial
Python – tensorflow.math.multiply()

10 Jun, 2020
TensorFlow is open-source python library designed by Google to develop Machine Learning models and deep learning  neural networks. multiply() is used to find element wise x*y. It supports broadcasting.
Syntax: tf.math.multiply(x, y, name)
Parameter:
x: It’s the input tensor. Allowed dtype for this tensor are bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128.
y: It’s the input tensor of same dtype as x.
name(optional): It’s defines the name for the operation.
Returns:It returns a tensor of same dtype as x.
Example 1:
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the input tensora = tf.constant([.2, .5, .7, 1], dtype = tf.float64)b = tf.constant([.1, .3, 1, 5], dtype = tf.float64)  # Printing the input tensorprint('a: ', a)print('b: ', b)  # Calculating resultres = tf.math.multiply(x = a, y = b)  # Printing the resultprint('Result: ', res)
Output:
a:  tf.Tensor([0.2 0.5 0.7 1. ], shape=(4, ), dtype=float64)
b:  tf.Tensor([0.1 0.3 1.  5. ], shape=(4, ), dtype=float64)
Result:  tf.Tensor([0.02 0.15 0.7  5.  ], shape=(4, ), dtype=float64)



Example 2: Complex number multiplication
Python3
# importing the libraryimport tensorflow as tf  # Initializing the input tensora = tf.constant([-2 + 3j, -5 + 4j, 7 + 2j, 1 + 7j], dtype = tf.complex128)b = tf.constant([-1 + 2j, -6 + 8j, 8 + 2j, 0 + 1j], dtype = tf.complex128)  # Printing the input tensorprint('a: ', a)print('b: ', b)  # Calculating resultres = tf.math.multiply(x = a, y = b)  # Printing the resultprint('Result: ', res)
Output:
a:  tf.Tensor([-2.+3.j -5.+4.j  7.+2.j  1.+7.j], shape=(4, ), dtype=complex128)
b:  tf.Tensor([-1.+2.j -6.+8.j  8.+2.j  0.+1.j], shape=(4, ), dtype=complex128)
Result:  tf.Tensor([-4. -7.j -2.-64.j 52.+30.j -7. +1.j], shape=(4, ), dtype=complex128)

Python Tensorflow-math-functions
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python regex to find sequences of one upper case letter followed by lower case letters

29 Dec, 2020
Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print ‘Yes’, otherwise ‘No’.
Examples:
Input : Geeks
Output : Yes

Input : geeksforgeeks
Output : No

 
Approach: Using re.search()
To check if the sequence of one upper case letter followed by lower case letters we use regular expression ‘[A-Z]+[a-z]+$‘.
# Python3 code to find sequences of one upper# case letter followed by lower case lettersimport re  # Function to match the stringdef match(text):                  # regex        pattern = '[A-Z]+[a-z]+$'                  # searching pattern        if re.search(pattern, text):                return('Yes')        else:                return('No')  # Driver Functionprint(match("Geeks"))print(match("geeksforGeeks"))print(match("geeks"))
Output:
Yes
Yes
No
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Iterate over characters of a string in Python
Python | Convert set into a list
Python min() Function

13 Aug, 2020
Python min() function returns the smallest of the value or smallest item in an iterable passed as its parameter. There are two types of min function –
min() functions with objects
min() functions with an iterable
Unlike the min() function of C/C++, the min() function in Python can take any type of object and returns the smallest among them. In the case of strings, it returns the lexicographically smallest value.
Syntax: min(a, b, c, ..., key=func)
Parameters:
a, b, c, .. : similar type of data.
key: A function to customize the sort order
Example:
Python3
# Python code to demonstrate the # working of min()  # printing the minimum of# 4, 12, 43.3, 19, 100print(min(4, 12, 43.3, 19, 100))  # printing the minimum of # a, b, c, d, eprint(min('a', 'b', 'c', 'd', 'e'))
Output:
4
a

To customize the sort order key parameter is passed in the min() function. 
Example:
Python3
# Python code to demonstrate the # working of min()      # find the string with minimum # lengths = min("GfG", "Geeks", "GeeksWorld", key = len)print(s)
Output:
GfG

min() functions throw TypeError when conflicting data types are compared.
Example:
Python3
# Python code to demonstrate the# Exception of min()     # printing the minimum of 4, 12, 43.3, 19, # "GeeksforGeeks" Throws Exception print(min(4, 12, 43.3, 19, "GeeksforGeeks"))
Output:
TypeError: unorderable types: str() < int()

When an iterable is passed to the min function it returns the smallest item of the iterable.
Syntax: min(iterable, default = obj, key = func)
Parameters:
iterable: An iterable like list, tuple, string
default: Default value that is returned when the iterable is empty
key: A function to customize the sort order
Example:
Python3
# Python code to demonstrate the# working of min()     # printing the minimum of [4, 12, 43.3, 19]print(min([4, 12, 43.3, 19]))  # printing the minimum of "GeeksforGeeks"print(min("GeeksforGeeks"))  # printing the minimum of ("A", "b", "C")print(min(("A", "a", "C")))
Output:
4
G
A

As seen above, to customize the sort order key parameter is passed in the min() function. 
Example:
Python3
# Python code to demonstrate the# working of min()           d = {1: "c", 2: "b", 3: "a"}  # printing the minimum key of# dictionaryprint(min(d))  # printing the key with minimum # value in dictionaryprint(min(d, key = lambda k: d[k]))
Output:
1
3

ValueError is raised when an empty iterable is passed without the default argument
Example:
Python3
# Python code to demonstrate the# Exception of min()     L = []  # printing the minimum empty listprint(min(L))
Output:
ValueError: min() arg is an empty sequence

Python-Built-in-functions
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
unordered_map operator[] in C++ STL

14 Dec, 2018
The std::unordered_map::operator[] is a built in function in C++ STL which returns the reference of value if key matches in the container. If no key is found then it inserts that key into container.Syntax:
mapped_type& operator[](key_type&& k);

Parameter: It takes parameter as key whose mapped value is accessed.Return type: Returns a reference associated to that key.
Example 1
// C++ code to illustrate the method// unordered_map operator[]#include <bits/stdc++.h>using namespace std;  int main(){    unordered_map<int, int> sample;      // Map initialization    sample = { { 1, 2 }, { 3, 4 }, { 5, 6 } };      // print element before doing    // any operations    for (auto& it : sample)        cout << it.first << " : " << it.second << endl;      // existing element is read    int m = sample[1];      // existing element is written    sample[3] = m;      // existing elements are accessed    sample[5] = sample[1];      // non existing element    // new element 25 will be inserted    m = sample[25];      // new element 10 will be inserted    sample[5] = sample[10];      // print element after doing    // operations    for (auto& it : sample)        cout << it.first << " : " << it.second << endl;    return 0;}
5 : 6
3 : 4
1 : 2
10 : 0
1 : 2
5 : 0
3 : 2
25 : 0

Example 2
// C++ code to illustrate the method// unordered_map operator[]#include <bits/stdc++.h>  using namespace std;  int main(){    unordered_map<char, int> sample;      // Map initialization    sample = { { 'a', 2 }, { 'b', 4 }, { 'c', 6 } };      // print element before doing    // any operations    for (auto& it : sample)        cout << it.first << " : " << it.second << endl;      // existing element is read    int m = sample['a'];      // existing element is written    sample['b'] = m;      // existing elements are accessed    sample['c'] = sample['a'];      // non existing element    // new element 'd' will be inserted    m = sample['d'];      // new element 'f' will be inserted    sample['c'] = sample['f'];      // print element after doing    // operations    for (auto& it : sample)        cout << it.first << " : " << it.second << endl;    return 0;}
c : 6
b : 4
a : 2
f : 0
a : 2
b : 2
c : 0
d : 0

Time Complexity O(n) in worst case.
cpp-unordered_map
cpp-unordered_map-functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
Given an example of C pointer addition and subtraction

Pointers have many but easy concepts and they are very important to C programming.
Two of the arithmetic pointer concepts are explained below, which are C pointer addition and subtraction respectively.
C pointer addition refers to adding a value to the pointer variable.
The formula is as follows −
new_address= current_address + (number * size_of(data type))
Following is the C program for C pointer addition −
 Live Demo
#include<stdio.h>
int main(){
   int num=500;
   int *ptr;//pointer to int
   ptr=#//stores the address of number variable
   printf("add of ptr is %u \n",ptr);
   ptr=ptr+7; //adding 7 to pointer variable
   printf("after adding add of ptr is %u \n",ptr);
   return 0;
}
When the above program is executed, it produces the following result −
add of ptr is 6422036
after adding add of ptr is 6422064
It subtracts a value from the pointer variable. Subtracting any number from a pointer variable will give an address.
The formula is as follows −
new_address= current_address - (number * size_of(data type))
Following is the C program for C pointer subtraction −
 Live Demo
#include<stdio.h>
int main(){
   int num=500;
   int *ptr;//pointer to int
   ptr=#//stores the address of number variable
   printf("addr of ptr is %u \n",ptr);
   ptr=ptr-5; //subtract 5 to pointer variable
   printf("after sub Addr of ptr is %u \n",ptr);
   return 0;
}
When the above program is executed, it produces the following result −
addr of ptr is 6422036
after sub Addr of ptr is 6422016
XSD - Element

Simple Element is an XML element which can only have text. It can not contain any attribute.
<xs:element name = "element-name" type = "element-type"/>

<xs:element name = "firstname" type = "xs:string"/> 

defines following element
<firstname></firstname>

<xs:element name = "firstname" type = "xs:string"/> 

<firstname>Dinkar</firstname>

Consider the following XML Elements
<name>Dinkar</name>
<marks>90</marks>
<birthdate>1985-05-23</birthdate>

XSD declarations for above XML elements will be as follows − 
<xs:element name = "name" type = "xs:string"/>
<xs:element name = "marks" type = "xs:integer"/>
<xs:element name = "birthdate" type = "xs:date"/>

A Simple Element can have a default value assigned. Default values are used in case an element does not have any text.
<xs:element name = "grade" type = "xs:string" default = "NA" /> 

Simple Element can have fix value assigend. In case, fixed value is assigned element can not have any text.
<xs:element name = "class" type = "xs:string" fixed = "1" />
execute_async_script driver method – Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around execute_async_script driver method in Selenium. execute_async_script method asynchronously Executes JavaScript in the current window/frame. This is a big feature of selenium, because javascript can do everything with a website from hitting APIs to playing with live code.
Syntax –
execute_async_script(script, *args)
Args –
script: The JavaScript to execute.
*args: Any applicable arguments for your JavaScript.
Example –Now one can use execute_async_script method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.execute_async_script("alert("alert via selenium")")

To demonstrate, execute_async_script method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # write scriptscript = "alert('Alert via selenium')"  # generate a alert via javascriptdriver.execute_async_script(script)
Output –Browser generates alert as verified below –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sum Of Two Numbers in PL/SQL

29 Dec, 2020
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. 
In declare part, we declare variables and between begin and end part, we perform the operations.
Here, first, we take three variables x, y, and z and assign the value in x and y and after addition of both the numbers, we assign the resultant value to z and print z.
Examples:  
Input : 15 25
Output : 40
Input : 250 400
Output : 650
Below is the required implementation: 
SQL
declare -- declare variable x, y-- and z of datatype numberx number(5);            y number(5);           z number(7);        begin -- Here we Assigning 10 into xx:=10;                 -- Assigning 20 into xy:=20;                 -- Assigning sum of x and y into zz:=x+y;                 -- Print the Resultdbms_output.put_line('Sum is '||z);end;/                        -- Program End
Output : 
Sum is 30
 
viswajit4u
SQL-PL/SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
CTE in SQL
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
Java Examples - Update Table Contents

How to update(delete, insert or update) contents of a table using JDBC connection?
Following method uses update, delete & insert SQL commands to edit or delete row contents.
import java.sql.*;

public class updateTable {
   public static void main(String[] args) {
      try {
         Class.forName("org.apache.derby.jdbc.ClientDriver");
      } catch(ClassNotFoundException e) {
         System.out.println("Class not found "+ e);
      }
      try {
         Connection con = DriverManager.getConnection (
            "jdbc:derby://localhost:1527/testDb","username", "password");
         
         Statement stmt = con.createStatement();
         String query1 = "update emp set name = 'ravi' where id = 2";
         String query2 = "delete from emp where id = 1";
         String query3 = "insert into emp values (1,'ronak','manager')";
         
         stmt.execute(query1);
         stmt.execute(query2);
         stmt.execute(query3);
         
         ResultSet rs = stmt.executeQuery("SELECT * FROM emp");
         System.out.println("id  name    job");
         
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String job = rs.getString("job");
            System.out.println(id+"   "+name+"    "+job);
         }
      } catch(SQLException e) {
         System.out.println("SQL exception occured" + e);
      }
   }
}
The above code sample will produce the following result. The result may vary.
id  name    job
2   ravi    trainee
1   ronak    manager

 Print
 Add Notes
 Bookmark this page
How to convert NumPy array to dictionary in Python? - GeeksforGeeks

23 Feb, 2022
The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.
To convert a numpy array to dictionary the following program uses dict(enumerate(array.flatten(), 1)) and this is what it exactly does: 
array.flatten: This function is used to get a copy of given array, collapsed into one dimension.
enumerate: Enumerate method comes with an automatic counter/index for each of the items present in the list. The first index value will start from 0
dict: this function is used to convert any object to dictionary.
Example 1:
Python3
# importing required librariesimport numpy as np # creating a numpy arrayarray = np.array([['a', 'b', 'c'],                  ['d', 'e', 'f'],                  ['g', 'h', 'i']]) # convert numpy array to dictionaryd = dict(enumerate(array.flatten(), 1)) # print numpy arrayprint(array)print(type(array)) # print dictionaryprint(d)print(type(d))
Output:
[[‘a’ ‘b’ ‘c’]
[‘d’ ‘e’ ‘f’]
[‘g’ ‘h’ ‘i’]]
<class ‘numpy.ndarray’>
{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’, 5: ‘e’, 6: ‘f’, 7: ‘g’, 8: ‘h’, 9: ‘i’}
<class ‘dict’>
Example 2:
Python3
# importing required librariesimport numpy as np # creating a numpy arrayarray = np.array([['1', '2', '3','4','5'],                  ['6', '7', '8','9','10'],                  ['11', '12', '13','14','15']]) # convert numpy array to dictionaryd = dict(enumerate(array.flatten(), 1)) # print numpy arrayprint(array)print(type(array)) # print dictionaryprint(d)print(type(d))
Output:
[[‘1’ ‘2’ ‘3’ ‘4’ ‘5’]
[‘6’ ‘7’ ‘8’ ‘9’ ’10’]
[’11’ ’12’ ’13’ ’14’ ’15’]]
<class ‘numpy.ndarray’>
{1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’, 5: ‘5’, 6: ‘6’, 7: ‘7’, 8: ‘8’, 9: ‘9’, 10: ’10’, 11: ’11’, 12: ’12’, 13: ’13’, 14: ’14’, 15: ’15’}
<class ‘dict’>
kashishsoda
varshagumber28
sumitgumber28
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
JUnit - Executing Tests

The test cases are executed using JUnitCore class. JUnitCore is a facade for running tests. It supports running JUnit 4 tests, JUnit 3.8.x tests, and mixtures. To run tests from the command line, run java org.junit.runner.JUnitCore <TestClass>. For one-shot test runs, use the static method runClasses(Class[]).
Following is the declaration for org.junit.runner.JUnitCore class:
public class JUnitCore extends java.lang.Object

Here we will see how to execute the tests with the help of JUnitCore.
Create a java class to be tested, say, MessageUtil.java, in C:\>JUNIT_WORKSPACE.
/*
* This class prints the given message on console.
*/

public class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   public MessageUtil(String message){
      this.message = message;
   }
      
   // prints the message
   public String printMessage(){
      System.out.println(message);
      return message;
   }   
	
}  
Create a java test class, say, TestJunit.java.
Create a java test class, say, TestJunit.java.
Add a test method testPrintMessage() to your test class.
Add a test method testPrintMessage() to your test class.
Add an Annotaion @Test to the method testPrintMessage().
Add an Annotaion @Test to the method testPrintMessage().
Implement the test condition and check the condition using assertEquals API of JUnit.
Implement the test condition and check the condition using assertEquals API of JUnit.
Create a java class file named TestJunit.java in C:\>JUNIT_WORKSPACE.
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class TestJunit {
	
   String message = "Hello World";	
   MessageUtil messageUtil = new MessageUtil(message);

   @Test
   public void testPrintMessage() {
      assertEquals(message,messageUtil.printMessage());
   }
}
Now create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
		
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
		
      System.out.println(result.wasSuccessful());
   }
}  	
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java

Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner

Verify the output.
Hello World
true


    24 Lectures 
     2.5 hours 

 Nishita Bhatt

    56 Lectures 
     7.5 hours 

 Dinesh Varyani
 Print
 Add Notes
 Bookmark this page
What is Docker Images?

09 Jun, 2022
Docker Image is an executable package of software that includes everything needed to run an application. This image informs how a container should instantiate, determining which software components will run and how. Docker Container is a virtual environment that bundles application code with all the dependencies required to run the application. The application runs quickly and reliably from one computing environment to another.
Running Instances from DockerFile
Follow the below steps to create a Docker Image and run a Container:
Step 1: Create a Dockerfile.
Step 2: Run the following command in the terminal and it will create a docker image of the application and download all the necessary dependencies needed for the application to run successfully.
docker build -t <name to give to your image>
This will start building the image.
Step 3:  We have successfully created a Dockerfile and a respective Docker image for the same.
Step 4: Run the following command in the terminal and it will create a running container with all the needed dependencies and start the application.
docker run -p 9000:80 <image-name>
The 9000 is the port we want to access our application on. 80 is the port the container is exposing for the host to access.
 List images:
docker ls
Pull an image from a registry:
docker image pull <image-name>
Remove an Image from Docker:
docker rmi <id-of-image>
khushb99
docker
Picked
TrueGeek-2021
Docker
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
How to Convert Char to String in Java?
Basics of API Testing Using Postman
Types of Internet Protocols
Can a try block have multiple catch blocks in Java?

Yes, you can have multiple catch blocks for a single try block.
The following Java program contains an array of numbers (which is displayed). from user it accepts two positions from this array and, divides the number in first position with the number in second position.
While entering values −
If you choose a position which is not in the displayed array an ArrayIndexOutOfBoundsException is thrown
If you choose a position which is not in the displayed array an ArrayIndexOutOfBoundsException is thrown
If you choose 0 as denominator and ArithmeticException is thrown.
If you choose 0 as denominator and ArithmeticException is thrown.
In this program we have handled all the possible exceptions using two different catch blocks.
 Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class MultipleCatchBlocks {
   public static void main(String [] args) {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Enter 3 integer values one by one: ");
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }
      catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Warning: You have chosen a position which is not in the array");
      }
      catch(ArithmeticException e) {
         System.out.println("Warning: You cannot divide an number with 0");
      }
   }
}
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)
2
8
Warning: You have chosen a position which is not in the array
Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
1
4
Warning: You cannot divide an number with 0
turtle.degrees() function in Python

01 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to set angle measurement units to degrees. By default the angle measurement unit is “degrees”.
Syntax: turtle.degrees(fullcircle=360.0)
Parameter:
fullcircle(optional): a number. Set angle measurement units, i.e. set number of ‘degrees’ for a full circle. Default value is 360 degrees.
Below is the implementation of the above method with an example :
Python3
# importing packageimport turtle  # set turtle speedturtle.speed(1)  # forward turtle by 100turtle.forward(100)  # turn the turtle (degrees)turtle.left(90)  # print headingprint(turtle.heading())  # move forward by 100turtle.forward(100)  # set to radiansturtle.radians()  # turn to left by 90 (radians)turtle.left(1.57079633)  # print headingprint(turtle.heading())  # move forward by 100turtle.forward(100)  # set to radiansturtle.degrees()  # turn to left by 90 (degrees)turtle.left(90)  # print headingprint(turtle.heading())
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
HTTP headers | X-Content-Type-Options

14 Sep, 2021
The HTTP headers X-Content-Type-Options acts as a marker that indicates the MIME-types headers in the content types headers should not be changed to the server. This header was introduced in the Internet Explorer 8 of Microsoft. This header block the content sniffing (non-executable MIME type into executable MIME type). After that, all the other browsers also introduce the X-Content-Type-Options, and their MIME sniffing algorithms were less aggressive. 
Syntax:  
x-content-type-options: nosniff
Directives: There is a single directive accepted by X-Content-Type-Options header.  
nosniff: It blocks all request if there “style” MIME-type is not text/css and JavaScript MIME-type. Plus it enables the cross origin if there MIME-Type text/html, text/plain, text/jason, application/jason and any type of xml extension.
Example:  
x-content-type-options: nosniff
To check the X-Content-Type-Options in action go to Inspect Element -> Network check the request header for x-content-type-options like below. 
Supported Browsers: The browsers compatible with x-content-type-options header are listed below: 
Google Chrome
Internet Explorer
Firefox
Opera
singghakshay
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add a column in an R data frame with consecutive numbers?

Addition of a column with consecutive might have different objectives such as getting the sequence of numbers, representing serial numbers, representing ids, identification of each row, or a variable. We can use the sequence starting from any number up to the number of rows if we know the number of rows for this purpose.
Consider the below data frame:
Live Demo
> x1<-rnorm(20,5,1.12)
> x2<-rnorm(20,5,0.34)
> df1<-data.frame(x1,x2)
> df1
     x1       x2
1 6.137898 5.203712
2 5.283467 5.057344
3 5.873749 4.907388
4 7.628762 5.012650
5 4.134700 4.988379
6 5.340686 4.684900
7 5.126999 4.821752
8 3.722762 4.974044
9 4.097969 5.284176
10 4.249122 4.503324
11 5.511502 5.355315
12 5.826045 4.853419
13 4.947602 5.512752
14 7.174369 5.320503
15 4.671888 5.100163
16 3.777945 4.893680
17 3.591266 4.715214
18 4.270032 4.776928
19 6.913433 4.828765
20 4.619279 5.138295
Adding a column of consecutive numbers:
> df1$consecutive_numbers<-1:nrow(df1)
> df1
  x1 x2 consecutive numbers
1 6.137898 5.203712    1
2 5.283467 5.057344    2
3 5.873749 4.907388    3
4 7.628762 5.012650    4
5 4.134700 4.988379    5
6 5.340686 4.684900    6
7 5.126999 4.821752    7
8 3.722762 4.974044    8
9 4.097969 5.284176    9
10 4.249122 4.503324  10
11 5.511502 5.355315  11
12 5.826045 4.853419  12
13 4.947602 5.512752  13
14 7.174369 5.320503  14
15 4.671888 5.100163  15
16 3.777945 4.893680  16
17 3.591266 4.715214  17
18 4.270032 4.776928  18
19 6.913433 4.828765  19
20 4.619279 5.138295  20
Live Demo
> y1<-rpois(20,5)
> y2<-rpois(20,8)
> df2<-data.frame(y1,y2)
> df2
 y1 y2
1 4 7
2 11 7
3 5 5
4 3 8
5 6 5
6 4 8
7 6 6
8 2 10
9 1 8
10 6 6
11 6 5
12 2 10
13 4 3
14 1 12
15 5 9
16 4 8
17 5 8
18 4 2
19 6 10
20 4 8
Adding a column of consecutive numbers:
> df2$consecutive_numbers<-101:120
> df2
 y1 y2 consecutive numbers
1 4 7     101
2 11 7    102
3 5 5     103
4 3 8     104
5 6 5     105
6 4 8     106
7 6 6     107
8 2 10    108
9 1 8     109
10 6 6    110
11 6 5    111 
12 2 10   112
13 4 3    113
14 1 12   114
15 5 9    115
16 4 8    116
17 5 8    117
18 4 2    118
19 6 10   119
20 4 8    120