code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas Series/Dataframe.any()

16 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas any() method is applicable both on Series and Dataframe. It checks whether any value in the caller object (Dataframe or series) is not 0 and returns True for that. If all values are 0, it will return False.
Syntax: DataFrame.any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)
Parameters:axis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columns.bool_only: Checks for bool only series in Data frame, if none found, it will use only boolean values. This parameter is not for series since there is only one column.skipna: Boolean value, If False, returns True for whole NaN column/rowlevel: int or str, specifies level in case of multilevel
Return type: Boolean series
Example #1: Index wise implementation
In this example, a sample data frame is created by passing dictionary to Pandas DataFrame() method. Null values are also passed to some indexes using Numpy np.nan to check behaviour with null values. Since in this example, the method is implemented on index, the axis parameter is kept 0 (that stands for rows).
# importing pandas module import pandas as pd   # importing numpy moduleimport numpy as np  # creating dictionarydic = {'A': [1, 2, 3, 4, 0, np.nan, 3],       'B': [3, 1, 4, 5, 0, np.nan, 5],       'C': [0, 0, 0, 0, 0, 0, 0]}  # making dataframe using dictionarydata = pd.DataFrame(dic)  # calling data.any column wiseresult = data.any(axis = 0)  # displaying resultresult
Output:As shown in output, since last column is having all values equal to zero, Hence False was returned only for that column.
 Example #2: Column wise Implementation
In this example, a sample data frame is created by passing dictionary to Pandas DataFrame() method just like in above example. But instead of passing 0 to axis parameter, 1 is passed to implement for each value in every column.
# importing pandas module import pandas as pd   # importing numpy moduleimport numpy as np  # creating dictionarydic = {'A': [1, 2, 3, 4, 0, np.nan, 3],       'B': [3, 1, 4, 5, 0, np.nan, 5],       'C': [0, 0, 0, 0, 0, 0, 0]}  # making dataframe using dictionarydata = pd.DataFrame(dic)  # calling data.any column wiseresult = data.any(axis = 1)  # displaying resultresult
Output:As shown in the output, False was returned for only rows where all values were 0 or NaN and 0.
Python pandas-dataFrame-methods
Python pandas-general-functions
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Tweepy – Getting the screen name of a user

03 Jul, 2020
In this article we will see how we can get the screen name of a user. Screen name is the username of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their screen name, often in a shortened version. All the screen names must be unique.
Identifying the screen name in the GUI :
In the above mentioned profile, geeksforgeeks is the screen name of the profile.
In order to get the screen name we have to do the following :
Identify the user ID of the profile.Get the User object of the profile using the get_user() method and the user ID.From this object, fetch the screen_name attribute present in it.
Identify the user ID of the profile.
Get the User object of the profile using the get_user() method and the user ID.
From this object, fetch the screen_name attribute present in it.
Example 1: Consider the following profile :The user ID of the above mentioned profile is 57741058.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the userid = 57741058  # fetching the useruser = api.get_user(id)  # fetching the screen namescreen_name = user.screen_name  print("The screen name of the user is : " + screen_name)
Output :
The screen name of the user is : geeksforgeeks

Example 2: Consider the following profile :The user ID of the above mentioned profile is 4802800777.
# the ID of the userid = 4802800777  # fetching the useruser = api.get_user(id)  # fetching the screen namescreen_name = user.screen_name  print("The screen name of the user is : " + screen_name)
Output :
The screen name of the user is : PracticeGfG

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL | CONVERT( ) Function - GeeksforGeeks

19 Nov, 2019
The MySQL CONVERT() function is used for converting a value from one datatype to a different datatype. The MySQL CONVERT() function is also used for converting a value from one character set to another character set. It accepts two parameters which are the input value and the type to be converted in.
The CONVERT() function returns the value in the specified datatype or character set.
Syntax for converting datatypes:
CONVERT( input_value, data_type )
Syntax for converting character sets:
CONVERT( input_value USING character_set )
Parameters Used:
input_value – It is used to specify the input value.data_type – It is used to specify the desired datatype to be converted in.character_set – It is used to specify the desired character set to be converted in.
Return Value:The CONVERT() function returns the value in the specified datatype or character set.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
MySQL 4.0
MySQL 3.23
Example-1: Implementing CONVERT() function to convert a value to a CHAR datatype.
SELECT CONVERT(198, CHAR); 
Output:
198 
Example-2: Implementing CONVERT() function to convert a value to datetime datatype.
SELECT CONVERT('2019-11-19', DATETIME); 
Output:
2019-11-19 00:00:00 
Example-3: Implementing CONVERT() function to convert a value to UNSIGNED type.
SELECT CONVERT(2-5, UNSIGNED); 
Output:
18446744073709551613 
Example-4: Implementing CONVERT() function to convert a string value to utf8 character set.
SELECT CONVERT('geeksforgeeks' USING utf8); 
Output:
geeksforgeeks 
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Combine Vectors, Matrix or Data Frames by Rows in R Language - rbind() Function - GeeksforGeeks

04 Jun, 2020
rbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by rows.
Syntax: rbind(x1, x2, ..., deparse.level = 1)
Parameters:x1, x2: vector, matrix, data framesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1.
Example 1:
# R program to illustrate# rbind function  # Initializing two vectorsx <- 2:7y <- c(2, 5)  # Calling rbind() functionrbind(x, y)
Output:
  [, 1] [, 2] [, 3] [, 4] [, 5] [, 6]
x    2    3    4    5    6    7
y    2    5    2    5    2    5

Example 2:
# R program to illustrate# rbind function  # Initializing a vectorx <- 1:5  # Calling rbind() functionrbind(x, 4)rbind(x, 5, deparse.level = 0)rbind(x, 6, deparse.level = 2)rbind(x, 4, deparse.level = 6)
Output:
  [, 1] [, 2] [, 3] [, 4] [, 5]
x    1    2    3    4    5
     4    4    4    4    4

     [, 1] [, 2] [, 3] [, 4] [, 5]
[1, ]    1    2    3    4    5
[2, ]    5    5    5    5    5

  [, 1] [, 2] [, 3] [, 4] [, 5]
x    1    2    3    4    5
6    6    6    6    6    6

     [, 1] [, 2] [, 3] [, 4] [, 5]
[1, ]    1    2    3    4    5
[2, ]    4    4    4    4    4

R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
java.time.LocalDateTime.of() Method Example

The java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) method obtains an instance of LocalDateTime from year, month, day, hour, minute, second and nanosecond.
Following is the declaration for java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) method.
public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)

year − the year to represent, from MIN_YEAR to MAX_YEAR
year − the year to represent, from MIN_YEAR to MAX_YEAR
month − the month-of-year to represent
month − the month-of-year to represent
dayOfMonth − the day-of-month to represent, from 1 to 31
dayOfMonth − the day-of-month to represent, from 1 to 31
hour − the hour-of-day to represent, from 0 to 23
hour − the hour-of-day to represent, from 0 to 23
minute − the minute-of-hour to represent, from 0 to 59
minute − the minute-of-hour to represent, from 0 to 59
second − the second-of-minute to represent, from 0 to 59
second − the second-of-minute to represent, from 0 to 59
nanoOfSecond − the nano-of-second to represent, from 0 to 999,999,999
nanoOfSecond − the nano-of-second to represent, from 0 to 999,999,999
the local date-time, not null.
DateTimeException − if the value of any field is out of range, or if the day-of-month is invalid for the month-year.
The following example shows the usage of java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second) method.
package com.tutorialspoint;

import java.time.LocalDateTime;
import java.time.Month;

public class LocalDateTimeDemo {
   public static void main(String[] args) {
 
      LocalDateTime date = LocalDateTime.of(2017,Month.FEBRUARY,3,6,30,40,50000);
      System.out.println(date);  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-02-03T06:30:40.000050

 Print
 Add Notes
 Bookmark this page
Determine if a String is a legal Java Identifier

To determine if a String is a legal Java Identifier, use the Character.isJavaIdentifierPart() and Character.isJavaIdentifierStart() methods.
The java.lang.Character.isJavaIdentifierPart() determines if the character (Unicode code point) may be part of a Java identifier as other than the first character.
A character may be part of a Java identifier if any of the following are true.
it is a letter
it is a currency symbol (such as '$')
it is a connecting punctuation character (such as '_')
it is a digit
it is a numeric letter (such as a Roman numeral character)
The java.lang.Character.isJavaIdentifierStart() determines if the character (Unicode code point) is permissible as the first character in a Java identifier.
A character may start a Java identifier if and only if one of the following conditions is true.
isLetter(ch) returns true
getType(ch) returns LETTER_NUMBER
the referenced character is a currency symbol (such as '$')
the referenced character is a connecting punctuation character (such as '_').
The following is an example that checks for individual characters in a string as well as an entire string. It checks whether the string can be a legal Java Identifier or not.
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String []args) {
      char ch1, ch2;
      ch1 = 's';
      ch2 = '_';
      String str = "jkv_yu";
      System.out.println("Checking characters for valid identifier status...");
      boolean bool1, bool2;
      bool1 = Character.isJavaIdentifierPart(ch1);
      bool2 = Character.isJavaIdentifierStart(ch2);
      String str1 = ch1 + " may be a part of Java identifier = " + bool2;
      String str2 = ch2 + " may start a Java identifier = " + bool2;
      System.out.println(str1);
      System.out.println(str2);
      System.out.println("\nChecking an entire string for valid identifier status...");
      System.out.println("The string to be checked: "+str);
      if (str.length() == 0 || !Character.isJavaIdentifierStart(str.charAt(0))) {
         System.out.println("Not a valid Java Identifier");
      }
      for (int i = 1; i < str.length(); i++) {
         if (!Character.isJavaIdentifierPart(str.charAt(i))) {
            System.out.println("Not a valid Java Identifier");
         }
      }
      System.out.println("Valid Java Identifier");
   }
}
Checking characters for valid identifier status...
s may be a part of Java identifier = true
_ may start a Java identifier = true

Checking an entire string for valid identifier status...
The string to be checked: jkv_yu
Valid Java Identifier
Interesting Queries | Practice | GeeksforGeeks

Given an array nums of n elements and q queries . Each query consists of two integers l and r . You task is to find the number of elements of nums[] in range [l,r] which occur atleast k times.
 
Example 1:
Input: nums = {1,1,2,1,3}, Queries = {{1,5},
{2,4}}, k = 1
Output: {3,2}
Explanation: For the 1st query, from l=1 to r=5
1, 2 and 3 have the frequency atleast 1.
For the second query, from l=2 to r=4, 1 and 2 have 
the frequency atleast 1.

 
Your Task:
Your task is to complete the function solveQueries() which takes nums, Queries and k as input parameter and returns a list containg the answer for each query.
 
Expected Time Complexity: O(n*sqrt(n)*log(n))
Expected Space Compelxity: O(n)
 
Constraints:
1 <= n, no of Queries, k <= 104
1 <= nums[i] <= 103
1 <= Queries[i][0] <= Queries[i][1] <= n
0
Sachin Poonia9 months ago
Sachin Poonia
Solution in java should also be given
0
Saarth Vikram Jhaveri11 months ago
Saarth Vikram Jhaveri
i don't know whats going wrong here, my code works completely fine in my c++ compiler , whereas here it gives different answer, please fix it asap! https://p.ip.fi/MzyO
0
aditya anand1 year ago
aditya anand
Please correct python driver code, when submitting my code gives wrong ans(only problem is spaces) but gives correct ans in custom test.
0
Shreyansh Shukla1 year ago
Shreyansh Shukla
even i saw the solution none of them contained the given structure at the starting of problem!!!every one is typing a fresh code??
then why such WRONG modification for us!!such that it gives different answer!!!!
0
Shreyansh Shukla1 year ago
Shreyansh Shukla
please correct the test case of this question 2 5 310 42 22 22 22 21 1
it shows different output for expected one and different output for submit button !!!!!What the heck is this!!so irresponsible!!!@@vikranttandon:disqus
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.
What is tilde (~) operator in Python?

The bitwise operator ~ (pronounced as tilde) is a complement operator. It takes one bit operand and returns its complement. If the operand is 1, it returns 0, and if it is 0, it returns 1
For example if a=60 (0011 1100 in binary) its complement is -61 (-0011 1101) stored in 2's complement
>>> a=60
>>> bin(a)
'0b111100'
>>> b=~a
>>> a
60
>>>
>>> b
-61
>>> bin(b)
'-0b111101
Matplotlib.pyplot.hlines() in Python - GeeksforGeeks

19 Apr, 2020
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.
The Matplotlib.pyplot.hlines() is used to draw horizontal lines in a graph at each y from xmin to xmax.
Syntax: matplotlib.pyplot.hlines(y, xmin, xmax, colors=’k’, linestyles=’solid’, label=”, *, data=None, **kwargs
Parameters:The Matplotlib.pyplot.hlines() accepts the below-described parameters:
y : It is a required parameter for this method. This parameter describes that in the graph the line is to be drawn. Its value is a scalar or sequence of scalars, in other words, it is the y-indexes where the line is to be plotted.
xmin: It is a required parameter that has either a scalar value or a 1D array-like value that sets the beginning of each line. If scalars are provided all the lines will have the same length.
colors: As the name suggests it is used to set the color of the line to be plotted. This parameter is optional in nature and its default value is ‘k’
linestyles: It is also an optional parameter that accepts four values namely ‘solid’, ‘dashed’, ‘dashdot’ and ‘dotted’. It is responsible for setting the style of the line to be plotted.
label: It is an optional parameter used to describe information about the plotted line in the same line. This accepts a string whose default value is an empty string.
**kwargs: This parameter is used to make use of LineCollection properties in the plotted line.
Note: In addition to the above-mentioned parameters, this method can take a data keyword argument. It is also important to note that the object passed as data must support item access and membership test.
from matplotlib import pyplot as plt  plt.hlines(y = 1, xmin = 1, xmax = 4)  plt.hlines(y = 1.6, xmin = 1.5, xmax = 4.5)  plt.hlines(y = 2, xmin = 2, xmax = 5)
Output :
Example 2:
from matplotlib import pyplot as plt  plt.hlines(y = 1, xmin = 1, xmax = 4, label ="black line")  plt.hlines(y = 1.6, xmin = 1.5, xmax = 4.5, color ='r')plt.text(1, 1.6, 'Red line', ha ='left', va ='center')  plt.hlines(y = 2, xmin = 2, xmax = 5)
Output :
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Area of a n-sided regular polygon with given side length in C++

In this problem for finding the area of an n-sided regular polygon with a given side, we will derive the formula for the area of the figure and create a program based on it. But before that let's revise the basics to understand the topic easily.
An N-sided regular polygon is a polygon of n side in which all sides are equal. For example regular pentagon, regular hexagon, etc.
The area is the quantitative representation of the extent of any two-dimensional figure.
To find the area of this figure we need to find the area of individual triangles in the figure and multiply it by the number of sides it has. Since we are given n sided.
Now, from the above figure, we can create a formula for the area.
Each side of the regular polygon can create one triangle of side a (side of a polygon) and angle 180 / n (n is a number of sides of a polygon). So, the area can be found using the formula,
Area of triangle = 1⁄2 * b * h
Now, h = a * tan(180/n)
So , area = 1⁄2 * a * a / 2 * tan(180/n)
= a * a / (4 * tan(180/n))
Using this formula for an individual triangle of the polygon, we can create the area of the whole polygon,
Area of n-sided regular polygon = n * (a * a / (4 * tan(180 /n)))
Step 1 : calculate the value of angle using (180 / n)
Step 2 : Calculate the area of regular polygon using n * (a * a / (4 * tan(180 /n))) .
Step 3 : Print the area of polygon.
 Live Demo
#include<iostream>
#include<math.h>
using namespace std;
int main(){
   float a = 12, n = 9;
   float area=(a * a * n) / (4 * tan((180 / n) * 3.14159 / 180));
   cout<<"The area of "<<n<<" sided regular polygon of side "<<a<<" is "<<area;
   return 0;
}
The area of 9 sided regular polygon of side 12 is 890.183
C/C++ Program for nth Catalan Number?

Catalan numbers are a sequence of numbers. Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects.
Cn is the number of Dyck words of length 2n. A Dyck word is a string consisting of n X's and n Y's such that no initial segment of the string has more Y's than X's. For example, the following are the Dyck words of length 6
Cn is the number of Dyck words of length 2n. A Dyck word is a string consisting of n X's and n Y's such that no initial segment of the string has more Y's than X's. For example, the following are the Dyck words of length 6
XXXYYY XYXXYY XYXYXY XXYYXY XXYXYY.
Re-interpreting the symbol X as an open parenthesis and Y as a close parenthesis, Cn counts the number of expressions containing n pairs of parentheses which are correctly matched
Re-interpreting the symbol X as an open parenthesis and Y as a close parenthesis, Cn counts the number of expressions containing n pairs of parentheses which are correctly matched
((())) ()(()) ()()() (())() (()())
Cn is the number of different ways n + 1 factors can be completely parenthesized (or the number of ways of associating n applications of a binary operator). For n = 3, for example, we have the following five different parenthesizations of four factors:
Cn is the number of different ways n + 1 factors can be completely parenthesized (or the number of ways of associating n applications of a binary operator). For n = 3, for example, we have the following five different parenthesizations of four factors:
((ab)c)d (a(bc))d (ab)(cd) a((bc)d) a(b(cd))
Successive applications of a binary operator can be represented in terms of a full binary tree. (A rooted binary tree is full if every vertex has either two children or no children.) It follows that Cn is the number of full binary trees with n + 1 leaves:
Successive applications of a binary operator can be represented in terms of a full binary tree. (A rooted binary tree is full if every vertex has either two children or no children.) It follows that Cn is the number of full binary trees with n + 1 leaves:
Input - 6Output - 1 1 2 5 14 42
Explanation
The first Catalan numbers for n = 0, 1, 2, 3,4,5,6,7,8,9,10, ... are1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862,
#include<iostream>
using namespace std;
long int catalan( int n) {
   if (n <= 1){
      return 1;
   }
   long int result = 0;
   for (int i=0; i<n; i++){
      result += catalan(i)*catalan(n-i-1);
   }
   return result;
}
int main(){
   for (int i=0; i<6; i++)
   cout << catalan(i) << " ";
   return 0;
}
1 1 2 5 14 42
How to center a button element vertically and horizontally with CSS?

To center a button vertically and horizontally with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .centered {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
      border: 3px solid rgb(0, 70, 128);
   }
   button{
      font-size: 18px;
      border: none;
      padding:10px;
      background-color: darkblue;
      color:white;
   }
</style>
</head>
<body>
<h1>Centering Example</h1>
<div class="centered">
<button>This button is centered</button>
</div>
</body>
</html>
The above code will produce the following output −
CSS | rotateX() Function

07 Aug, 2019
The rotateX() function is an inbuilt function which is used to rotate an element around the x-axis.
Syntax:
rotateX( angle )
Parameters: This function accepts single parameter angle which represents the angle of rotations. The positive and negative angles rotate the elements in clockwise and counter-clockwise respectively.
Below examples illustrate the rotateX() function in CSS:Example 1:
<!DOCTYPE html> <html> <head>     <title>CSS rotateX() function</title>     <style>         body {            text-align:center;        }        h1 {            color:green;        }        .rotateX_image {            transform: rotateX(60deg);        }    </style> </head>   <body>     <h1>GeeksforGeeks</h1>    <h2>CSS rotateX() function</h2>          <img class="rotateX_image" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"        alt="GeeksforGeeks logo"> </body> </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head>     <title>CSS rotateX() function</title>     <style>         body {            text-align:center;        }        h1 {            color:green;        }        .GFG {            font-size:35px;            font-weight:bold;            color:green;            transform: rotateX(60deg);        }    </style> </head>   <body>     <h1>GeeksforGeeks</h1>    <h2>CSS rotateX() function</h2>          <div class="GFG">Welcome to GeeksforGeeks</div> </body> </html>
Output:
Supported Browsers: The browsers supported by rotateX() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
unordered_map size() in C++ STL

31 Dec, 2018
The unordered_multimap::size() is a built-in function in C++ Standard Template Library which return’s the number of element int the unordered map.
Syntax:
unordered_multimap_name.size()
Return Value: It returns the number of the element present in the unordered map.
Time complexity:
Constant i.e. O(1).
Program 1:
// C++ program to demonstrate// unordered_map size() method  #include <iostream>#include <unordered_map>using namespace std;  int main(){    unordered_map<char, char>        n{ { 'A', 'G' },           { 'B', 'E' },           { 'C', 'E' },           { 'D', 'K' },           { 'E', 'S' } };      cout << "size of map = "         << n.size() << endl;      return 0;}
size of map = 5

Program 2:
// C++ program to demonstrate// unordered_map size() method  #include <iostream>#include <string>#include <unordered_map>using namespace std;  int main(){    unordered_map<string, double> ra;      cout << "Initial size of map = "         << ra.size() << endl;      ra = {        { "Geeks", 1.556 },        { "For", 2.567 },        { "Geeks", 3.345 },        { "GeeksForGeeks", 4.789 },        { "GFG", 5.998 }    };      cout << "size of map = "         << ra.size() << endl;      return 0;}
Initial size of map = 0
size of map = 4

CPP-Functions
cpp-unordered_map
Picked
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Thread.CurrentThread Property in C#

13 May, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as CurrentThread to check the current running thread. Or in other words, the value of this property indicates the current running thread.
Syntax: public static Thread CurrentThread { get; }
Return Value: This property returns a thread that represent the current running thread.
Below programs illustrate the use of CurrentThread property:.Example 1:
// C# program to illustrate the // use of CurrentThread propertyusing System;using System.Threading;  class GFG {      // Main Method    static public void Main()    {        Thread thr;          // Get the reference of main Thread        // Using CurrentThread property        thr = Thread.CurrentThread;        thr.Name = "Main thread";        Console.WriteLine("Name of current running "+                            "thread: {0}", thr.Name);    }}
Output:
Name of current running thread: Main thread
Example 2:
// C# program to illustrate the// use of CurrentThread propertyusing System;using System.Threading;  class GFG {      // Display the id of each thread    // Using CurrentThread and     // ManagedThreadId properties    public static void Myjob()    {        Console.WriteLine("Thread Id: {0}",            Thread.CurrentThread.ManagedThreadId);    }      // Main method    static public void Main()    {          // Creating multiple threads        ThreadStart value = new ThreadStart(Myjob);        for (int q = 1; q <= 7; ++q)         {            Thread mythread = new Thread(value);            mythread.Start();        }    }}
Output:
Thread Id: 3
Thread Id: 8
Thread Id: 9
Thread Id: 6
Thread Id: 5
Thread Id: 7
Thread Id: 4

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.currentthread?view=netframework-4.7.2
Akanksha_Rai
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Number random() Method

Python number method random() returns a random float r, such that 0 is less than or equal to r and r is less than 1.
Following is the syntax for random() method −
random ( )

Note − This function is not accessible directly, so we need to import random module and then we need to call this function using random static object.
NA
NA
This method returns a random float r, such that 0 is less than or equal to r and r is less than 1.
The following example shows the usage of random() method.
#!/usr/bin/python
import random

# First random number
print "random() : ", random.random()

# Second random number
print "random() : ", random.random()
When we run above program, it produces following result −
random() :  0.281954791393
random() :  0.309090465205
JavaScript SyntaxError – Missing = in const declaration

27 Sep, 2021
This JavaScript exception missing = in const declaration occurs if a const is declared and value is not provided(like const ABC_DEF;). Need to provide the value in same statement (const ABC_DEF = ‘#ee0’).
Message:
SyntaxError: Const must be initialized (Edge)
SyntaxError: missing = in const declaration (Firefox)
SyntaxError: Missing initializer in const declaration (Chrome)
Error Type:
SyntaxError
Cause of Error: A constant value cannot be changed by the program while execution. It cannot be altered through re-assignment also.
Example 1: In this example, a const is declared but not initialized so the error has occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>      const GFG;                       document.write(GFG);    </script></body></html>
Output:
SyntaxError: Const must be initialized
Example 2:  In this example, a const is declared and initialized later, so the error has occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>      const INIT_VAL;      // invalid statement      INIT_VAL = 5;                       document.write(INIT_VAL);    </script></body></html>
Output:
SyntaxError: Const must be initialized
abhishek0719kadiyan
JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
unordered_set == operator in C++ STL

29 Jun, 2022
The ‘==’ is an operator in C++ STL performs equality comparison operation between two unordered sets and unordered_set::operator== is the corresponding operator function for the same. Syntax:  
(unordered_set &uset1 == unordered_set &uset2)
Parameters: This operator function takes reference of two unordered sets uset1 and uset2 as parameters which are to be compared.Return Value: This method returns a boolean result value after comparing the two sets. The comparison procedure is as follows:  
Firstly their sizes are compared .
Then each element in ust1 is looked for in ust2
If both the conditions are satisfied true value is returned and at any point if a condition is not satisfied, false value is returned.Below program illustrates unordered_set::operator== in C++.Program: 
CPP
#include <iostream>#include <unordered_set>using namespace std; int main(){    // Initialize three unordered sets    unordered_set<int>        sample1 = { 10, 20, 30, 40, 50 };    unordered_set<int>        sample2 = { 10, 30, 50, 40, 20 };    unordered_set<int>        sample3 = { 10, 20, 30, 50, 60 };     // Compare sample1 and sample2    if (sample1 == sample2) {         cout << "sample1 and "             << "sample2 are equal."             << endl;    }    else {         cout << "sample1 and "             << "sample2 are not equal."             << endl;    }     // Compare sample2 and sample3    if (sample2 == sample3) {         cout << "sample2 and "             << "sample3 are equal."             << endl;    }    else {         cout << "sample2 and "             << "sample3 are not equal."             << endl;    }     return 0;}
sample1 and sample2 are equal.
sample2 and sample3 are not equal.
 
Time complexity: O(N2)
arorakashish0911
utkarshgupta110092
cpp-unordered_set
Picked
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
Object Oriented Programming in C++
Inheritance in C++
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
How to disable arrows from Number input ?

16 Feb, 2021
In this article, we will see how to disable arrows from the Number input.
See the Images below, the first image is having the default arrow and the second is without having the arrow.
Default input box (Having arrows)
Input box without having arrows.
To achieve this, we use the following syntax :
Approach 1:
For chrome, Safari, Edge, Opera :
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
For firefox :
input[type=number]{
    -moz-appearance: textfield;
}
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        input::-webkit-outer-spin-button,        input::-webkit-inner-spin-button {            -webkit-appearance: none;            margin: 0;        }          input[type=number] {            -moz-appearance: textfield;        }    </style></head>  <body>    <h1 style="color: green;">      GeeksforGeeks    </h1>      <h3>        How to disable arrows from        Number input using CSS?    </h3>      <input type="number"            placeholder="Enter number..." /></body>  </html>
Output :
Approach 2: This approach is simple yet powerful. Using inputmode=”numeric” attribute you can find an input box without an arrow. The older browsers might not support this feature for example Internet Explorer and Safari but most of the modern browsers like Chrome, Firefox, Edge, Opera support this attribute. The main purpose of this attribute is to provide a numeric input interface in mobile devices.
<input type="text" inputmode="numeric" />
Example :
HTML
<!DOCTYPE html><html>  <body>    <h1 style="color: green;">GeeksforGeeks</h1>      <h3>        Disable arrows from number input    </h3>    <input type="text" inputmode="numeric"         placeholder="Enter number..."/></body>  </html>
Output :
CSS-Properties
CSS-Questions
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
Stack pop() Method in Java

12 Dec, 2021
The Java.util.Stack.pop() method in Java is used to pop an element from the stack. The element is popped from the top of the stack and is removed from the same.Syntax: 
STACK.pop()
Parameters: The method does not take any parameters.Return Value: This method returns the element present at the top of the stack and then removes it.Exceptions: The method throws EmptyStackException is thrown if the stack is empty.Below programs illustrate the Java.util.Stack.pop() method: Program 1: 
Java
// Java code to illustrate pop()import java.util.*; public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<String> STACK = new Stack<String>();         // Use add() method to add elements        STACK.push("Welcome");        STACK.push("To");        STACK.push("Geeks");        STACK.push("For");        STACK.push("Geeks");         // Displaying the Stack        System.out.println("Initial Stack: " + STACK);         // Removing elements using pop() method        System.out.println("Popped element: " +                                         STACK.pop());        System.out.println("Popped element: " +                                         STACK.pop());         // Displaying the Stack after pop operation        System.out.println("Stack after pop operation "                                             + STACK);    }}
Program 2: 
Java
// Java code to illustrate pop()import java.util.*; public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<Integer> STACK = new Stack<Integer>();         // Use add() method to add elements        STACK.push(10);        STACK.push(15);        STACK.push(30);        STACK.push(20);        STACK.push(5);         // Displaying the Stack        System.out.println("Initial Stack: " + STACK);         // Removing elements using pop() method        System.out.println("Popped element: " +                                         STACK.pop());        System.out.println("Popped element: " +                                         STACK.pop());         // Displaying the Stack after pop operation        System.out.println("Stack after pop operation "                                             + STACK);    }}
Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]
 
sumitgumber28
Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
Plotting a trend graph in Python

21 Apr, 2021
Prerequisites: Matplotlib
A trend Graph is a graph that is used to show the trends data over a period of time. It describes a functional representation of two variables (x , y). In which the x is the time-dependent variable whereas y is the collected data.  The graph can be in shown any form that can be via line chart, Histograms, scatter plot, bar chart, and pie-chart. In python, we can plot these trend graphs by using matplotlib.pyplot library. It is used for plotting a figure for the given data. 
The task is simple and straightforward, for plotting any graph we must suffice the basic data requirement after this determine the values of x over the period of time and data collected for y. Plot the graphs for the above-given data.
Given below are various implementations to depict the same:
Example 1:
Python3
# import all the librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt  # create a dataframeSports = {    "medals": [100, 98, 102, 56, 78, 56, 78, 96],    "Time_Period": [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]}  df = pd.DataFrame(Sports)print(df)  # to plot the graphdf.plot(x="Time_Period", y="medals", kind="line")plt.show()
Output:
   medals  Time_Period
0     100         2010
1      98         2011
2     102         2012
3      56         2013
4      78         2014
5      56         2015
6      78         2016
7      96         2017
                                                                            
Example 2: Using the above data we would plot the scatter and bar graph.
Python3
# import all the librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt  # create a dataframeSports = {    "medals": [100, 98, 102, 56, 78, 56,               78, 96],        "Time_Period": [2010, 2011, 2012, 2013,                    2014, 2015, 2016, 2017]}df = pd.DataFrame(Sports)print(df)    # to plot the graph# subplot (rowno,columno,position) is used# to plot in a single frame.# to plot the scatter graph ,write kind= scatterdf.plot(x="Time_Period", y="medals", kind="scatter")plt.title("scatter chart")plt.subplot(1, 1, 1)    # to Plot the graph in Bar chartdf.plot(x="Time_Period", y="medals", kind="bar")plt.title("bar")plt.subplot(1, 1, 2)  plt.show()
Output:
Example 3: student getting marks in 2010.
Python3
# import the libraryimport matplotlib.pyplot as plt    # Creation of Datax1 = ['math', 'english', 'science', 'Hindi', 'social studies']y1 = [92, 54, 63, 75, 53]y2 = [86, 44, 65, 98, 85]  # Plotting the Dataplt.plot(x1, y1, label='Semester1')plt.plot(x1, y2, label='semester2')  plt.xlabel('subjects')plt.ylabel('marks')plt.title("marks obtained in 2010")  plt.plot(y1, 'o:g', linestyle='--', linewidth='8')plt.plot(y2, 'o:g', linestyle=':', linewidth='8')  plt.legend()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to print checkerboard pattern of nxn using numpy

06 Apr, 2020
Given n, print the checkboard pattern for a n x n matrix
Checkboard Pattern for n = 8:
It consists of n * n squares of alternating 0 for white and 1 for black.
We can do the same using nested for loops and some if conditions, but using Python’s numpy library, we can import a 2-D matrix and get the checkboard pattern using slicing.W2’ll be using following python function to print pattern :
x = np.zeros((n, n), dtype=int)
Using this function, we initialize a 2-D matrix with 0’s at all index using numpy
x[1::2, ::2] = 1 : Slice from 1st index row till 1+2+2... and fill all columns with 1 starting from 0th to 0+2+2... and so on.
x[::2, 1::2] = 1 : Slice from 0th row till 0+2+2... and fill all columns with 1 starting from 1 to 1+2+2+.....
Function of np.zeros((n, n), dtype=int) : Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. Using the dtype parameter initializes all the values with int data-type.For example: np.zeros, np.ones etc.
# Python program to print nXn# checkerboard pattern using numpy  import numpy as np  # function to print Checkerboard patterndef printcheckboard(n):          print("Checkerboard pattern:")      # create a n * n matrix    x = np.zeros((n, n), dtype = int)      # fill with 1 the alternate rows and columns    x[1::2, ::2] = 1    x[::2, 1::2] = 1          # print the pattern    for i in range(n):        for j in range(n):            print(x[i][j], end =" ")         print()     # driver coden = 8printcheckboard(n)
Output:
Checkerboard pattern:
0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 
0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 
0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 
0 1 0 1 0 1 0 1 
1 0 1 0 1 0 1 0 

Improved Source Code Based on Assumption that Checkerboard is always an even nXn i.e., n is even
# Python program to print nXn Assuming that n # is always even as a checkerboard was  import numpy as npdef printcheckboard(n):    final = []    for i in range(n):        final.append(list(np.tile([0,1],int(n/2))) if i%2==0 else list(np.tile([1,0],int(n/2))))    print(np.array(final))    # driver coden = 8printcheckboard(n)
Output:
Checkerboard pattern:
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

bsaik7
Python numpy-program
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to compare String equality in Java?

You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
import java.lang.*
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "Tutorialspoint";
      String str2 = "Tutorialspoint";
      String str3 = "Hi";
     
      // checking for equality
      boolean retval1 = str2.equals(str1);
      boolean retval2 = str2.equals(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}
str2 is equal to str1 = true
str2 is equal to str3 = false
How to count the number of lines in a CSV file in Python?

24 Jan, 2021
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
In this article, we are going to discuss various approaches to count the number of lines in a CSV file using Python.
We are going to use the below dataset to perform all operations:
Python3
# import moduleimport pandas as pd  # read the csv fileresults = pd.read_csv('Data.csv')  # display datasetprint(results)
Output:
To count the number of lines/rows present in a CSV file, we have two different types of methods:
Using len() function.
Using a counter.
Under this method, we need to read the CSV file using pandas library and then use the len() function with the imported CSV file, which will return an int value of a number of lines/rows present in the CSV file.
Python3
# import moduleimport pandas as pd  # read CSV fileresults = pd.read_csv('Data.csv')  # count no. of linesprint("Number of lines present:-",       len(results))
Output:
Under this approach, we will be initializing an integer rowcount to -1 (not 0 as iteration will start from the heading and not the first row)at the beginning and iterate through the whole file and incrementing the rowcount by one. And in the end, we will be printing the rowcount value.
Python3
#Setting initial value of the counter to zerorowcount  = 0#iterating through the whole filefor row in open("Data.csv"):  rowcount+= 1 #printing the resultprint("Number of lines present:-", rowcount)
Output:
Picked
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list