code-rag-bench/online-tutorials huggingface dataset:
Add elements to HashMap in Java

To add elements to HashMap, use the put() method.
First, create a HashMap −
HashMap hm = new HashMap();
Now, let us add some elements to the HashMap −
hm.put("Maths", new Integer(98));
hm.put("Science", new Integer(90));
hm.put("English", new Integer(97));
The following is an example to add elements to HashMap −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Maths", new Integer(98));
      hm.put("Science", new Integer(90));
      hm.put("English", new Integer(97));
      hm.put("Physics", new Integer(91));
      hm.put("Chemistry", new Integer(93));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
   }
}
Maths: 98
English: 97
Chemistry: 93
Science: 90
Physics: 91
Print all possible sums of consecutive numbers with sum N in C++

In this problem, we are given a positive integer N and we have to print the sequence of all possible consecutive numbers with a sum equal to N.
Let’s take an example to understand the problem,
Input: N = 15
Output: 1 2 3 4 5
7 8
A simple solution to this problem is by adding up consecutive sequence combinations till N/2. And then print the sequence that sums up to N.
 Live Demo
#include<iostream>
using namespace std;
void printConsequtiveSum(int N){
   int start = 1, end = (N+1)/2;
   while (start < end){
      int sum = 0;
      for (int i = start; i <= end; i++){
         sum = sum + i;
         if (sum == N){
            for (int j = start; j <= i; j++)
               cout<<j<<" ";
               cout<<endl;
               break;
         }
         if (sum > N)
            break;
      }
      sum = 0;
      start++;
   }
}
int main(){
   int N = 25;
   cout<<"Sequence of consicutive numbers that sum upto "<<N<<" are :\n";
   printConsequtiveSum(N);
   return 0;
}
The sequence of consecutive numbers that sum up to 25 are −
3 4 5 6 7
12 13
This method is easy but is not so efficient.
So, we have a more complex but optimum solution that will be using a precomputed array of sums to keep track of sum. This will decrease the complexity of the sum.
Example
 Live Demo
#include <iostream>
using namespace std;
void printConsequtiveSum(int N){
   int start = 1, end = 1;
   int sum = 1;
   while (start <= N/2){
      if (sum < N){
         end += 1;
         sum += end;
      }
      else if (sum > N){
         sum -= start;
         start += 1;
      }
      else if (sum == N){
         for (int i = start; i <= end; ++i)
            cout<<i<<" ";
            cout<<endl;
            sum -= start;
            start += 1;
      }
   }
}
int main(){
   int N = 25;
   cout<<"Sequence of consicutive numbers that sum upto "<<N<<" are:\n";
   printConsequtiveSum(N);
   return 0;
}
Sequence of consecutive numbers that sum up to 25 are −
3 4 5 6 7
12 13
What is character entities in HTML ? - GeeksforGeeks

20 Aug, 2021
In this article, we will learn about HTML character entities and how to use them. HTML character entities are basically a set of characters (entity) used to represent few characters reserved by the HTML, especially invisible characters or characters difficult to type out using a regular keyboard. HTML provides some entity names and entity numbers to use these symbols. Please refer to HTML Entities for more details about characters.
Example: ‘<‘ is already reserved in HTML language. Sometimes this character needs to display on the web page that creates ambiguity in code. Along with these are the character which is normally not present in basic keyboard ( £, ¥, €, © ), etc. We will explore the HTML entities in detail as we grow in the article. 
Syntax:
&entity_name; or &#entity_number;
Some useful symbols with their entity name and entity numbers are discussed below:
Reserved Characters: Reserved characters are those characters that are either reserved for HTML or those which are not present in the basic keyboard.
Example: As Entity numbers are easy to learn. Here, a few of the reserved characters are discussed:
Other Characters: Some characters that aren’t available directly on our keyboard, therefore such an entity can be used to represent it by using their entity number. 
Example: These keywords are directly not available to type, we need to specify their entity number. Here #x before the numbers represents the hexadecimal representation. 
Example: 
HTML
<!DOCTYPE html><html>  <head>    <title>HTML Character entities</title>  </head>  <body>    <h3>Indian rupee sign = ₹</h3>    <h3>Euro sign = €</h3>    <h3>Dollar sign = $</h3>    <h3>Pound sign = £</h3>  </body></html>
Output: 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Basics
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Program to find covariance in C++

In this tutorial, we will be discussing a program to find covariance.
For this we will be provided with two sets of random variables. Our task is to calculate their covariance i.e, the measure of how much those two values differ together.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
//function to find mean
float mean(float arr[], int n){
   float sum = 0;
   for(int i = 0; i < n; i++)
   sum = sum + arr[i];
   return sum / n;
}
//finding covariance
float covariance(float arr1[], float arr2[], int n){
   float sum = 0;
   for(int i = 0; i < n; i++)
      sum = sum + (arr1[i] - mean(arr1, n)) * (arr2[i] - mean(arr2, n));
   return sum / (n - 1);
}
int main(){
   float arr1[] = {65.21, 64.75, 65.26, 65.76, 65.96};
   int n = sizeof(arr1) / sizeof(arr1[0]);
   float arr2[] = {67.25, 66.39, 66.12, 65.70, 66.64};
   int m = sizeof(arr2) / sizeof(arr2[0]);
   if (m == n)
      cout << covariance(arr1, arr2, m);
   return 0;
}
-0.0580511
SVG - Ellipse

<ellipse>  element is used to draw ellipse with a center point and given two radii.
Following is the syntax declaration of <ellipse> element. We've shown main attributes only.
<ellipse
   cx="x-axis co-ordinate"
   cy="y-axis co-ordinate"
   
   rx="length" 
   ry="length" >    
</ellipse>
<html>
   <title>SVG Ellipse</title>
   <body>
   
      <h1>Sample SVG Ellipse Image</h1>
      <svg width="800" height="800">
         <g>
            <text x="0" y="15" fill="black" >Ellipse #1: Without opacity.</text>
            
            <ellipse cx="100" cy="100" rx="90" ry="50" 
            stroke="black" stroke-width="3" fill="rgb(121,0,121)"></ellipse>
         </g> 
      </svg>
   
   </body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.
<html>
   <title>SVG Ellipse</title>
   <body>
      
      <h1>Sample SVG Ellipse Image</h1>
      
      <svg width="800" height="800">
         <g>
            <text x="0" y="15" fill="black" >Ellipse #2: With opacity </text>
            
            <ellipse cx="100" cy="100" rx="90" ry="50" 
            style="fill:rgb(121,0,121);stroke-width:3;
            stroke:rgb(0,0,0);stroke-opacity:0.5;opacity:0.5"></ellipse> 
         </g>
      </svg>
   
   </body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Converting date type SYDATUM in a format like MM/DD/YY in SAP ABAP

It depends if you want to write it to a list screen or you want to convert it to a text variable. To write it to a list screen, you can use below code −
WRITE I_my_dateMM/DD/YYYY
To convert it to a text variable, you can use below command −
WRITE l_my_dateTO l_my_text MM/DD/YYYY
If you want to set the date in SAPscript form, you can use SET DATE MASK command. You can specify date fields to be printed in specified format −
/: SET DATE MASK= 'date_mask'
In the date mask, you can use the following codes −
DD: day (two digits)
DDD: day name - abbreviated
DDDD: day name - written out in full
MM: month (two digits)
MMM: month name - abbreviated
MMMM: month name - written out in full
YY: year (two digits)
YYYY: year (four digits)
You can also reset date mask to default setting by using an “empty string” as below −
/: SET DATE MASK= ' '
Also note that the full forms of days and months are stored in table - “TTDTG”  which is language dependent and with the below keys-
%%SAPSCRIPT_DDD_dd:abbreviated day name
%%SAPSCRIPT_DDDD_dd:full form of day name
%%SAPSCRIPT_MMM_mm:abbreviated month name
%%SAPSCRIPT_MMMM_mm:full form of month name
dd: day number 01= Monday,..., 07 = Sunday
mm: month number 01 = January,..., 12 = December
To see table fields, navigate to T-code SE11 → Enter Table name TTDTG → Display
To see table fields, navigate to Utilities → Table Content → Display
Increase the distance between the title and the plot in Matplotlib

To increase the distance between the title and the plot in matplotlib, we can take the following steps −
Create point x using numpy.
Create point x using numpy.
Create point y using numpy sin.
Create point y using numpy sin.
Set the title of the plot. After changing the value y (in argument), we can increase or decrease the distance between the title and the plot.
Set the title of the plot. After changing the value y (in argument), we can increase or decrease the distance between the title and the plot.
Plot x and y points using the plot() method, where color is red and line width is 2.
Plot x and y points using the plot() method, where color is red and line width is 2.
Ti display the figure, use the show() method.
Ti display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 1000)
y = np.sin(x)
ttl = plt.title('Sine Curve', y=1.05)
plt.plot(x, y, c="red", lw=2)
plt.show()
Ext.js - Basic Alert Box

This is the simplest alert box just to show some information on some event.
Following is a simple syntax for basic alert box.
Ext.Msg.alert('Title', 'Basic message box in ExtJS');

Following is a simple example showing the usage.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" 
         rel = "stylesheet" />
      
      <script type = "text/javascript" 
         src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
      <script type = "text/javascript">
         Ext.onReady(function() {
            Ext.create('Ext.Button', {
               renderTo: Ext.getElementById('msgBox'),
               text: 'Click Me',
               listeners: {
                  click: function() {
                     Ext.Msg.alert('Title', 'Basic message box in ExtJS');
                  }
               }
            });
         });
      </script>
   </head>
   
   <body>
      <p> Click the button for alert box </p>
      <div id = "msgBox" ></div>
   </body>
</html>
The above program will produce the following result −
 Click the button for alert box 
 Print
 Add Notes
 Bookmark this page
add_cookie driver method - Selenium Python - GeeksforGeeks

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 add_cookie driver method in Selenium. add_cookie method is used to add a cookie to your current session. This cookie can be used by website itself or by you.
Syntax –
add_cookie(cookie_dict)
Example –Now one can use add_cookie method as a driver method as below –
driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’})

To demonstrate, add_cookie 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/")  # add_cookie method driverdriver.add_cookie({"name" : "foo", "value" : "bar"})
Output –Cookie with name foo and value bar is added as verified below –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Fix MySQL Error #1064 - You have an error in your SQL syntax... near 'TYPE=MyISAM?

This error occurs when we use TYPE for ENGINE NAME. The error is as follows −
mysql> create table DemoTable1836
     (
     ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
     ClientName varchar(20)
     )Type=MyISAM AUTO_INCREMENT=1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Type=MyISAM AUTO_INCREMENT=1' at line 5
Now, in MySQL 8, you can use ENGINE instead of Type. Let us first create a table −
mysql> create table DemoTable1836
     (
     ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
     ClientName varchar(20)
     )ENGINE=MyISAM AUTO_INCREMENT=1;
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1836(ClientName) values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1836(ClientName) values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1836(ClientName) values('Mike');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1836(ClientName) values('Sam');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1836;
This will produce the following output −
+----------+------------+
| ClientId | ClientName |
+----------+------------+
|        1 | Chris      |
|        2 | David      |
|        3 | Mike       |
|        4 | Sam        |
+----------+------------+
4 rows in set (0.00 sec)
Where should jQuery code go in header or footer?

It’s always a good practice to add jQuery code in footer i.e. just before the closing </body> tag. If you have not done that, then use the defer attribute.
Use defer attribute so the web browser knows to download your scripts after the HTML downloaded −
<script src="new.js" defer="defer"></script>
The defer attribute is used to specify that the script execution occurs when the page loads. It is useful only for external scripts and is a boolean attribute.
The following code shows how to use the defer attribute −
<!DOCTYPE html>
<html>
   <body>
      <script src="new.js" defer></script>
      <p>The external file added will load later, since we're using defer</p>
   </body>
</html>
TreeSet size() Method in Java - GeeksforGeeks

26 Nov, 2018
The Java.util.TreeSet.size() method is used to get the size of the Tree set or the number of elements present in the Tree set.
Syntax:
Tree_Set.size()

Parameters: The method does not take any parameter.
Return Value: The method returns the size or the number of elements present in the Set.
Below program illustrates the use of Java.util.TreeSet.size() method:
// Java code to illustrate size()import java.util.*;import java.util.TreeSet;  public class TreeSetDemo {    public static void main(String args[])    {        // Creating an empty TreeSet        TreeSet<String> tree = new TreeSet<String>();          // Use add() method to add elements into the Set        tree.add("Welcome");        tree.add("To");        tree.add("Geeks");        tree.add("4");        tree.add("Geeks");        tree.add("TreeSet");          // Displaying the TreeSet        System.out.println("TreeSet: " + tree);          // Displaying the size of the set        System.out.println("The size of the set is: " + tree.size());    }}
TreeSet: [4, Geeks, To, TreeSet, Welcome]
The size of the set is: 5

Java - util package
Java-Collections
Java-Functions
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
PHP pow() Function

The pow () function is used to compute power of a certain number. It returns xy calculation, also termed as x raised to y. PHP also provides "**" asexponentiation operator.
So, pow(x,y) returns xy which is same as x**y
pow ( number $base , number $exp ) : number
PHP pow() function returns base raised to power of exp. If both arguments are non-negative integers,the result is returned as integer, otherwise it is returned as a float.
This function is available in PHP versions 4.x, PHP 5.x as well as PHP 7.x.
 Live Demo
Following example calculates 102 using pow() function
<?php
   echo "pow(10,2) = " . pow(10,2);
   echo " using ** operator " . 10**2;
?>
This will produce following result −
pow(10,2) = 100 using ** operator 100
 Live Demo
Any number raised to 0 results in 1. This is verified by following example −
<?php
   $x=10;
   $y=0;
   echo "pow(" . $x, "," . $y . ")=". pow($x,$y);
?>
This will produce following result −
pow(10,0)=1
 Live Demo
Following example computes square root of 100 using pow() function;
<?php
   $x=100;
   $y=0.5;
   echo "pow(" . $x, "," . $y . ")=". pow($x,$y) . "\n";
   echo "using sqrt() function : ". sqrt(100);
?>
This will produce following result −
pow(100,0.5)=10
using sqrt() function : 10
 Live Demo
This example shows uses pow() function in calculation of area of circle.−
<?php
   $radius=5;
   echo "radius = " . $radius . " area = " . M_PI*pow(5,2);
?>
This will produce following result −
radius = 5 area = 78.539816339745
An Even Easier Guide to Getting Stock Data With Python | by Melvynn Fernandez | Towards Data Science

Follow along, access to code here.
I just came across this article in my email newsletter. So I wanted to do an even easier version of getting stock data with Python. Only my version requires no installation of Python on your computer. It is completely run using Google Colab.
For those unfamiliar with Google Colab, it is a free online cloud-based Jupyter notebook environment. It makes programming very easy without installing anything on your local machine. It is also capable of utilizing GPUs remotely, perfect for individuals who love programming but do not have the resources to do so.
In the article, they mention using a library called yfinance. I will be using pandas_datareader. We do not need to install it in Google Colab because it is already built-in. So instead we just need to do some imports. We start off the code with:
from pandas_datareader import data as web
Since we will be messing with a lot of dates another handy library is datetime. Let’s go ahead and import that as well.
import datetime
To keep things simple I will also be using the same stock symbol as the article, which is SPDR S&P 500 ETF Trust. Translated to SPY in stock ticker symbol form. So we take this and set it to a variable called stock.
stock = 'MSFT'
In this next bit of code, I am grabbing the data that is one year before the date that this code is running.
start_date = (datetime.datetime.now() - datetime.timedelta(days=365)).strftime("%m-%d-%Y")
I now plug the start_date into DataReader. The source I will be getting my data from is Yahoo. Then I will now output into a dataframe.
df = web.DataReader(stock, data_source='yahoo', start=start_date)
We can now import matplotlib, if we want to visualize it and make it look better.
import matplotlib.pyplot as plt
Now plotting is as simple as taking one of the columns. Let’s do that now with the close column from the dataframe.
plt.plot(df['Close'])
And it is as simple as that, no installation and it is ready to go! Feel free to share this article and the code as well! Google Colab makes it easy and fast.
Feel free to check out my other articles as well. I also have technical analysis using Python and how to connect to Robinhood Using Python.
How to get text found between span – Selenium

We can get the text found within the span tag with Selenium webdriver.
The text of a web element can be captured with the method getText. Let us see an example of an element having the text - © Copyright 2021. All Rights Reserved enclosed within the span tag.
WebElement l = driver.findElement(By.xpath("//p/span"));
String s = l.getText();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class SpanText{
   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);
      //maximize window
      driver.manage().window().maximize();
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      // scroll to element with Javascript Executor
      JavascriptExecutor js = (JavascriptExecutor) driver;
      js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
      // identify element with span and get text
      WebElement l = driver.findElement(By.xpath("//p/span"));
      String s = l.getText();
      System.out.println("Text is: " + s);
      driver.quit();
   }
}
File Permissions in C#

For File Permission in C#, use the FileIOPermission Class. It controls the ability to access files and folders.
The following are the properties of File Permissions class −
The following are the methods of File Permission class −
Let us see an example to work wuth FileIOPermission Class in C#. Here, the Demand() method forces a SecurityException at run time if all callers higher in the call stack have not been granted the permission specified by the current instance −
using System;
using System.IO;
using System.Security.Permissions;
using System.Security;

public class Demo {
   public static void Main() {

      FileIOPermission file= new FileIOPermission(PermissionState.None);
      file.AllLocalFiles = FileIOPermissionAccess.Read;
      try {
         Console.WriteLine("Demands the permission to determine whether the application has
         permission to read the files");
         file.Demand();
      }
      catch (SecurityException s) {
         Console.WriteLine(s.Message);
      }
   }
}
How to get the size of a json object in JavaScript?

To get the number of keys in a JSON object in javascript you can use one
of the following 2 methods.
The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.
let a = {
   name: "John",
   age: 32,
   city: "Hong Kong"
}
console.log(Object.keys(a).length)
This will give the output −
3
The for...in statement iterates over all non-Symbol, enumerable
properties of an object. For example,
let a = {
   name: "John",
   age: 32,
   city: "Hong Kong"
}
let count = 0;
for(let key in a) {
   count ++;
}
console.log(count)
This will give the output −
3
C++ IOS Library - Setf

It is used to set specific format flags. The format flags of a stream affect the way data is interpreted in certain input functions and how it is written by certain output functions. See ios_base::fmtflags for the possible values of this function's arguments.
Following is the declaration for ios_base::setf function.
set (1)	fmtflags setf (fmtflags fmtfl);
mask (2) fmtflags setf (fmtflags fmtfl, fmtflags mask);
The first form (1) sets the stream's format flags whose bits are set in fmtfl, leaving unchanged the rest, as if a call to flags(fmtfl|flags()).
The second form (2) sets the stream's format flags whose bits are set in both fmtfl and mask, and clears the format flags whose bits are set in mask but not in fmtfl, as if a call to flags((fmtfl&mask)|(flags()&~mask)).
fmtfl − Format flags to be set. If the second syntax is used, only the bits set in both fmtfl and mask are set in the stream's format flags; the flags set in mask but not in fmtfl are cleared.
mask − Mask containing the flags to be modified.
The format flags selected in the stream before the call.
Basic guarantee − if an exception is thrown, the stream is in a valid state.
Modifies the stream object. Concurrent access to the same stream object may cause data races.
In below example explains about ios_base::setf function.
#include <iostream>     

int main () {
   std::cout.setf ( std::ios::hex, std::ios::basefield );  
   std::cout.setf ( std::ios::showbase );                  
   std::cout << 100 << '\n';
   std::cout.unsetf ( std::ios::showbase );                
   std::cout << 100 << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
 0x64
64

 Print
 Add Notes
 Bookmark this page
How can we take a backup of multiple databases by using mysqldump client program?

By using mysql dump client program we can take the backup of multiple databases into a file having the extension ‘.sql’. It can be understood with the help of the following example −
In this example, with the help of mysql dump client program, we are taking the backup of two databases named ‘tutorials’ and ‘query1’ in a file named ‘tutorials_query1.sql’. The following command will do this −
C:\mysql\bin>mysqldump -u root --databases tutorials query1 > tutorials_query1.sql
The above command will create a file named tutorials_query1.sql which have the dump information of both the databases named tutorials and query1.
How to save the plot to a numpy array in RGB format?

To save the plot to a numpy array in RGB format, we can take the following steps −
Create r, g and b random array using numpy.
Create r, g and b random array using numpy.
Zip r, g and b (grom step 1) to make an rgb tuple list.
Zip r, g and b (grom step 1) to make an rgb tuple list.
Convert rgb into a numpy array to plot it.
Convert rgb into a numpy array to plot it.
Plot the numpy array that is in rgb format.
Plot the numpy array that is in rgb format.
Save the figure at the current location.
Save the figure at the current location.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
r = np.random.rand(100)
g = np.random.rand(100)
b = np.random.rand(100)
rgb = zip(r, g, b)
arr = np.array([item for item in rgb])
plt.plot(arr)
plt.savefig("myplot.png")
plt.show()
Count numbers with difference between number and its digit sum greater than specific value in C++

We are provided two numbers N which defines a range [1,N] and D which is a difference.The goal is to find all the numbers in the range [1,N] such that the [ number - (sum of its digits) ] > D. We will do this by traversing numbers from 1 to N and for each number we will calculate its digit sum using a while loop. Check if the number and calculated digit sum has a difference more than D.
Let’s understand with examples.
Input 
N=15 D=5
Output 
Numbers such that difference b/w no. and its digit sum greater than value D: 6
Explanation 
Numbers 10, 11, 12, 13, 14, 15 satisfy the condition. ( 10-1, 11-2, 12-3, 13-4, 14-5, 15-6 ) all differences are 9 which is greater than 5.
Input 
N=20 D=10
Output 
Only 20 satisfies the condition. 20-2=18 > 10.
Explanation 
This is list of numbers divisible by all non-zero digits : 100 101 102 104 105 110 111 112 115 120 122 124 126 128 132 135 140 144 150 155 162 168 175 184 200
We take integers N and D.
We take integers N and D.
Function digitSum(int n, int d) takes variables N, D and returns the count of numbers with (num-digitsum) >d.
Function digitSum(int n, int d) takes variables N, D and returns the count of numbers with (num-digitsum) >d.
Take the initial variable count as 0 for such numbers.
Take the initial variable count as 0 for such numbers.
Take variable digsum as 0
Take variable digsum as 0
Traverse range of numbers using for loop. i=1 to i=n
Traverse range of numbers using for loop. i=1 to i=n
Now for each number num=i, using while loop check if number is >0.
Now for each number num=i, using while loop check if number is >0.
calculate digsum+=num%10. Reduce num=num/10 to add the next digit.
calculate digsum+=num%10. Reduce num=num/10 to add the next digit.
At the end of the while, check if ( i - digsum > d ). If true increment count.
At the end of the while, check if ( i - digsum > d ). If true increment count.
At the end of all loops count will have a total number which satisfies the condition.
At the end of all loops count will have a total number which satisfies the condition.
Return the count as result.
Return the count as result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int digitSum(int n, int d){
   int count = 0;
   int digsum = 0;
   for (int i = 1; i <= n; i++){
      int num=i;
      digsum=0;
      while(num>0){
         digsum+=num%10; //sum of digits
         num=num/10;
      }
      if(i-digsum>d) //original number is i {
         count++;
         //cout<<i<<" ";
      }
   }
   return count;
}
int main(){
   int N = 20;
   int D = 8;
   cout <<"Numbers such that difference between number and its digit sum greater than specific value: "<<digitSum(N,D);
   return 0;
}
If we run the above code it will generate the following output −
Numbers such that difference between number and its digit sum greater than specific value: 11
MONTH() Function in SQL Server - GeeksforGeeks

11 Jan, 2021
MONTH() function :This function in SQL Server is used to return the month of the year i.e, from 1 to 12 for a date stated.
Features :
This function is used to find the month of the year for a date specified.
This function comes under Date Functions.
This function accepts only one parameter i.e, date.
This function can also include time with the stated date.
Syntax :
MONTH(date)
Parameter :This method accepts only one parameter as given below :
date : Specified date from which the month of the year is to be returned.
Returns :It returns the month of the year i.e, from 1 to 12 for a date specified.
Example-1 :Using MONTH() function and getting the month of the year from the date specified.
SELECT MONTH('2020/01/02');
Output :
1
Example-2 :Using MONTH() function with a variable and getting the month of the year from the date specified.
DECLARE @date VARCHAR(50);
SET @date = '2020/07/05';
SELECT MONTH(@date);
Output :
7
Example-3 :Using MONTH() function with date as parameter which includes time as well.
SELECT MONTH('2018/11/22 07:44');
Output :
11
Example-4 :Using MONTH() function with a variable and a date as parameter which includes time as well.
DECLARE @date VARCHAR(50);
SET @date = '2020/09/30 23:59';
SELECT MONTH(@date);

Output :
9
Application :This function is used to find the month of the year from the date specified.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
Program to find Nth term of series 0, 11, 28, 51, 79, 115, 156, 203, .... - GeeksforGeeks

10 Mar, 2021
Given a number N. The task is to write a program to find the Nth term of the below series: 
0, 11, 28, 51, 79, 115, 156, 203.....(N Terms)
Examples:  
Input: N = 4
Output: 51
For N = 4
4th Term = ( 3 * 4 * 4 + 2 * 4 - 5) 
         = 51

Input: N = 10
Output: 314
 
Approach: The generalized Nth term of this series:  
 
Below is the required implementation:  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the N-th term of the series:// 0, 11, 28, 51, 79, 115, 156, 203.....#include <iostream>#include <math.h>using namespace std; // calculate Nth term of seriesint nthTerm(int n){    return 3 * pow(n, 2) + 2 * n - 5;} // Driver codeint main(){    int N = 4;     cout << nthTerm(N) << endl;     return 0;}
// Java program to find the// N-th term of the series:// 0, 11, 28, 51, 79, 115, 156, 203.....import java.io.*; class GFG{ // calculate Nth term of seriesstatic int nthTerm(int n){    return 3 * (int) Math.pow(n, 2) +                           2 * n - 5;} // Driver codepublic static void main (String[] args){    int N = 4;     System.out.println(nthTerm(N));}} // This code is contributed// by anuj_67
# Python3 program to find the# N-th term of the series:# 0, 11, 28, 51, 79, 115, 156, 203..... # calculate Nth term of seriesdef nthTerm(n):     return 3 * pow(n, 2) + 2 * n - 5 # Driver codeN = 4print(nthTerm(N)) # This code is contributed by# Sanjit_Prasad
// C# program to find the// N-th term of the series:// 0, 11, 28, 51, 79, 115, 156, 203.....using System; class GFG{ // calculate Nth term of seriesstatic int nthTerm(int n){    return 3 * (int) Math.Pow(n, 2) +                         2 * n - 5;} // Driver codepublic static void Main (){    int N = 4;     Console.WriteLine(nthTerm(N));}} // This code is contributed// by inder_verma
<?php// PHP program to find the// N-th term of the series:// 0, 11, 28, 51, 79, 115, 156, 203..... // calculate Nth term of seriesfunction nthTerm($n){    return 3 * pow($n, 2) + 2 * $n - 5;} // Driver code$N = 4; echo nthTerm($N) . "\n"; // This code is contributed// by Akanksha Rai(Abby_akku)
<script>// JavaScript program to find the N-th term of the series:// 0, 11, 28, 51, 79, 115, 156, 203..... // calculate Nth term of seriesfunction nthTerm( n){    return 3 * Math.pow(n, 2) + 2 * n - 5;} // Driver codelet N = 4;     document.write( nthTerm(N)); // This code contributed by gauravrajput1 </script>
51
 
Time Complexity: O(1) 
Sanjit_Prasad
Akanksha_Rai
vt_m
inderDuMCA
GauravRajput1
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
Python | Pandas Series.valid() - GeeksforGeeks

29 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.valid() function return the same Series object but without the null values.
Syntax: Series.valid(inplace=False, **kwargs)
Parameter :inplace: boolean
Returns : Series
Example #1: Use Series.valid() function to remove the null values from the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', None, 'Toronto', 'Lisbon', 'Rio', 'Chicago', 'Lisbon'])  # Print the seriesprint(sr)
Output :
Now we will use Series.valid() function to remove the null values from the given series object.
# return valid valuessr.valid()
Output :
As we can see in the output, the Series.valid() function has returned a Series object containing all the valid value of the original series object on which it was called.
Example #2: Use Series.valid() function to remove the null values from the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, 214, 325, 88, None, 325, None, 325, 100])  # Print the seriesprint(sr)
Output :
Now we will use Series.valid() function to remove the null values from the given series object.
# return valid valuessr.valid()
Output :As we can see in the output, the Series.valid() function has returned a Series object containing all the valid value of the original series object on which it was called.
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
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
Comparing two dates in PHP

To compare two dates in PHP, the code is as follows. Here, we have used the equality operator to compare dates −
 Live Demo
<?php
   $dateOne = "2019-10-30";
   $dateTwo = "2019-10-30";
   echo "Date1 = $dateOne";
   echo "\nDate2 = $dateTwo";
   if ($dateOne == $dateTwo)
      echo "\nBoth the dates are equal!";
   else
      echo "Both the dates are different!";
?>
This will produce the following output−
Date1 = 2019-10-30
Date2 = 2019-10-30
Both the dates are equal!
Let us now see another example−
 Live Demo
<?php
   $dateOne = "2019-11-08";
   $dateTwo = "2018-08-10";
   echo "Date1 = $dateOne";
   echo "\nDate2 = $dateTwo";
   if ($dateOne < $dateTwo)
      echo "\nDateTwo is the latest date!";
   else
      echo "\nDateOne is the latest date!";
?>
This will produce the following output−
Date1 = 2019-11-08
Date2 = 2018-08-10
DateOne is the latest date!
Python 3 - os.close() Method

The method close() closes the associated with file descriptor fd.
Following is the syntax for close() method −
os.close(fd)

fd − This is the file descriptor of the file.
This method does not return any value.
Note − This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe().
The following example shows the usage of close() method.
#!/usr/bin/python3
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
line = "this is test" 

# string needs to be converted byte object
b = str.encode(line)
os.write(fd, b)

# Close opened file
os.close( fd )

print ("Closed the file successfully!!")
When we run the above program, it produces the following result −
Closed the file successfully!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Count how many times the substring appears in the larger String in Java

Let’s say we have the following string.
String str = "Learning never ends! Learning never stops!";
In the above string, we need to find out how many times the substring “Learning” appears.
For this, loop until the index is not equal to 1 and calculate.
while ((index = str.indexOf(subString, index)) != -1) {
subStrCount++;
index = index + subString.length();
}
The following is an example.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String str = "Learning never ends! Learning never stops!";
      System.out.println("String: "+str);
      int subStrCount = 0;
      String subString = "Learning";
      int index = 0;
      while ((index = str.indexOf(subString, index)) != -1) {
         subStrCount++;
         index = index + subString.length();
      }
      System.out.println("Substring "+subString+" found "+subStrCount+" times!");
   }
}
String: Learning never ends! Learning never stops!
Substring Learning found 2 times!
Matplotlib.pyplot.get_figlabels() in Python - GeeksforGeeks

10 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The get_figlabels() method in pyplot module of matplotlib library is used to get the list of existing figure labels.
Syntax: matplotlib.pyplot.get_figlabels()
Parameters: This method does not accept any parameters.
Returns: This method returns the list of existing figure labels.
Below examples illustrate the matplotlib.pyplot.get_figlabels() function in matplotlib.pyplot:
Example 1:
import matplotlib.pyplot as pltimport numpy as np       t = np.arange(0.01, 5.0, 0.01)s = np.exp(-t)     plt.plot(t, s)plt.ylim(1, 0)plt.ylabel('Display Y-axis Label', fontweight ='bold')plt.grid(True)  w = plt.get_figlabels()  plt.text(1.5, 0.58,         "List of existing figure labels : \n"         + str(w),         fontsize = 12)     plt.title('matplotlib.pyplot.get_figlabels() function\ Example', fontweight ="bold")   plt.show()
Output:
Example 2:
import matplotlib.pyplot as pltimport matplotlib as mplimport matplotlib.patches as patchesimport numpy as np         mpl.rcParams['figure.dpi'] = 80mpl.rcParams['savefig.dpi'] = 80   def redraw(event):          if  np.size(plt.get_figlabels()):        ax.clear()        drawRectangles(ax)        fig.canvas.draw()    else:        pass      def drawRectangles(ax):          td2dis = ax.transData    coords = td2dis.transform([0.2, 0.5])    tr = mpl.transforms.Affine2D().rotate_deg_around(coords[0],                                                     coords[1], 10)    t = td2dis + tr    rec0 = patches.Rectangle((0.5, 0.5),                             0.25, 0.2,                              color = 'green',                              alpha = 0.4)    ax.add_patch(rec0)    rect1 = patches.Rectangle((0.5, 0.5),                              0.25, 0.2,                              color = 'green',                              alpha = 0.7,                              transform = t)    ax.add_patch(rect1);    plt.title('matplotlib.pyplot.get_figlabels() function Example', fontweight ="bold")    plt.grid()      figSize = (8, 6)fig = plt.figure("Patch rotate", figsize = figSize)   ax = fig.add_subplot(111)ax.set_xlim(0, 1);ax.set_ylim(0, 1);  fig.canvas.mpl_connect('resize_event', redraw)drawRectangles(ax)   plt.show()
Output:
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters
Python Program to Generate Gray Codes using Recursion

When it is required to generate gray codes with the help of recursion, a method is defined, that creates an empty list and appends values 0 and 1 to it. Multiple ‘for’ loops are used to generate the gray code within the function.
Below is the demonstration of the same −
 Live Demo
import math as mt
def generate_gray_list(my_val):
   if (my_val <= 0):
      return
   my_list = list()
   my_list.append("0")
   my_list.append("1")
   i = 2
   j = 0
   while(True):
      if i >= 1 << my_val:
         break
      for j in range(i - 1, -1, -1):
         my_list.append(my_list[j])
      for j in range(i):
         my_list[j] = "0" + my_list[j]
      for j in range(i, 2 * i):
         my_list[j] = "1" + my_list[j]
      i = i << 1
   for i in range(len(my_list)):
      print(my_list[i])
my_num = 3
print("The number is :")
print(my_num)
print("Method to convert gray code to binary is being called...")
generate_gray_list(my_num)
The number is :
3
Method to convert gray code to binary is being called...
000
001
011
010
110
111
101
100
The required packages are imported.
The required packages are imported.
A method is defined, that creates an empty list.
A method is defined, that creates an empty list.
It appends 0 and 1 to the list.
It appends 0 and 1 to the list.
Multiple ‘for’ loops are used to iterate within the range of 0 and 2.
Multiple ‘for’ loops are used to iterate within the range of 0 and 2.
The left shift operator is used on the iterator and compared with the number.
The left shift operator is used on the iterator and compared with the number.
Outside the method, it is called by passing relevant parameter.
Outside the method, it is called by passing relevant parameter.
The output is displayed on the console.
The output is displayed on the console.