code-rag-bench/online-tutorials huggingface dataset:
How can I select date from a datepicker div using Selenium Webdriver?

We can select data from a datepicker using Selenium webdriver. A datepicker in a calendar can be designed in numerous ways on the web UI. Based on the UI, we have to design our test.
A calendar may have a dropdown for selection of day, month or year. It may also contain forward and backward navigation to move up and down in the dates or any other design. The below example shows a calendar having a datepicker. Let us make an attempt to select the date 03/02/2021(2nd March, 2021) date from the below calendar −
In the above html code, we can see the calendar within a table tag identified by the <table> and its dates are represented by the rows and columns having the <tr> and the <td> tags respectively(tr being the parent of td). To select a date, we need to identify all the elements having <td> tag using the findElements method.
This method returns a list of matching elements. We have to traverse through this list and check a specific date with the help of the getText method. Once we encounter the required date, we shall select it and break out from the loop.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import java.util.List;
public class DtPicker{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://jqueryui.com/datepicker");
      //switch to frame
      WebElement f = driver .findElement(By.xpath("//iframe[@class='demo-frame']"));
      driver.switchTo().frame(f);
      //identify element within frame
      WebElement l = driver.findElement(By.id("datepicker"));
      l.click();
      //identify all td elements in list
      List<WebElement> t =driver.findElements(By.xpath("//table/tbody/tr/td"));
      //list traversal
      for (int k = 0; k<t.size(); k++) {
         //check date
         String dt = t.get(k).getText();
         if (dt.equals("2")) {
            t.get(k).click();
            break;
         }
      }
      //obtain selected date
      String v = l.getAttribute("value");
      System.out.print("Date selected by date picker: "+ v);
      //close browser
      driver.close();
   }
}
Angular Google Charts - Environment Setup

This tutorial will guide you on how to prepare a development environment to start your work with Google Charts and Angular Framework. In this chapter, we will discuss the Environment Setup required for Angular 6. To install Angular 6, we require the following −
Nodejs
Npm
Angular CLI
IDE for writing your code
Nodejs has to be greater than 8.11 and npm has to be greater than 5.6.
To check if nodejs is installed on your system, type node -v in the terminal. This will help you see the version of nodejs currently installed on your system.
C:\>node -v
v8.11.3

If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS.
Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm -v in the terminal. It should display the version of the npm.
C:\>npm -v
5.6.0

Angular 6 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command.
Type npm install -g @angular/cli, to install angular cli on your system.
You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc.
Run the following command to install Google Charts Wrapper module in the project created.
googleChartsApp> npm angular-google-charts

+ angular-google-charts@0.1.0
added 2 packages in 20.526s

Add the following entry in app.module.ts file
import { GoogleChartsModule } from 'angular-google-charts';

imports: [
   ...
   GoogleChartsModule
],

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Python OpenCV – Background Subtraction

22 Jun, 2020
Background Subtraction is one of the major Image Processing tasks. It is used in various Image Processing applications like Image Segmentation, Object Detection, etc. OpenCV provides us 3 types of Background Subtraction algorithms:-
BackgroundSubtractorMOG
BackgroundSubtractorMOG2
BackgroundSubtractorGMG
Normally, we can perform background Subtraction using matrix subtraction, i.e, just subtracting the static frame from the video. But this has a lot of drawbacks. It is a very less efficient algorithm for Background subtraction because it does not update itself. This problem is being handled by the Background Subtraction algorithms provided by OpenCV.
To use BackgroundSubtractorMOG we can use
cv2.bgsegm.createBackgroundSubtractorMOG()
Then we can apply it using the “apply” method on each frame of the video. Consider the below example for a better understanding of the topic.
Example:
import numpy as npimport cv2  cap = cv2.VideoCapture('sample.mp4')  # initializing subtractor fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()   while(1):    ret, frame = cap.read()             # applying on each frame    fgmask = fgbg.apply(frame)        cv2.imshow('frame', fgmask)    k = cv2.waitKey(30) & 0xff    if k == 27:        break  cap.release()cv2.destroyAllWindows()
Output :
In the previous subtractor worked fairly well but in real-world situations, there is also a presence of shadows. In BackgroundSubtractorMOG2, we can also detect shadows and in the output of the following code, it’s clearly seen. To apply BackgroundSubtractorMOG2, use
cv2.createBackgroundSubtractorMOG2()
Example:
import numpy as npimport cv2  cap = cv2.VideoCapture('sample.mp4')  # initializing subtractor fgbg = cv2.createBackgroundSubtractorMOG2()  while(1):    ret, frame = cap.read()       # applying on each frame    fgmask = fgbg.apply(frame)      cv2.imshow('frame', fgmask)      k = cv2.waitKey(30) & 0xff    if k == 27:        break  cap.release()cv2.destroyAllWindows()
Output :
This algorithm combines statistical background image estimation and per-pixel Bayesian segmentation. It employs a probabilistic foreground segmentation algorithm that identifies possible foreground objects using Bayesian inference. To use BackgroundSubtractorGMG, use
cv2.bgsegm.createBackgroundSubtractorGMG()
Note: We will get a black window during first few frames.
import numpy as npimport cv2  cap = cv2.VideoCapture('sample.mp4')  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))  # initializing subtractor fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()  while(1):    ret, frame = cap.read()      # applying on each frame    fgmask = fgbg.apply(frame)      fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)           cv2.imshow('frame', fgmask)    k = cv2.waitKey(30) & 0xff    if k == 27:        break  cap.release()cv2.destroyAllWindows()
Output :
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java toDegrees() method with Example

12 Apr, 2018
The java.lang.Math.toDegrees() is used to convert an angle measured in radians to an approximately equivalent angle measured in degrees.
Note: The conversion from radians to degrees is generally inexact; users should not expect cos(toRadians(90.0)) to exactly equal 0.0.
Syntax:
public static double toDegrees(double rad)

Parameter:
rad : This parameter is an angle in radians which
we want to convert in degrees.
Return :
This method returns the measurement of the angle 
rad in degrees.

Example: To show working of java.lang.Math.toDegrees() method.
// Java program to demonstrate working// of java.lang.Math.toDegrees() methodimport java.lang.Math;  class Gfg {      // driver code    public static void main(String args[])    {        // value of PI in degrees        double rad = Math.PI;        System.out.println(Math.toDegrees(rad));          // value of PI/2 in degrees        rad = (Math.PI) / 2;        System.out.println(Math.toDegrees(rad));          // value of PI/4 in degrees        rad = (Math.PI) / 4;        System.out.println(Math.toDegrees(rad));    }}
Output:
180.0
90.0
45.0

Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Monitors in Process Synchronization

30 Sep, 2019
The monitor is one of the ways to achieve Process synchronization. The monitor is supported by programming languages to achieve mutual exclusion between processes. For example Java Synchronized methods. Java provides wait() and notify() constructs.
It is the collection of condition variables and procedures combined together in a special kind of module or a package.The processes running outside the monitor can’t access the internal variable of the monitor but can call procedures of the monitor.Only one process at a time can execute code inside monitors.
It is the collection of condition variables and procedures combined together in a special kind of module or a package.
The processes running outside the monitor can’t access the internal variable of the monitor but can call procedures of the monitor.
Only one process at a time can execute code inside monitors.
Syntax:
Condition Variables:Two different operations are performed on the condition variables of the monitor.
Wait.
signal.

let say we have 2 condition variablescondition x, y; // Declaring variable
 
Wait operationx.wait() : Process performing wait operation on any condition variable are suspended. The suspended processes are placed in block queue of that condition variable.
Note: Each condition variable has its unique block queue.
 
Signal operationx.signal(): When a process performs signal operation on condition variable, one of the blocked processes is given chance.
If (x block queue empty)
  // Ignore signal
else
  // Resume a process from block queue.
Advantages of Monitor:Monitors have the advantage of making parallel programming easier and less error prone than using techniques such as semaphore.
Disadvantages of Monitor:Monitors have to be implemented as part of the programming language . The compiler must generate code for them. This gives the compiler the additional burden of having to know what operating system facilities are available to control access to critical sections in concurrent processes. Some languages that do support monitors are Java,C#,Visual Basic,Ada and concurrent Euclid.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shivanshukumarsingh1
Process Synchronization
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove all duplicates words from a given sentence

27 Jun, 2022
Given a sentence containing n words/strings. Remove all duplicates words/strings which are similar to each others.Examples:  
Input : Geeks for Geeks
Output : Geeks for

Input : Python is great and Java is also great
Output : is also Java Python and great
 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
We can solve this problem quickly using python Counter() method. Approach is very simple.1) Split input sentence separated by space into words. 2) So to get all those strings together first we will join each string in given list of strings. 3) Now create a dictionary using Counter method having strings as keys and their frequencies as values. 4) Join each words are unique to form single string. 
Python
from collections import Counter  def remov_duplicates(input):      # split input string separated by space    input = input.split(" ")      # now create dictionary using counter method    # which will have strings as key and their     # frequencies as value    UniqW = Counter(input)      # joins two adjacent elements in iterable way    s = " ".join(UniqW.keys())    print (s)  # Driver programif __name__ == "__main__":    input = 'Python is great and Java is also great'    remov_duplicates(input)
and great Java Python is also
Alternative Method:-  
Python
# Program without using any external librarys = "Python is great and Java is also great"l = s.split()k = []for i in l:      # If condition is used to store unique string     # in another list 'k'     if (s.count(i)>=1 and (i not in k)):        k.append(i)print(' '.join(k))
Python is great and Java also
Method 3: Another shorter implementation:
Python3
# Python3 program  string = 'Python is great and Java is also great'  print(' '.join(dict.fromkeys(string.split())))
Python is great and Java also
Divyu_Pandey
ehtishamulhuq7
abhi35
Python dictionary-programs
Python string-programs
python-dict
python-string
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change the title bar in Tkinter?

Tkinter initially sets a default title bar for every application. We can update or replace the Title Bar of the Tkinter application by configuring the title("Enter any Title") method. For a particular application, let us see how we can change the title of a Tkinter application that calculates the square of a number.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
import math

#Create an instance of Tkinter frame
win = Tk()

#Set the geometry of tkinter frame
win.geometry("750x270")

#Set the Title of Tkinter window
win.title("Square Calculator")

def find_square():
   no= int(entry.get())
   Label(win, text=no*no).pack()

#Create an entry widget to accept user input
entry= Entry(win, width=40)
entry.pack(ipadx= 20,pady=20)

#Create a button to calculate the number
ttk.Button(win, text= "Calculate", command= find_square).pack()
win.mainloop()
The above program calculates the square of the given number in the Entry widget. Thus, the program window Title has been renamed to "Square Calculator".
Minkowski distance in Python

The Minkowski distance is a metric and in a normed vector space, the result is Minkowski inequality. Minkowski distance is used for distance similarity of vector.
scipy.spatial.distance.minkowski
>>> from scipy.spatial import distance
>>> distance.minkowski([1, 0, 0], [0, 1, 0], 1)
2.0
>>> distance.minkowski([1, 0, 0], [0, 1, 0], 2)
1.4142135623730951
>>> distance.minkowski([1, 0, 0], [0, 1, 0], 3)
1.2599210498948732
>>> distance.minkowski([1, 1, 0], [0, 1, 0], 1)
1.0
>>> distance.minkowski([1, 1, 0], [0, 1, 0], 2)
1.0
>>> distance.minkowski([1, 1, 0], [0, 1, 0], 3)
1.0

from math import *
from decimal import Decimal
def my_p_root(value, root):
   my_root_value = 1 / float(root)
   return round (Decimal(value) **
   Decimal(my_root_value), 3)
def my_minkowski_distance(x, y, p_value):
   return (my_p_root(sum(pow(abs(a-b), p_value)
      for a, b in zip(x, y)), p_value))
# Driver Code
vector1 = [0, 2, 3, 4]
vector2 = [2, 4, 3, 7]
my_position = 5
print("The Distance is::",my_minkowski_distance(vector1, vector2, my_position))
The Distance is:: 3.144
innerHTML vs innerText in JavaScript.

innerHTML − The innerHTML property returns the text, including all spacing and inner element tags. It preserves the formatting of the text and all the extra tags like <b>, <i> etc.
innerText − The innerText property returns just the text, removing the spacing and the inner element tags.
Following is the code for innerHTML and innerText in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>innerHTML vs innerText</h1>
<div class="sample">Hello <b>World</b> <i>Some Text</i></div>
<div class="result">innerHTML =</div>
<div class="result">innerText =</div>
<button class="Btn">Click here</button>
<h3>Click on the above button to see the innerText and innerHTML result for
the above paragraph</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelectorAll(".result");
   let sampleEle = document.querySelector(".sample");
   let a;
   BtnEle.addEventListener("click", () => {
      resEle[0].innerHTML += sampleEle.innerHTML;
      resEle[1].innerHTML += sampleEle.innerText;
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
What is super() function in JavaScript?

Use the super() function to call the constructor of the parent class and access functions on an object's parent class.
You can try to run the following code to implement super()
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         class Department {
            constructor() {}
            static msg() {
               return 'Hello';
            }
         }
         class Employee extends Department {
            constructor() {}
            static displayMsg() {
               return super.msg() + ' World!';
            }
         }
         document.write(Employee.displayMsg());
      </script>
   </body>
</html>
How do I check for null values in JavaScript?

To check for null values in JavaScript, you need to check the variable value with null. Use the JavaScript strict equality operator to achieve this.
You can try to run the following code to check whether the value of the variable is null or not −
<html>
   <head>
      <title>JavaScript Strict Equality Operator</title>
   </head>
   <body>
      <script>
         var a = 10;
         if(a === null) {
            document.write("Value is null");
         } else {
            document.write("Value is not null");
         }
      </script>
   </body>
</html>
NumPy Array Indexing

Array indexing is the same as accessing an array element.
You can access an array element by referring to its index number.
The indexes in NumPy arrays start with 0, meaning that the first element  
has index 0, and the second has index 1 etc.
Get the first element from the following array:
Get the second element from the following array.
Get third and fourth elements from the following array and add them.
To access elements from 2-D arrays we can use comma separated integers representing 
the 
dimension and the index of the element.
Think of 2-D arrays like a table with rows and columns, where the row 
represents the dimension and the index represents the column.
Access the element on the first row, second column:
Access the element on the 2nd row, 5th column:
To access elements from 3-D arrays we can use comma separated integers representing 
the dimensions and the index of the element.
Access the third element of the second array of the first array:
arr[0, 1, 2] prints the value 6.
And this is why:
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]
The second number represents the second dimension, which also contains two arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]
The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6
Use negative indexing to access an array from the end.
Print the last element from the 2nd dim:
Insert the correct syntax for printing the first item in the array.
arr = np.array([1, 2, 3, 4, 5])

print(arr)

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
toupper() function in C - GeeksforGeeks

04 Aug, 2021
The toupper() function is used to convert lowercase alphabet to uppercase. i.e. If the character passed is a lowercase alphabet then the toupper() function converts a lowercase alphabet to an uppercase alphabet. It is defined in the ctype.h header file.Syntax:  
int toupper(int ch);
Parameter: It accepts a single parameter: 
ch: This represents the character to be converted to uppercase.
Returns: This function returns the uppercase character corresponding to the ch.Below programs illustrate the toupper() function in C:Example 1:- 
c
// C program to demonstrate// example of toupper() function.#include <ctype.h>#include <stdio.h> int main(){    char ch;     ch = 'g';    printf("%c in uppercase is represented as  %c",           ch, toupper(ch));     return 0;}
g in uppercase is represented as  G
 
Example 2:- 
C
// C program to demonstrate// example of toupper() function.#include <ctype.h>#include <stdio.h> int main(){    int j = 0;    char str[] = "geekforgeeks\n";    char ch;     while (str[j]) {        ch = str[j];        putchar(toupper(ch));        j++;    }     return 0;}
GEEKFORGEEKS
 
Note:  
 If the character passed in the toupper() is any of these three
1. uppercase character
2. special symbol
3. digit
toupper() will return the character as it is.                      
Example :
C
// C program to demonstrate// example of toupper() function.#include <ctype.h>#include <stdio.h> int main(){    int j = 0;    char str[] = "GeEks@123\n";    char ch;     while (str[j]) {        ch = str[j];        putchar(toupper(ch));        j++;    }     return 0;}// code is contributed by codersaty
Output:
GEEKS@123
CoderSaty
simranarora5sos
C-Functions
C-String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Structures in C
How to change the font size of textView in android?

This example demonstrates how do I change the font size of TextView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Im Huge"
      android:fontFamily="sans-serif-smallcaps"
      android:layout_centerInParent="true"
      android:textSize="64sp" />
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/textView1"
      android:layout_marginBottom="10dp"
      android:text="Im small"
      android:layout_centerInParent="true"
      android:fontFamily="serif-monospace"
      android:textSize="36sp" />
   <TextView
      android:id="@+id/textView3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/textView2"
      android:layout_marginBottom="10dp"
      android:text="Im tiny"
      android:layout_centerInParent="true"
      android:fontFamily="serif-monospace"
      android:textSize="24sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
CloneNode() method in JavaScript?

It is a method used to clone an element from one list to another list. The cloneNode(), provided by javascript, the method creates a copy of a node and returns the clone. It can clone all attributes and their values. 
node.cloneNode();
In the following example, initially, two lists were created and then using the javascript method "cloneNode()" one of the elements in the second list is cloned, nothing but copied, to the first list and the result is displayed as shown in the output.
<html>
<body>
   <ul id="List1"><li>Tesla</li><li>SolarCity</li></ul>
   <ul id="List2"><li>Spacex</li><li>Hyperloop</li></ul>
<script>
   var item = document.getElementById("List2").firstChild;
   var cln = item.cloneNode(true);
   document.getElementById("List1").appendChild(cln);
</script>
</body>
</html>
Tesla
SolarCity
Spacex

Spacex
Hyperloop
set::empty() in C++ STL - GeeksforGeeks

17 Jun, 2020
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
empty() function is used to check if the set container is empty or not.
Syntax :
setname.empty()
Parameters :
No parameters are passed.
Returns :
True, if set is empty
False, Otherwise

Examples:
Input  : myset{1, 2, 3, 4, 5};
         myset.empty();
Output : False

Input  : myset{};
         myset.empty();
Output : True

Errors and Exceptions
1. It has a no exception throw guarantee.2. Shows error when a parameter is passed.
// INTEGER SET// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <set>using namespace std;  int main(){    // set declaration    set<int> myset{};      // checking if set is empty    if (myset.empty()) {        cout << "True";    }    else {        cout << "False";    }    return 0;}
Output:
True

// CHARACTER SET// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <set>using namespace std;  int main(){    // set declaration    set<char> myset{ 'A', 'b' };      // checking if set is empty    if (myset.empty()) {        cout << "True";    }    else {        cout << "False";    }
Output:
False

Time Complexity : O(1)
Application :Given a set of integers, find the sum of the all the integers.
Input  : 1, 5, 6, 3, 9, 2
Output : 26
Explanation -  1+5+6+3+9+2 = 26
Algorithm
1. Check if the set is empty, if not add the first element to a variable initialised as 0, and erase the first element.2. Repeat this step until the set is empty.3. Print the final value of the variable.
// CPP program to illustrate// Application of empty() function#include<iostream>#include<set>   using namespace std;   int main(){    // sum variable declaration    int sum = 0;       // set declaration    set<int> myset{ 1, 5, 6, 3, 9, 2 };       // finding sum of elements    while(!myset.empty()){        sum+= *myset.begin();        myset.erase(myset.begin());    }          // print sum     cout<<sum<<endl;    return 0;}
Output:
26

prabhusatyam44
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Inline Functions in C++
Convert string to char array in C++
How to Install Matplotlib on Windows? - GeeksforGeeks

09 Sep, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
In this article, we will look into the various process of installing Matplotlib on Windows.
The only thing that you need for installing Numpy on Windows are:
Python 
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda, you can use the below command:
conda install matplotlib
Type y for yes when prompted.
You will get a similar message once the installation is complete
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
Users who prefer to use pip can use the below command to install Matplotlib:
pip install matplotlib
You will get a similar message once the installation is complete:
To verify if Matplotlib has been successfully installed in your system run the below code in a python IDE of your choice:
Python3
import matplotlibmatplotlib.__version__
If successfully installed you will get the following output.
Blogathon-2021
how-to-install
Picked
Python-matplotlib
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
Python | Pandas Series.iteritems() - GeeksforGeeks

12 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.iteritems() function iterates over the given series object. the function iterates over the tuples containing the index labels and corresponding value in the series.
Syntax: Series.iteritems()
Parameter : None
Returns : tuples
Example #1: Use Series.iteritems() function to iterate over all the elements in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.iteritems() function to iterate over all the elements in the given series object.
# iterate over all the elementsfor items in sr.iteritems():    print(items)
Output :
As we can see in the output, the Series.iteritems() function has successfully iterated over all the elements in the given series object. Example #2 : Use Series.iteritems() function to iterate over all the elements in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.iteritems() function to iterate over all the elements in the given series object.
# iterate over all the elementsfor items in sr.iteritems():    print(items)
Output :
As we can see in the output, the Series.iteritems() function has successfully iterated over all the elements in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
PLSQL | ASCII Function - GeeksforGeeks

18 Sep, 2019
The string in PL/SQL is actually a sequence of characters with an optional size specification.The characters could be numeric, letters, blank, special characters or a combination of all.The ASCII Function in PLSQL is used to return the NUMBER code that represents the specified character.
Syntax
ASCII( single_character )
Parameters Used:
single_character – It is used to retrieve the NUMBER code for the specified character.If more than one character is entered, the ASCII function will return the value for the first character and ignore all of the characters after the first.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example:
DECLARE 
   Test_Char char := 'A';
   Test_Char2 char := 'H';
   Test_String varchar2(6) := 'Hello';
   
BEGIN 
   dbms_output.put_line(ASCII(Test_Char)); 
   dbms_output.put_line(ASCII(Test_Char2)); 
   dbms_output.put_line(ASCII(Test_String)); 
    
END; 
Output:
65
72
72
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
CTE in SQL
SQL | Views
Difference between DELETE, DROP and TRUNCATE
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL Interview Questions
What is Temporary Table in SQL?
MySQL | Group_CONCAT() Function
Difference between Where and Having Clause in SQL
Fetch multiple documents in MongoDB query with OR condition?

Let us create a collection with documents −
> db.demo362.insertOne({"ClientName":"John","ClientProject":"School Management System"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a77454a481fef8ec7a1c")
}
> db.demo362.insertOne({"ClientName":"David","ClientProject":"Library Management System"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a78454a481fef8ec7a1d")
}
> db.demo362.insertOne({"ClientName":"Mike","ClientProject":"Event Tracker"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a7a054a481fef8ec7a1e")
}
> db.demo362.insertOne({"ClientName":"Carol","ClientProject":"Hospital Management System"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56a7b754a481fef8ec7a1f")
}
Display all documents from a collection with the help of find() method −
> db.demo362.find();
This will produce the following output −
{ "_id" : ObjectId("5e56a77454a481fef8ec7a1c"), "ClientName" : "John", "ClientProject" : "School Management System" }
{ "_id" : ObjectId("5e56a78454a481fef8ec7a1d"), "ClientName" : "David", "ClientProject" : "Library Management System" }
{ "_id" : ObjectId("5e56a7a054a481fef8ec7a1e"), "ClientName" : "Mike", "ClientProject" : "Event Tracker" }
{ "_id" : ObjectId("5e56a7b754a481fef8ec7a1f"), "ClientName" : "Carol", "ClientProject" : "Hospital Management System" }
Following is the query to fetch multiple documents −
> db.demo362.find({$or: [{"ClientName":"John"}, {"ClientProject": "Event Tracker" }]});
This will produce the following output −
{ "_id" : ObjectId("5e56a77454a481fef8ec7a1c"), "ClientName" : "John", "ClientProject" : "School Management System" }
{ "_id" : ObjectId("5e56a7a054a481fef8ec7a1e"), "ClientName" : "Mike", "ClientProject" : "Event Tracker" }
Evaluate the expression | Practice | GeeksforGeeks

Given a number n, find the value of below expression:
            f(n-1)*f(n+1) - f(n)*f(n)    where f(n) is nth Fibonacci. 
 
Example 1:
Input : n = 5
Output: -1
Explanation: f(4) = 3, f(5) = 5
f(6) = 8. 3 * 8 - 5 * 5 = -1

Example 2:
Input: n = 3
Output: 1
Explanation: f(2) = 1, f(3) = 2
and f(4) = 3. 1 * 3 - 2 * 2 = -1

 
Your Task:
You don't need to read or print anything. Yous task is to complete the function evaluate_exp() which takes n as input parameter and returns the value of the given expression.
 
Expected Time Complexity: O(1)
Expected Space Complexity: O(1)
 
Constraints:
1 <= n <= 1018
0
gurucharanchouhan171 month ago
One Line Code in Java :)
 return n%2==0?1:-1;
0
jonnakutieshwar134 months ago
 int evaluate_exp(int n){       // Code here       if(n%2==0)         return 1;       return -1;   } 
0
Babita Kumari1 year ago
Babita Kumari
//correct Answer.....Execution time:0.01
int evaluate_exp(int n){
     if(n & 1)         return -1;     else         return 1;
       // Code here   }
0
SOURABH GOLCHHA3 years ago
SOURABH GOLCHHA
really @harshit97:disqus  F(N) should be defined clearly............?
0
Harshit Agarwal5 years ago
Harshit Agarwal
Please mention that f(n) means nth Fibonacci number.This should have been made clear in the question.
0
Jihye Sofia Seo5 years ago
Jihye Sofia Seo
Is f an identity, in other words, f(n) =n for all n?
0
Anshu Jha5 years ago
Anshu Jha
EITHERoutput should be   -1 all time..OR f( n)  should be defined...
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Creating Dictionary using Javascript

Let's create a MyMap class so that it doesn't hide the actual Map class in JS. We'll create a container object that'll keep track of all our values that we add to the map. We'll also create a display function that prints the map for us. 
class MyMap {
   constructor() {
      this.container = {};
   }
   display() {
      console.log(this.container);
   }
}
In ES6, you can directly create a dictionary using the Map class. For example, 
const map1 = new Map();
const map2 = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);
We need to define the hasKey method so that we can check if a key is already there. We will use this method while removing elements and setting new values. 
hasKey(key) {
   return key in this.container;
}
In ES6, you can check if a key exists in a map using the has method. For example, 
const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);
console.log(myMap.has("key1"))
console.log(myMap.has("key3"))
This will give the output −
True
False
How to get the mean of a specific column in a dataframe in Python?

Sometimes, it may be required to get the mean value of a specific column that is numeric in nature. This is where the ‘mean’ function can be used.
The column whose mean needs to be computed can be indexed to the dataframe, and the mean function can be called on this using the dot operator.
The index of the column can also be passed to find the mean. The term mean() refers to finding the sum of all values and dividing it by the total number of values in the dataset.
Let us see a demonstration of the same −
 Live Demo
import pandas as pd
my_data = {'Name':pd.Series(['Tom','Jane','Vin','Eve','Will']),'Age':pd.Series([45, 67, 89, 12, 23]),'value':pd.Series([8.79,23.24,31.98,78.56,90.20])}
print("The dataframe is :")
my_df = pd.DataFrame(my_data)
print(my_df)
print("The mean of column 'Age' is :")
print(my_df['Age'].mean())
print("The mean of column 'value' is :")
print(my_df['value'].mean())
The dataframe is :
   Name  Age   value
0  Tom   45    8.79
1  Jane  67   23.24
2  Vin   89   31.98
3  Eve  12    78.56
4  Will  23   90.20
The mean of column 'Age' is :
47.2
The mean of column 'value' is :
46.553999999999995
The required libraries are imported, and given alias names for ease of use.
The required libraries are imported, and given alias names for ease of use.
Dictionary of series consisting of key and value is created, wherein a value is actually a series data structure.
Dictionary of series consisting of key and value is created, wherein a value is actually a series data structure.
This dictionary is later passed as a parameter to the ‘Dataframe’ function present in the ‘pandas’ library
This dictionary is later passed as a parameter to the ‘Dataframe’ function present in the ‘pandas’ library
The dataframe is printed on the console.
The dataframe is printed on the console.
We are looking at computing the mean of a specific column that contain numeric values in them.
We are looking at computing the mean of a specific column that contain numeric values in them.
The ‘mean’ function is called on the dataframe by specifying the name of the column, using the dot operator.
The ‘mean’ function is called on the dataframe by specifying the name of the column, using the dot operator.
The mean of numeric column is printed on the console.
The mean of numeric column is printed on the console.
How to select distinct value from one MySQL column only?

To select distinct value from one column only, you can use aggregate function MAX() along with GROUP BY. Let us first create a table −
mysql> create table distinctFromOneColumn
   -> (
   -> StudentId int,
   -> StudentName varchar(100)
   -> );
Query OK, 0 rows affected (0.77 sec)
Following is the query to insert records in the table using insert command −
mysql> insert into distinctFromOneColumn values(1001,'John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into distinctFromOneColumn values(1002,'Carol');
Query OK, 1 row affected (0.15 sec)

mysql> insert into distinctFromOneColumn values(1001,'Sam');
Query OK, 1 row affected (0.15 sec)

mysql> insert into distinctFromOneColumn values(1001,'David');
Query OK, 1 row affected (0.16 sec)

mysql> insert into distinctFromOneColumn values(1002,'Ramit');
Query OK, 1 row affected (0.15 sec)

mysql> insert into distinctFromOneColumn values(1003,'Bob');
Query OK, 1 row affected (0.21 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from distinctFromOneColumn;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1001      | John        |
| 1002      | Carol       |
| 1001      | Sam         |
| 1001      | David       |
| 1002      | Ramit       |
| 1003      | Bob         |
+-----------+-------------+
6 rows in set (0.00 sec)
Here is the query to select a distinct value from one column only −
mysql> select StudentId,MAX(StudentName) AS StudentName
   -> from distinctFromOneColumn
   -> group by StudentId;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1001      | Sam         |
| 1002      | Ramit       |
| 1003      | Bob         |
+-----------+-------------+
3 rows in set (0.00 sec)
Make a gradient color mapping on a specified column in Pandas - GeeksforGeeks

05 Apr, 2022
Let us see how to gradient color mapping on specific columns of a Pandas DataFrame. We can do this using the Styler.background_gradient() function of the Styler class.
Syntax : Styler.background_gradient(cmap=’PuBu’, low=0, high=0, axis=0, subset=None)
Parameters :  
cmap : str or colormap (matplotlib colormap)
low, high : float (compress the range by these values.)
axis : int or str (1 or ‘columns’ for columnwise, 0 or ‘index’ for rowwise)
subset : IndexSlice (a valid slice for data to limit the style application to)
Returns :  self
Approach :
Import Pandas module
Create DataFrame
Wisely choose specific column with style.background_gradient() function
Display DataFrame
Let’s understand with examples:
Example 1 :
Create a DataFrame and gradient all the columns.
Python3
# importing pandas moduleimport pandas as pd # Creating pandas DataFramedf = pd.DataFrame({"A": [1, 2, -3, 4, -5, 6],                   "B": [3, -5, -6, 7, 3, -2],                   "C": [-4, 5, 6, -7, 5, 4],                   "D": [34, 5, 32, -3, -56, -54]}) # Displaying the original DataFrameprint("Original Array : ")print(df) # background color mappingprint("\nDataframe - Gradient color:")df.style.background_gradient()
Output :
Example 2 :
Create a DataFrame and gradient the specific columns
Python3
# importing pandas moduleimport pandas as pd # Creating pandas DataFramedf = pd.DataFrame({"A": [1, 2, -3, 4, -5, 6],                   "B": [3, -5, -6, 7, 3, -2],                   "C": [-4, 5, 6, -7, 5, 4],                   "D": [34, 5, 32, -3, -56, -54]}) # Displaying the original DataFrameprint("Original Array : ")print(df) # background color mappingprint("\nDataframe - Gradient color:") # df.style.background_gradient()df.style.background_gradient(subset='B')
Output :
If you want to change another column then
Python3
df.style.background_gradient(subset='D')
Output : 
,
surinderdawra388
simmytarika5
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python