code-rag-bench/online-tutorials huggingface dataset:
Initialize a static map in Java with Examples

27 Oct, 2021
In this article, a static map is created and initialized in Java.
A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.
Method 1:Creating a static map variable.Instantiating it in a static block.Below is the implementation of the above approach:// Java program to create a static map  import java.util.*;  class GFG {      // Declaring the static map    private static Map<Integer, String> map;      // Instantiating the static map    static    {        map = new HashMap<>();        map.put(1, "GFG");        map.put(2, "Geek");        map.put(3, "GeeksForGeeks");    }      // Driver code    public static void main(String[] args)    {        System.out.println(map);    }}Output:{1=GFG, 2=Geek, 3=GeeksForGeeks}

Creating a static map variable.Instantiating it in a static block.
Creating a static map variable.
Instantiating it in a static block.
Below is the implementation of the above approach:
// Java program to create a static map  import java.util.*;  class GFG {      // Declaring the static map    private static Map<Integer, String> map;      // Instantiating the static map    static    {        map = new HashMap<>();        map.put(1, "GFG");        map.put(2, "Geek");        map.put(3, "GeeksForGeeks");    }      // Driver code    public static void main(String[] args)    {        System.out.println(map);    }}
{1=GFG, 2=Geek, 3=GeeksForGeeks}

Method 2: Creating a static map variable and instantiating it together.Below is the implementation of the above approach:// Java program to create a static map  import java.util.*;  class GFG {      // Declaring the static map    private static Map<Integer, String> map        = new HashMap<>() {              map.put(1, "GFG");              map.put(2, "Geek");              map.put(3, "GeeksForGeeks");          }      // Driver code    public static void main(String[] args)    {        System.out.println(map);    }}Output:{1=GFG, 2=Geek, 3=GeeksForGeeks}

Below is the implementation of the above approach:
// Java program to create a static map  import java.util.*;  class GFG {      // Declaring the static map    private static Map<Integer, String> map        = new HashMap<>() {              map.put(1, "GFG");              map.put(2, "Geek");              map.put(3, "GeeksForGeeks");          }      // Driver code    public static void main(String[] args)    {        System.out.println(map);    }}
{1=GFG, 2=Geek, 3=GeeksForGeeks}

chhabradhanvi
java-map
Static Keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.findLast() Method

02 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.findLast() method iterates over the elements in a collection from the right to the left. It is almost the same as _.find() method.
Syntax:
_.findLast( collection, predicate, fromIndex )
Parameters: This method accepts three parameters as mentioned above and described below:
collection: It is the collection that the method iterates over.
predicate: It is the function that is invoked for every iteration.
fromIndex: It is the index of the array from where the search starts.
Return Value: This method returns the element that matches, else undefined.
Example 1:
// Requiring the lodash library const _ = require("lodash");       // Original array var users = ([3, 4, 5, 6]);  // Using the _.findLast() methodlet found_elem = _.findLast(users, function(n) {  return n % 2 == 1;});  // Printing the output console.log(found_elem);
Output:
5
Example 2:
// Requiring the lodash library const _ = require("lodash");       // Original array var user1 = ([3, 4, 5, 6, 9, 1, 7]);var user2 = ([24, 14, 55, 36, 76]);  // Using the _.findLast() methodlet found_elem = _.findLast(user1, function(n) {  return n % 2 == 0;});let found_elem2 = _.findLast(user2, function(n) {  return n % 2 == 1;});  // Printing the output console.log(found_elem);console.log(found_elem2);
Output:
6
55
Example 3:
// Requiring the lodash library const _ = require("lodash");       // Original array var user1 = ([3.5, 4.7, 5.8, 6.9, 9.4, 1.3, 7.2]);  // Using the _.findLast() methodlet found_elem = _.findLast(user1, function(n) {  return n % 2 == 1;});  // Printing the output console.log(found_elem);
Output:
undefined
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SymPy - Substitution

One of the most basic operations to be performed on a mathematical expression is substitution. The subs() function in SymPy replaces all occurrences of first parameter with second.
>>> from sympy.abc import x,a 
>>> expr=sin(x)*sin(x)+cos(x)*cos(x) 
>>> expr

The above code snippet gives an output equivalent to the below expression −
sin2⁡(x)+cos2⁡(x)
>>> expr.subs(x,a)

The above code snippet gives an output equivalent to the below expression −
sin2⁡(a)+cos2⁡(a)
This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.
>>> expr=a*a+2*a+5 
>>> expr

The above code snippet gives an output equivalent to the below expression −
a2+2a+5
expr.subs(a,5)

The above code snippet gives the following output −
40
>>> from sympy.abc import x 
>>> from sympy import sin, pi 
>>> expr=sin(x) 
>>> expr1=expr.subs(x,pi) 
>>> expr1

The above code snippet gives the following output −
0
This function is also used to replace a subexpression with another subexpression. In following example, b is replaced by a+b.
>>> from sympy.abc import a,b 
>>> expr=(a+b)**2 
>>> expr1=expr.subs(b,a+b) 
>>> expr1

The above code snippet gives an output equivalent to the below expression −
(2a+b)2
 Print
 Add Notes
 Bookmark this page
Why scale_fill_manual does not fill the bar with colors created by using ggplot2 in R?

We can manually fill the color of bars in a bar plot which is created by using ggplot2 but for this we would be needing color aesthetics already used for the bars. That means we need to use filling of bars inside aes of ggplot2 and then the colors can be mentioned inside the scale_fill_manual function.
Consider the below data frame:
Live Demo
> x<-c("A","B","C","D")
> count<-c(321,324,320,328)
> df<-data.frame(x,count)
> df
x count
1 A 321
2 B 324
3 C 320
4 D 328
Loading ggplot2 package and creating bar plot:
> library(ggplot2)
> ggplot(df,aes(x,count))+geom_bar(stat="identity")
Creating the bar plot by using scale_fill_manual:
> ggplot(df,aes(x,count))+geom_bar(stat="identity")+scale_fill_manual(values=c("blue","green","grey","yellow"))
This does not change the color of bars.
Creating the bar plot by using scale_fill_manual but passing the fill of bars in aes:
> ggplot(df,aes(x,count,fill=x))+geom_bar(stat="identity")+scale_fill_manual(values=c("blue","green","grey","yellow"))
HTML | DOM onchange Event

28 Jun, 2019
The HTML DOM onchange event occurs when the value of an element has been changed. It also works with radio buttons and checkboxes when the checked state has been changed.
Note: This event is similar to the oninput event but the only difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.
Syntax:
In HTML:
<element onchange="myScript">
In JavaScript:
object.onchange = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("change", myScript);
Example: Using HTML
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onchange Event</h2>          <select id="LangSelect" onchange="GFGfun()">            <option value="c">C</option>            <option value="java">JAVA</option>            <option value="html">HTML</option>            <option value="python">PYTHON</option>        </select>          <p id="demo"></p>          <script>            function GFGfun() {                var x = document.getElementById("LangSelect").value;                document.getElementById(                    "demo").innerHTML = "You selected: " + x;            }        </script>    </center></body>  </html>
Output:Before:After:Example: Using JavaScript
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onchange Event</h2> Email:        <input type="email" id="email">          <script>            document.getElementById(              "email").onchange = function() {                GFGfun()            };              function GFGfun() {                var x = document.getElementById("email");                x.value = x.value.toLowerCase();            }        </script>      </center></body>  </html>
Output:Before:After:
Example: In JavaScript, using the addEventListener() method:
<!DOCTYPE html><html>  <body>    <center>        <h1 style="color:green">          GeeksforGeeks      </h1>        <h2>HTML DOM onchange Event</h2> Email:        <input type="email" id="email">          <script>            document.getElementById(                "email").addEventListener(              "change", GFGfun);              function GFGfun() {                var x = document.getElementById("email");                x.value = x.value.toLowerCase();            }        </script>    </center>  </body>  </html>
Before:After:
Supported Browsers: The browsers supported by DOM onchange Event are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Regex metacharacters in Java Regex

Metacharacters are characters which are having special meanings in Java regular expression.
Following metacharacters are suppored in Java Regular expressions.
( ) [ ] { { \ ^ $ | ? * + .
How to make a textarea and input type read only using jQuery?

To make a textarea and input type read only, use the attr() method .
For readonly, set the input type text and textarea as read only as shown below:
$('input[type="text"], textarea').each(function(){
   $(this).attr('readonly','readonly');
});
The following is the code to set readonly to textarea and input type:
 Live Demo
<html>
<head>
<title>jQuery Example</title>
   <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function() {
         $('input[type="text"], textarea').each(function(){
            $(this).attr('readonly','readonly');
         });
      });

   </script>
</head>
<body>
<form>
<input type="text" value="readonly text field" /><br>
<textarea>readonly textarea</textarea>
</form>
</body>
</html>
C++ Vector Library - rbegin() Function

The C++ function std::vector::rbegin() returns a reverse iterator which points to the last element of the vector.
Reverse iterator iterates reverse order that is why incrementing them moves towards beginning of vector.
Following is the declaration for std::vector::rbegin() function form std::vector header.
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;

reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;

None
Returns a reverse iterator pointing to the reverse beginning of vector.
If object is constant qualified then method returns constant reverse iterator otherwise non-constant reverse iterator.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::rbegin() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};

   /* Iterate vector in reverse order */
   for (auto it =  v.rbegin(); it != v.rend(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
5
4
3
2
1

 Print
 Add Notes
 Bookmark this page
Difference between == and equals() method in Java.

The equals() 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.
 Live Demo
public class Sample {
   public static void main(String []args) {
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1.equals(s2));
      System.out.println(s2.equals(s3));
   }
}
true
false
You can also compare two strings using == operator. But, it compares references of the given variables not values.
public class Sample {
   public static void main(String []args) {
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1 == s2);
      System.out.println(s2 == s3);
   }
}
true
false
Strikethrough text with CSS

Use the text-decoration property to strikethrough text with CSS. You can try to run the following code to underline text:
<html>
   <head>
   </head>
   <body>
      <p style = "text-decoration:line-through;">
         This will be striked through.
      </p>
   </body>
</html>
Composition vs inheritance in React.js

Composition and inheritance are the approaches to use multiple components together in React.js . This helps in code reuse. React recommend using composition instead of inheritance as much as possible and inheritance should be used in very specific cases only.
Example to understand it −
Let’s say we have a component to input username.
class UserNameForm extends React.Component {
   render() {
      return (
         <div>
            <input type="text" />
         </div>
      );
   }
}
ReactDOM.render(
   < UserNameForm />,
   document.getElementById('root'));
This sis simple to just input the name. We will have two more components to create and update the username field.
With the use of inheritance we will do it like −
class UserNameForm extends React.Component {
   render() {
      return (
         <div>
            <input type="text" />
         </div>
      );
   }
}
class CreateUserName extends UserNameForm {
   render() {
      const parent = super.render();
      return (
         <div>
            {parent}
            <button>Create</button>
         </div>
      )
   }
}
class UpdateUserName extends UserNameForm {
   render() {
      const parent = super.render();
      return (
         <div>
            {parent}
            <button>Update</button>
         </div>
      )
   }
}
ReactDOM.render(
   (<div>
      < CreateUserName />
      < UpdateUserName />
   </div>), document.getElementById('root')
);
We extended the UserNameForm component and extracted its method in child component using super.render();
class UserNameForm extends React.Component {
   render() {
      return (
         <div>
            <input type="text" />
         </div>
      );
   }
}
class CreateUserName extends React.Component {
   render() {
      return (
         <div>
            < UserNameForm />
            <button>Create</button>
         </div>
      )
   }
}
class UpdateUserName extends React.Component {
   render() {
      return (
         <div>
            < UserNameForm />
            <button>Update</button>
         </div>
      )
   }
}
ReactDOM.render(
   (<div>
      <CreateUserName />
      <UpdateUserName />
   </div>), document.getElementById('root')
);
Use of composition is simpler than inheritance and easy to maintain the complexity.
Export Pandas dataframe to a CSV file - GeeksforGeeks

01 Sep, 2021
Suppose you are working on a Data Science project and you tackle one of the most important tasks, i.e, Data Cleaning. After data cleaning, you don’t want to lose your cleaned data frame, so you want to save your cleaned data frame as a CSV. Let us see how to export a Pandas DataFrame to a CSV file. Pandas enable us to do so with its inbuilt to_csv() function.First, let’s create a sample data frame  
Python3
# importing the moduleimport pandas as pd # making the datascores = {'Name': ['a', 'b', 'c', 'd'],          'Score': [90, 80, 95, 20]} # creating the DataFramedf = pd.DataFrame(scores) # displaying the DataFrameprint(df)
Output :
Now let us export this DataFrame as a CSV file named your_name.csv : 
Python3
# converting to CSV filedf.to_csv("your_name.csv")
Output
File Successfully saved
In case you get a UnicodeEncodeError, just pass the encoding parameter with ‘utf-8’ value. 
Python3
# converting to CSV filedf.to_csv("your_name.csv", encoding = 'utf-8')
1. Include index numberYou can choose if you want to add automatic index. The default value is True. To set it to False. 
Python3
# converting to CSV filedf.to_csv('your_name.csv', index = False)
Output :  
 
2. Export only selected columns If you want to export only a few selected columns, you may pass it in to_csv() as ‘columns = [“col1”, “col2”]  
 
Python3
# converting to CSV filedf.to_csv("your_name.csv", columns = ['Name'])
Output :  
 
3. Export header You can choose if you want your column names to be exported or not by setting the header parameter to True or False. The default value is True.
Python3
# converting to CSV filedf.to_csv('your_name.csv', header = False) 
Output :  
 
4. Handle NaN In case your data frame has NaN values, you can choose it to replace by some other string. The default value is ”.  
Python3
# converting to CSV filedf.to_csv("your_name.csv", na_rep = 'nothing')
5. Separate with something else If instead of separating the values with a ‘comma’, we can separate it using custom values.  
Python3
# converting to CSV file# separated with tabsdf.to_csv("your_name.csv", sep ='\t')
Output :  
 
saurabh1990aror
clintra
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
JavaScript Count the number of unique elements in an array of objects by an object property?

Suppose, we have the following array of objects that contains data about orders placed in a restaurant −
const orders = [
   {table_id: 3, food_id: 5},
   {table_id: 4, food_id: 2},
   {table_id: 1, food_id: 6},
   {table_id: 3, food_id: 4},
   {table_id: 4, food_id: 6},
];
We are required to write a JavaScript function that takes in one such array. Our function should count the number of unique table_id property in the array (i.e., the number of unique tables for which the orders are booked).
And the number of unique food_id property (i.e., the number of unique food dishes ordered.)
const orders = [
   {table_id: 3, food_id: 5},
   {table_id: 4, food_id: 2},
   {table_id: 1, food_id: 6},
   {table_id: 3, food_id: 4},
   {table_id: 4, food_id: 6},
];
const countUniques = (orders = []) => {
   const tableObj = {}, foodObj = {};
   orders.forEach(el => {
      tableObj[el.table_id] = null;
      foodObj[el.food_id] = null;
   });
   const tableUniqueIDs = Object.keys(tableObj).length;
   const foodUniqueIDs = Object.keys(foodObj).length;
   return {
      tableUniqueIDs, foodUniqueIDs
   };
};
console.log(countUniques(orders));
And the output in the console will be −
{ tableUniqueIDs: 3, foodUniqueIDs: 4 }
Bootstrap .has-success class

The has-success class allows you to set success action for input −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form class = "form-horizontal" role = "form">
         <div class = "form-group has-success">
            <label class = "col-sm-2 control-label" for = "inputSuccess">
               Input with success
            </label>
            <div class = "col-sm-10">
               <input type = "text" class = "form-control" id = "inputSuccess">
            </div>
         </div>
      </form>
   </body>
</html>
Square and Square root in Arduino

Arduino has support for several popular math functions, square and square root being among them. Let’s look at the square root first.
sqrt(x)
where x is a number of any data type. It returns a double.
For square, you ideally shouldn’t need a separate function. You can just multiply the number by itself.
x_squared = x*x;
However, Arduino does have a separate function for calculating squares. The syntax is −
sq(x) where x is a number of any data type. This again returns a double.
The following example illustrates the use of these functions −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   float x = 4.0;
   Serial.println(sqrt(x));
   Serial.println(sq(x));
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
Program to check whether given graph is bipartite or not in Python

Suppose we have one undirected graph, we have to check whether the graph is bipartite or not. As we know a graph is bipartite when we can split the nodes of the graph into two sets A and B such that every edge {u,v} in the graph has one node u in A and another node v in B.
So, if the input is like
Then the output will be True, [0,4] are in set A and [1,2,3] are in set B, and all edges are from A to B or B to A, not A to A or B to B.
To solve this, we will follow these steps−
Define a function dfs() . This will take source
Define a function dfs() . This will take source
for each vertex in graph[source], doif color[vertex] is not same as -1, thenif color[vertex] is same as color[source], thenresult[0] := Falsereturngo for the next iterationcolor[vertex] := 1 - color[source]dfs(vertex)
for each vertex in graph[source], do
if color[vertex] is not same as -1, thenif color[vertex] is same as color[source], thenresult[0] := Falsereturngo for the next iteration
if color[vertex] is not same as -1, then
if color[vertex] is same as color[source], thenresult[0] := Falsereturn
if color[vertex] is same as color[source], then
result[0] := False
result[0] := False
return
return
go for the next iteration
go for the next iteration
color[vertex] := 1 - color[source]
color[vertex] := 1 - color[source]
dfs(vertex)
dfs(vertex)
From the main method, do the following−
From the main method, do the following−
n := size of arr
n := size of arr
graph := empty adjacency list for vertices 0 to n-1
graph := empty adjacency list for vertices 0 to n-1
for i in range 0 to n, dofor each j in arr[i], doinsert i into graph[j]insert j into graph[i]color := a list of size n and fill with -1result := a list with one True value
for i in range 0 to n, do
for each j in arr[i], doinsert i into graph[j]insert j into graph[i]
for each j in arr[i], do
insert i into graph[j]
insert i into graph[j]
insert j into graph[i]
insert j into graph[i]
color := a list of size n and fill with -1
color := a list of size n and fill with -1
result := a list with one True value
result := a list with one True value
for i in range 0 to n, doif color[i] is same as -1, thendfs(i)
for i in range 0 to n, do
if color[i] is same as -1, then
if color[i] is same as -1, then
dfs(i)
dfs(i)
return result[0]
return result[0]
Let us see the following implementation to get better understanding −
 Live Demo
from collections import defaultdict
class Solution:
   def solve(self, arr):
      n = len(arr)
      graph = [set() for i in range(n)]
      for i in range(n):
         for j in arr[i]:
            graph[j].add(i)
            graph[i].add(j)
      color = [-1] * n
      result = [True]
      def dfs(source):
      for child in graph[source]:
         if color[child] != -1:
            if color[child] == color[source]:
               result[0] = False
               return
            continue
      color[child] = 1 - color[source]
      dfs(child)
   for i in range(n):
      if color[i] == -1:
      dfs(i)
   return result[0]
ob = Solution()
graph = [[1,2,3],[0],[0,4],[0,4],[2,3]]
print(ob.solve(graph))
graph = [[1,2,3],[0],[0,4],[0,4],[2,3]]
True
W3.CSS - Environment Setup

There are two ways to use W3.CSS −
Local Installation − You can download the W3.CSS file on your local machine and include it in your HTML code.
Local Installation − You can download the W3.CSS file on your local machine and include it in your HTML code.
CDN Based Version − You can include the W3.CSS file into your HTML code directly from the Content Delivery Network (CDN).
CDN Based Version − You can include the W3.CSS file into your HTML code directly from the Content Delivery Network (CDN).
Go to https://www.w3schools.com/w3css/w3css_downloads.asp to download the latest version available.
Go to https://www.w3schools.com/w3css/w3css_downloads.asp to download the latest version available.
Then, put the downloaded w3.css file in a directory of your website, e.g. /css.
Then, put the downloaded w3.css file in a directory of your website, e.g. /css.
Now you can include the css file in your HTML file as follows −
<html>
   <head>
      <title>The W3.CSS Example</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "css/w3.css">
   </head>
   
   <body>
      <header class = "w3-container w3-teal">
         <h1>Hello World!</h1>
      </header>
   </body>
</html>
It will produce the following result −
You can include the W3.CSS file into your HTML code directly from the Content Delivery Network (CDN). W3Schools.com provides content for the latest version.
Note − We are using W3Schools.com CDN version of the library throughout this tutorial.
Now let us rewrite the above example using jQuery library from W3Schools.com CDN.
<html>
   <head>
      <title>The W3.CSS Example</title>
      <meta name = "viewport" content = "width =  device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://www.w3schools.com/lib/w3.css">
   </head>
   
   <body>
      <header class = "w3-container w3-teal">
         <h1>Hello World!</h1>
      </header>
   </body>
</html>
It will produce the following result −
 Print
 Add Notes
 Bookmark this page
How to read a file from command line using Python?

In order to read a file form command line using Python, the script you want to use for it needs to accept a CLI argument. For example, say you want to write a cat command in python(a command that dumps all file content on the terminal). In order to do that, you could simply write a program:
import sys
with open(sys.argv[1], 'r') as f:
    contents = f.read()
print contents
If you save this file as cat.py and run it using:
$ python cat.py my_file.txt
This will take the my_file.txt and pass it to cat.py as a CLI argument in variable argv[1](second command line argument) which we can use to get the file and its contents.
How to loop through all values of an enum in C#?

To loop through all the values of enum, use the Enum.GetValues().
Firstly, set an Enum −
public enum Grade { A, B, C, D, E, F };
Now, with foreach loop, you need to loop through Enum.GetValues(typeof(Grade)) −
foreach (Grade g in Enum.GetValues(typeof(Grade))) {
   Console.WriteLine(g);
}
Here is the complete code −
 Live Demo
using System;

public class EnumExample {
   public enum Grade { A, B, C, D, E, F };
   public static void Main() {
      foreach (Grade g in Enum.GetValues(typeof(Grade))) {
         Console.WriteLine(g);
      }
   }
}
A
B
C
D
E
F
Add column with constant value to pandas dataframe - GeeksforGeeks

02 Dec, 2020
Prerequisite: Pandas 
In this article, we will learn how to add a new column with constant value to a Pandas DataFrame. Before that one must be familiar with the following concepts:
Pandas DataFrame : Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular arrangement with labeled axes (rows and columns). A Data frame may be a two-dimensional arrangement , i.e., data is aligned during a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns.
Column in DataFrame : In Order to pick a column in Pandas DataFrame, we will either access the columns by calling them by their columns name. Column Addition: so as to feature a column in Pandas DataFrame, we will declare a replacement list as a column and increase a existing Dataframe.
Constant : A fixed value. In Algebra, a continuing may be a number on its own, or sometimes a letter like a, b or c to face for a hard and fast number. Example: in “x + 5 = 9”, 5 and 9 are constants.
Import LibraryLoad or create a dataframeAdd column with constant value to dataframe
Import Library
Load or create a dataframe
Add column with constant value to dataframe
To understand these above mentioned steps, lets discuss some examples :
Example 1: (By using Pandas Series)
Python3
# import packagesimport pandas as pdimport numpy as np  # create dataframedf = pd.DataFrame({'Number': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},                   'Power 2': {0: 1, 1: 4, 2: 9, 3: 16, 4: 25},                   'Power 3': {0: 1, 1: 8, 2: 27, 3: 64, 4: 125}})  # view dataframeprint("Initial dataframe")display(df)    # adding column with constant valuedf['Power 0'] = pd.Series([1 for x in range(len(df.index))])  # view dataframeprint("Final dataframe")display(df)
Output :
Example 2: (As static value)
Python3
# import packagesimport pandas as pdimport numpy as np  # create dataframedf = pd.DataFrame({'Name': {0: 'Ram', 1: 'Deep', 2: 'Yash', 3: 'Aman', 4: 'Akash'},                   'Marks': {0: 68, 1: 87, 2: 45, 3: 78, 4: 56}})    # view dataframeprint("Initial dataframe")display(df)    # adding column with constant valuedf['Pass'] = True  # view dataframeprint("Final dataframe")display(df)
Output :
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
Tryit Editor v3.7 - Show Java

public class ReadFile {  
  public static void main(String[] args) {  
    try {
      File myObj = new File("filename.txt");
      Scanner myReader = new Scanner(myObj);  
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
Python | Sort list of lists by lexicographic value and then length

11 May, 2020
There are many times different types of sorting has been discussed in python lists. The sorting of python list of lists has also been discussed. But sometimes, we have two parameters upon which we need to sort. First one being the list sum and next being its length. Let’s discuss how this type of problem can be solved.
Method #1 : Using sort() twiceThe first approach that comes into the mind is the generic way that is to use the sort function twice, firstly on basis of the value and then on basis of size of list.
# Python code to demonstrate# sort list of lists by value and length# using sort() twice   # initializing list test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]  # printing the original listprint ("The original list is : " + str(test_list))  # using sort() twice # sort list of lists by value and lengthtest_list.sort()test_list.sort(key = len)  # printing resultprint ("The list after sorting by value and length " + str(test_list))
The original list is : [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]The list after sorting by value and length [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]
 Method #2 : Using lambda functionThe above method calls a single sort function twice but as an improvement to it, this method calls the sort function just once and uses lambda function to perform both sorts in one go.
# Python code to demonstrate# sort list of lists by value and length# using lambda function  # initializing list test_list = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]  # printing the original listprint ("The original list is : " + str(test_list))  # using lambda function # sort list of lists by value and lengthres = sorted(test_list, key = lambda i: (len(i), i))  # printing resultprint ("The list after sorting by value and length " + str(res))
The original list is : [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]The list after sorting by value and length [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]
Python list-programs
python-list
Python-list-of-lists
Python-sort
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
User Input in PySimpleGUI

04 Aug, 2020
It is important how keys are key for understanding PySimpleGUI elements. If the user does not specify a key, then the element will be called an input element, a key will be provided to the user by default in integer form, starting the numbering with zero. If the user doesn’t specify any keys, then the values returned will be returned as a list as the keys are sequential integers. 
This below example has no keys specified. The 3 input fields will have keys 0, 1, 2. Your first input element will be accessed as values[0], value[1] for the second, value[2] for the third, and so on.  
Example: Python Program for User Input using PySimpleGUI .
Python3
import PySimpleGUI as sg  # Add some color# to the windowsg.theme('SandyBeach')       # Very basic window.# Return values using# automatic-numbered keyslayout = [    [sg.Text('Please enter your Name, Age, Phone')],    [sg.Text('Name', size =(15, 1)), sg.InputText()],    [sg.Text('Age', size =(15, 1)), sg.InputText()],    [sg.Text('Phone', size =(15, 1)), sg.InputText()],    [sg.Submit(), sg.Cancel()]]  window = sg.Window('Simple data entry window', layout)event, values = window.read()window.close()  # The input data looks like a simple list # when automatic numberedprint(event, values[0], values[1], values[2])   
Output:  
Python-gui
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Extract range characters from String

03 May, 2022
Given a String, extract characters only which lie between given letters.
Input : test_str = ‘geekforgeeks is best’, strt, end = “g”, “s” 
Output : gkorgksiss 
Explanation : All characters after g and before s are retained. 
Input : test_str = ‘geekforgeeks is best’, strt, end = “g”, “r” 
Output : gkorgki 
Explanation : All characters after g and before r are retained.
Method #1 : Using list comprehension
In this, we check for character in range using comparison operation and list comprehension does task of iteration and creation of new list. Then join() can be employed to reconvert to string.
Python3
# Python3 code to demonstrate working of# Extract range  characters from String# Using list comprehension # initializing stringtest_str = 'geekforgeeks is best' # printing original stringprint("The original string is : " + str(test_str)) # initializing range lettersstrt, end = "f", "s" # join() to get result in stringres = ''.join([chr for chr in test_str if chr >= strt and chr <= end]) # printing resultprint("Extracted String : " + str(res))
The original string is : geekforgeeks is best
Extracted String : gkforgksiss
Method #2 : Using filter() + lambda + join()
Another way to solve this, in this, we perform task of  comparison using lambda, and filter() used lambda function to get required characters.
Python3
# Python3 code to demonstrate working of# Extract range  characters from String# Using filter() + lambda + join() # initializing stringtest_str = 'geekforgeeks is best' # printing original stringprint("The original string is : " + str(test_str)) # initializing range lettersstrt, end = "f", "s" # join() to get result in stringres = ''.join(list(filter(lambda chr : chr >= strt and chr <= end, test_str))) # printing resultprint("Extracted String : " + str(res))
The original string is : geekforgeeks is best
Extracted String : gkforgksiss
simmytarika5
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Add new column in Pandas Data Frame Using a Dictionary

Pandas Data Frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. It can be created using python dict, list, and series etc. In this article, we will see how to add a new column to an existing data frame.
So first let's create a data frame using pandas series. In the below example we are converting a pandas series to a Data Frame of one column, giving it a column name Month_no.
import pandas as pd
s = pd.Series([6,8,3,1,12])
df = pd.DataFrame(s,columns=['Month_No'])
print (df)
Running the above code gives us the following result −
   Month_No
0           6
1           8
2           3
3           1
4         12
Next we create a new python dictionary containing the month names with values from the pandas series as the indices of the dictionary. Then we use a map function to add the month's dictionary with the existing Data Frame to get a new column. The map function takes care of arranging the month names with the indices of the dictionary.
import pandas as pd
s = pd.Series([6,8,3,1,12])
df = pd.DataFrame(s,columns=['Month_No'])
months = {6:'Jun', 8:'Aug', 3:'Mar', 1:'Jan',12:'Dec'}
df['Month_Name'] = df['Month_No'].map(months)
print (df)
Running the above code gives us the following result −
   Month_No Month_Name
0        6         Jun
1        8         Aug
2        3         Mar
3        1         Jan
4        12       Dec
ElementAt() method in C#

ElementAt() is a System.Linq method in C# that is used to get and display element at a particular index.
The following is our string array −
string[] arr = { "One", "Two", "Three", "Four", "Five" };
Now to get an element at index 0, use the ElementAt() method −
arr.ElementAt(0);
The following is the complete code −
 Live Demo
using System.IO;
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      string[] arr = { "One", "Two", "Three", "Four", "Five" };
      // displaying element at index 0
      string res = arr.ElementAt(0);
      Console.WriteLine(res);
   }
}
One
GATE | GATE-CS-2014-(Set-1) | Question 28 - GeeksforGeeks

28 Jun, 2021
Match the following:
1) Waterfall model        a) Specifications can be
                              developed incrementally

2) Evolutionary model     b) Requirements compromises 
                             are inevitable

3) Component-based        c) Explicit recognition of risk
software engineering

4) Spiral development     d) Inflexible partitioning of 
                             the project into stages
(A) 1-a, 2-b, 3-c, 4-d(B) 1-d, 2-a, 3-b, 4-c(C) 1-d, 2-b, 3-a, 4-c(D) 1-c, 2-a, 3-b, 4-dAnswer: (B)Explanation:
Waterfall Model: We can not go back in previous project phase as soon as as we proceed to next phase ,So inflexible
Evolutionary: It keeps changing with evolution so incremental in nature
Component based: Reuse-based approach to defining, implementing and composing loosely coupled independent components into systems
Spiral: Spiral model is the most advanced .It includes four faces one of which is Risk.Phases: Planning, Risk Analysis, Engineering and Evaluation
Phases: Planning, Risk Analysis, Engineering and Evaluation
Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE CS 2019 | Question 50
GATE | GATE CS 2018 | Question 45
GATE | GATE CS 2008 | Question 69
GATE | GATE CS 2010 | Question 33
GATE | GATE CS 2011 | Question 43
GATE | GATE-CS-2015 (Set 3) | Question 46
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2020 | Question 16
GATE | GATE-CS-2004 | Question 63
Area of circle which is inscribed in an equilateral triangle?

The area of a circle inscribed inside an equilateral triangle is found using the
mathematical formula πa2/12.
Lets see how this formula is derived,
Formula to find the radius of the inscribed circle = area of the triangle / semi-perimeter of triangle.
Area of triangle of side a = (√3)a2/4
Semi-perimeter of triangle of side a = 3a/2
According to formula,
Radius of circle = (√3)a22/4 / 3a/2 = a/2√3
Area of circle = πr2 = πa2/12
 Live Demo
#include <stdio.h>
int main(void) {
   int a = 5;
   float pie = 3.14;
   float area = (float)((pie*a*a)/12);
   printf("the area of circle inscribed in the triangle of side %d is %f",a,area);
   return 0;
}
the area of circle inscribed in the triangle of side 5 is 6.541667
Python 3 - String endswith() Method

It returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given indices start and end.
str.endswith(suffix[, start[, end]])

suffix − This could be a string or could also be a tuple of suffixes to look for.
suffix − This could be a string or could also be a tuple of suffixes to look for.
start − The slice begins from here.
start − The slice begins from here.
end − The slice ends here.
end − The slice ends here.
TRUE if the string ends with the specified suffix, otherwise FALSE.
#!/usr/bin/python3

Str = 'this is string example....wow!!!'
suffix = '!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,20))

suffix = 'exam'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))
True
True
False
True


    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
How to configure Apache for Python CGI Programming?

To get your server run CGI scripts properly, you have to configure your Web server. We will discuss how to configure your Apache web server to run CGI scripts.
You may set a directory as ScriptAlias Directive (options for configuring Apache). This way, Apache understands that all the files residing within that directory are CGI scripts. This may be the most simple way to run CGI Scripts on Apache. A typical ScriptAlias line looks like following in httpd.conf file of your Apache web server.
ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/
So, search ScriptAlias in your httpd.conf file and uncomment the line (remove preceding #) if you want to keep all your CGI files in the default directory specified by Apache. But this may not meet your requirement always. So, we will look some other options also for running Python as CGI.
You may use the following to prepare a particular directory to run CGI files.
<Directory /usr/local/apache2/htdocs/somedir>Options +ExecCGI</Directory>
Where 'somedir' is the directory of your preference.
If you use the above configuration. then you have to specify the following also to tell server extensions of the CGI files you winch to run.
AddHandler cgi-script .cgi .pl
So, the above tells Apache to run files with .cgi and .pl extensions as CGI
If you want to run CGI files from user's directory, then you may use the following −
<Directory /home/*/public_html>
Options +ExecCGI
AddHandler cgi-script .cgi
</Directory>
The above says Apache to run all files with .cgi extension present within user's directory as CGI.
Again, if you wish to run all files placed within user's directory as CGI, then you may use the following −
<Directory /home/*/public_html/cg-bin>
Options +ExecCGI
SetHandler cgi-script
</Directory>
Using .htaccess
If you don't have access to your httpd.conf file, you may use a .htaccess file to run CGI scripts. To use files with certain extensions as CGI, configure you .htaccess file as following −
Options +ExecCGI
AddHandler cgi-script cgi pl
If you would like to run all files residing within a directory as CGI, you may use the following −
Options +ExecCGI
SetHandler cgi-script
HTML | DOM Input Number value Property

03 Jun, 2022
The DOM Input Number value Property in HTML DOM is used to set or return the value of a value attribute of the number field. The value attribute specifies the initial value of the input number Field. It contains the default value or the user types. Syntax: 
It returns the value property.
numberObject.value
It is used to Set the value property.
numberObject.value = number
Property Value: It contains single value number which defines the value of the input number field. 
Return Value: It returns the numeric value which represent the value of the number Field. 
Example-1: This example illustrates how to return the property. 
html
<!DOCTYPE html><html>     <body style="text-align:center;">         <h1 style="color:green;">            GeeksForGeeks        </h1>         <h2>DOM Input Number value Property</h2>         <input type="number"            id="myNumber"            value="10">         <p>Click the button to get the        number of the number field.</p>         <button onclick="myFunction()">            Click Here!        </button>         <p id="demo"></p>         <script>            function myFunction() {                                 // Accessing input value                var x =                document.getElementById("myNumber").value;                document.getElementById("demo").innerHTML = x;            }        </script>     </body> </html>
Output: Before Clicking On Button:  After Clicking On Button:  Example-2 : This Example illustrates how to set the Property. 
html
<!DOCTYPE html><html>     <body style="text-align:center;">         <h1 style="color:green;">            GeeksForGeeks        </h1>         <h2>DOM Input Number value Property</h2>         <input type="number"            id="myNumber"            value="10">         <p>Click the button to change the        number of the number field.</p>         <button onclick="myFunction()">            Click Here!        </button>         <p id="demo"></p>         <script>            function myFunction() {                                 // Accessing input value                var x =                document.getElementById("myNumber").valued  = "20";                document.getElementById("demo").innerHTML =                "The value of number was changed to " + x;            }        </script>     </body> </html>
Output : Before Clicking On Button:  After Clicking On Button:  Supported Browsers: The browser supported by DOM input number value Property are listed below:
Google Chrome
Internet Explorer 10.0 +
Firefox
Opera
Safari
hritikbhatnagar2182
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
Design a Tribute Page using HTML & CSS
Form validation using jQuery
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
REST API (Introduction)
Differences between Functional Components and Class Components in React