code-rag-bench/online-tutorials huggingface dataset:
Python | Calculate geographic coordinates of places using google geocoding API

15 Feb, 2022
Geocoding is the process of converting addresses into geographic coordinates like latitude and longitude, which can be used to mark position on map.To use the Google Maps Geocoding API, one must need an API key, which can be get form here.   Modules needed : 
 
Below is the implementation : 
Python3
# Python program to calculate geographic# coordinates of places using google# geocoding API # importing required modulesimport requests, json # enter your api key hereapi_key = 'Your_api_key' # url variable store urlurl = 'https://maps.googleapis.com/maps/api/geocode/json?' # take place as inputplace = input() # get method of requests module# return response objectres_ob = requests.get(url + 'address =' +                place + '&key =' + api_key) # json method of response object# convert json format data# into python format data.x = res_ob.json() # print the value of xprint(x)
Output :  
Dehradun

{'results': [{'address_components': [{'long_name': 'Dehradun', 'short_name': 'Dehradun', 'types': ['locality', 'political']}, {'long_name': 'Dehradun', 'short_name': 'Dehradun', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Uttarakhand', 'short_name': 'UK', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'India', 'short_name': 'IN', 'types': ['country', 'political']}], 'formatted_address': 'Dehradun, Uttarakhand, India', 'geometry': {'bounds': {'northeast': {'lat': 30.4041936, 'lng': 78.1089305}, 'southwest': {'lat': 30.2466633, 'lng': 77.92533879999999}}, 'location': {'lat': 30.3164945, 'lng': 78.03219179999999}, 'location_type': 'APPROXIMATE', 'viewport': {'northeast': {'lat': 30.4041936, 'lng': 78.1089305}, 'southwest': {'lat': 30.2466633, 'lng': 77.92533879999999}}}, 'place_id': 'ChIJr4jIVsMpCTkRmYdRMsBiNUw', 'types': ['locality', 'political']}], 'status': 'OK'}
 
sagar0719kumar
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Poisson Probability Mass Function Plot in Python?

13 Jan, 2022
In this article, we will see how we can create a Poisson probability mass function plot in Python. In probability theory and statistics, the Poisson distribution is a discrete probability distribution that expresses the probability of a given number of events occurring in a fixed interval of time or space if these events occur with a known constant mean rate and independently of the time since the last event. The Poisson distribution can also be used for the number of events in other specified intervals such as distance, area or volume. 
In order to plot the Poisson distribution, we will use scipy module. SciPy is a free and open-source Python library used for scientific computing and technical computing. SciPy contains modules for optimization, linear algebra, integration, interpolation, special functions, FFT, signal and image processing, ODE solvers and other tasks common in science and engineering.
In order to get the poisson probability mass function plot in python we use scipy’s poisson.pmf method. Syntax : poisson.pmf(k, mu, loc)Argument : It takes numpy array, shape parameter and location as argumentReturn : It returns numpy array  
Example 1:
Python3
# importing poisson from scipyfrom scipy.stats import poisson # importing numpy as npimport numpy as np # importing matplotlib as pltimport matplotlib.pyplot as plt  # creating a numpy array for x-axisx = np.arange(0, 100, 0.5) # poisson distribution data for y-axisy = poisson.pmf(x, mu=40, loc=10)  # plotting the graphplt.plot(x, y) # showing the graphplt.show()
Output :  
Example 2: Using step size of data as 1 
Python3
# importing poisson from scipyfrom scipy.stats import poisson # importing numpy as npimport numpy as np # importing matplotlib as pltimport matplotlib.pyplot as plt  # creating a numpy array for x-axis# using step size as 1x = np.arange(0, 100, 1) # poisson distribution data for y-axisy = poisson.pmf(x, mu=10, loc=40)  # plotting the graphplt.plot(x, y) # showing the graphplt.show()
Output:  
Example 3: Plotting scatterplot for better viewing of data points 
Python3
# importing poisson from scipyfrom scipy.stats import poisson # importing numpy as npimport numpy as np # importing matplotlib as pltimport matplotlib.pyplot as plt  # creating a numpy array for x-axisx = np.arange(0, 100, 0.5) # poisson distribution data for y-axisy = poisson.pmf(x, mu=50, loc=0)  # plotting thescatter plot graphplt.scatter(x, y) # showing the graphplt.show()
Output:
kapoorsagar226
surindertarika1234
sweetyty
Python-matplotlib
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
negate function in C++ STL

18 Jul, 2018
This function is used to negate the given values i.e. to change the sign of the values. It changes the positive values to negative and vice-versa.
Note: Objects of this class can be used on standard algorithms such as transform.Syntax:
transform(arr_begin, arr_end, arr2_begin, negate())

Parameters: It accepts four parameters which are described below:
arr_begin: It is the lower bound of the given array.arr_end: It is the upper bound of the given array.arr2_begin: It is the lower bound of the second array in which the modified values to be updated.negate(): It is the function that is used to negate the values of the given array.
arr_begin: It is the lower bound of the given array.
arr_end: It is the upper bound of the given array.
arr2_begin: It is the lower bound of the second array in which the modified values to be updated.
negate(): It is the function that is used to negate the values of the given array.
Return values: It returns the same values with the opposite sign.
Below is the implementation that shows the working of negate() function:
// C++ program to show the working // of negate() function#include <algorithm>#include <functional>#include <iostream>using namespace std;int main(){    int arr[] = { 5, 7, -20, -60, 50 };      // using transform negation of values is done    transform(arr, arr + 5, arr, negate<int>());      for (int i = 0; i < 5; i++)        cout << arr[i] << ' ';      return 0;}
-5 -7 20 60 -50

CPP-Functions
cpp-template
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
eval command in Linux with Examples

15 May, 2019
eval is a built-in Linux command which is used to execute arguments as a shell command. It combines arguments into a single string and uses it as an input to the shell and execute the commands.
Syntax
eval [arg ...]
Example: In the below figure, you can see that cd Desktop command is stored in a variable “CD” as a shell command. Now you can use this “CD” as an argument with eval command.
Options:
help : It displays help information.
linux-command
Linux-Shell-Commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
Basic Operators in Shell Scripting
Java program to Find the first non-repeating character from a stream of characters

To find the first non-repeating character from a stream of characters, the Java code is as follows −
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo{
   final static int max_chars = 256;
   static void non_repeating_char(){
      List<Character> my_list = new ArrayList<Character>();
      boolean[] repeat = new boolean[max_chars];
      String my_str = "Thisisasample";
      for (int i = 0; i < my_str.length(); i++){
         char x = my_str.charAt(i);
         if (!repeat[x]){
            if (!(my_list.contains(x))){
               my_list.add(x);
            }
            else{
               my_list.remove((Character)x);
               repeat[x] = true;
            }
         }
         if (my_list.size() != 0){
            System.out.print("The first non-repeating character of the string is ");
            System.out.println(my_list.get(0));
         }
      }
   }
   public static void main(String[] args){
      non_repeating_char();
   }
}
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
A class named Demo contains a function named ‘non_repeating_char’ function. A list is created and a string is defined. This string is iterated over, and every character is inspected, and its count is stored in the form of a Boolean variable, in an array named ‘repeat’. The value will be true if it is repeated and false otherwise. In the main function, the function is called, and relevant message is displayed on the console.
Presentational vs container components - GeeksforGeeks

12 Oct, 2021
In react the components are divided into two categories: presentational components and container components. Each of these have their own characteristics. Let’s look at both of these components in details.Presentational components
Mainly concerned with how things look.
Have no major dependencies on the rest of the app.
No connection with the specification of the data that is outside the component.
Mainly receives data and callbacks exclusively via props.
May contain both presentational and container components inside it considering the fact that it contains DOM markup and styles of their own.
Example:For example, the below code denotes a presentational component, and it gets its data from the props and just focuses on showing an element.
// presentational componentconst Users = props =>       (<ul>            {props.users.map(user =>             (<li>{itr}</li>    ))         }      </ul>)
Container components
Mainly concerned with how things work.
May contain both presentational and container component but does not have DOM and markup of their own.
Provide the data and behaviour to presentational or other container components.
Call flux actions and provides these as callbackss to the presentational component.
// container componentclassUsersContainerextendsReact.Component{constructor()    {     this.state = {          itr: []        }  }  componentDidMount() {       axios.get('/users').then(itr=>this.setState({ users: itr}))        )  }render() {  return<Usersusers={this.state.itr} />    }}
Finally at the conclusion we can conclude in simple terms that the presentational components are concerned with the look, container components are concerned with making things work.
sweetyty
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
How to calculate the number of days between two dates in javascript?
How to create footer to stay at the bottom of a Web page?
Difference between var, let and const keywords in JavaScript
maxsize() method in Tkinter | Python - GeeksforGeeks

28 Nov, 2021
This method is used to set the maximum size of the root window (maximum size a window can be expanded). User will still be able to shrink the size of the window to the minimum possible.
Syntax :
 master.maxsize(height, width) 
Here, height and width are in pixels.
Code #1:
# importing only those functions# which are neededfrom tkinter import *from tkinter.ttk import * from time import strftime  # creating tkinter windowroot = Tk()  # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks',       font =('Verdana', 15)).pack(side = TOP, pady = 10)  Button(root, text = 'Click Me !').pack(side = TOP)  mainloop()
Output :Initial size of the window (maximum size of the window is not set)
Expanded size of the window (this window can be expanded til the size of the screen because size is not fixed). Code #2: Fixing maximum size of the root window
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * from time import strftime  # creating tkinter windowroot = Tk()  # Fixing the size of the root window.# No one can now expand the size of the# root window than the specified one.root.maxsize(200, 200)  # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks',       font =('Verdana', 15)).pack(side = TOP, pady = 10)  Button(root, text = 'Click Me !').pack(side = TOP)  mainloop()
Output :Maximum expanded size of the window
Note: Tkinter also offers a minsize() method which is used to set the minimum size of the window.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions
sum() function in Python
How to find inverse Laplace Transforms using MATLAB ? - GeeksforGeeks

21 Apr, 2021
In this article, we will see how to find Laplace Transform in MATLAB. Laplace Transform helps to simplify problems that involve Differential Equations into algebraic equations. Inverse Laplace Transform converts Laplace Domain Function F(s) into time-domain function f(t)
Using the above function one can generate a Time-domain function of any Laplace expression.
Example 1: Find the Inverse Laplace Transform of 
Matlab
% specify the variable a, t and s % as symbolic onessyms a t s  % define function F(s) F = s/(a^2 + s^2);  % ilaplace command to transform into time% domain function f(t)  % Inverse Laplace Functionf1=ilaplace(F,s,t);  % Display the output valuedisp(f1);  % Output can be verified by transforming % function f1 into Laplace Domain F(s)f=laplace(f1,t,s);  % Laplace Functiondisp(f);
Output:
which is 
Example 2: Find the Inverse Laplace Transform of 1/(s-a)
Matlab
% specify the variable a, t and % s as symbolic onessyms a t s  % define function F(s) F = 1/(s-a);  % ilaplace command to transform into% time domain function f(t)% Inverse Laplace Functionf1=ilaplace(F,s,t);   % Display the output valuedisp(f1);  % Output can be verified by transforming % function f1 into Laplace Domain F(s)f=laplace(f1,t,s);  % Laplace Functiondisp(f);
Output:
which is 
Example 3: Find the Inverse Laplace Transform of 
Matlab
% specify the variable a, t and % s as symbolic onessyms a t s  % define function F(s) F = 2/(s+1)+3/(s+2)+1/s;  % ilaplace command to transform into% time domain function f(t)  % Inverse Laplace Functionf1=ilaplace(F,s,t);  % Display the output valuedisp(f1);  %Output can be verified by transforming % function f1 into Laplace Domain F(s)f=laplace(f1,t,s);  % Laplace Functiondisp(f);
Output:
which is 
MATLAB-Maths
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
MRI Image Segmentation in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Laplace Transform in MATLAB
Laplacian of Gaussian Filter in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Boundary Extraction of image using MATLAB
jps - Unix, Linux Command

If
jps is run without specifying a hostid, it will look for instrumented JVMs
on the local host. If started with a hostid, it will look for JVMs
on the indicated host, using the specified protocol and port.
A jstatd process is assumed to be running on the target host.


The jps command will report the local VM identifier, or lvmid,
for each instrumented JVM found on the target system. The lvmid is
typically, but not necessarily, the operating system’s
process identifier for the JVM process. With no options,
jps will list each Java
application’s lvmid followed by the short form of the
application’s class name or jar file name. The short form of
the class name or JAR
file name omits the class’s package information or the
JAR files path information.


The jps command uses the java launcher to find the class name and
arguments passed to the main method. If the target JVM is started
with a custom launcher, the class name (or JAR file name)
and the arguments to the main method will not be available. In
this case, the
jps command will output the string Unknown for the class name
or JAR file name and for the arguments to the main method.


The list of JVMs produced by the jps command may be limited by
the permissions granted to the principal running the command. The
command will only list the JVMs for which the principle has
access rights as determined by operating system specific access control
mechanisms.


NOTE - This utility is unsupported and may or may not be
available in future versions of the JDK.
It is not currently available on Widows 98 and Windows ME platforms.



[protocol:][[//]hostname][:port][/servername]



lvmid [ [ classname | JARfilename | "Unknown"] [ arg* ] [ jvmarg* ] ]


Where all output tokens are separated by white space. An arg
that includes embedded white space will introduce ambiguity when
attempting to map arguments to their actual positional parameters.


NOTE- You are advised not to write scripts to parse jps output
since the format may change in future releases. If you choose to write
scripts that parse jps output, expect to modify them for
future releases of this tool.


Listing the instrumented JVMs on the local host:



jps
18027 Java2Demo.JAR
18032 jps
18005 jstat



jps -l remote.domain
3002 /opt/j2sdk1.5.0/demo/jfc/Java2D/Java2Demo.JAR
2857 sun.tools.jstatd.jstatd



jps -m remote.domain:2002
3002 /opt/j2sdk1.5.0/demo/jfc/Java2D/Java2Demo.JAR
3102 sun.tools.jstatd.jstatd -p 2002

java (1)
java (1)
jstat (1)
jstat (1)
jstatd (1)
jstatd (1)
rmiregistry (1)
rmiregistry (1)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Program for printing array in Pendulum Arrangement.

To arrange elements of the array following pendulum arrangement.
Sort the given array, create an empty array to store the result.
Store the 0th element in a variable say temp.
Store the element at index 1 in the sorted array in (mid+1)st position of the resultant array, and the next element int the (mid-1)st position and the next element in (mid+2)nd element and so on.
 Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class ArrayinPendulumArrangement {
   public static int[] swap(int origPos, int newPos, int[] array){
      origPos = 1;
      newPos = 4;
      int temp = array[origPos];
      array[origPos] = array[newPos];
      array[newPos] = temp;
      System.out.println(Arrays.toString(array));
      return array;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the required size of the array (odd) :");
      int size = sc.nextInt();
      int [] myArray = new int[size];
      System.out.println("Enter elements of the array :");
      for(int i = 0; i< size; i++){
         myArray[i] = sc.nextInt();
      }
      //Sort the given array
      Arrays.sort(myArray);
      System.out.println("Contents of the Array"+Arrays.toString(myArray));
      int temp = myArray[0];
      int mid = (size-1)/2;
      int k =1;
      int[] result = new int[size];
      for(int i = 1; i<=mid; i++){
         result[mid+i] = myArray[k++];
         result[mid-i] = myArray[k++];
      }
      result[mid] = temp;
      System.out.println("Pendulum arrangement "+Arrays.toString(result));
   }
}
Enter the required size of the array (odd) :
5
Enter elements of the array :
12
28
46
77
39
Contents of the Array[12, 28, 39, 46, 77]
Pendulum arrangement[77, 39, 12, 28, 46]
PyQt - QSlider Widget & Signal

QSlider class object presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. Position of the handle on the groove is equivalent to an integer between the lower and the upper bounds of the control.
A slider control can be displayed in horizontal or vertical manner by mentioning the orientation in the constructor.
self.sp = QSlider(Qt.Horizontal)
self.sp = QSlider(Qt.Vertical)

The following table lists some of the frequently used methods of QSlider class −
Given below are the most commonly used methods of QSlider.
setMinimum()
Sets the lower bound of the slider
setMaximum()
Sets the upper bound of the slider
setSingleStep()
Sets the increment/decrement step
setValue()
Sets the value of the control programmatically
value()
Returns the current value
setTickInterval()
Puts the number of ticks on the groove
setTickPosition()
Places the ticks on the groove. Values are −
valueChanged()
When the slider's value has changed
sliderPressed()
When the user starts to drag the slider
sliderMoved()
When the user drags the slider
sliderReleased()
When the user releases the slider
valueChanged() signal is the one which is most frequently used.
The following example demonstrates the above functionality. A Label and a horizontal slider is placed in a vertical layout. Slider’s valueChanged() signal is connected to valuechange() method.
self.sl.valueChanged.connect(self.valuechange)

The slot function valuechange() reads current value of the slider and uses it as the size of font for label’s caption.
size = self.sl.value()
self.l1.setFont(QFont("Arial",size))

The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class sliderdemo(QWidget):
   def __init__(self, parent = None):
      super(sliderdemo, self).__init__(parent)

      layout = QVBoxLayout()
      self.l1 = QLabel("Hello")
      self.l1.setAlignment(Qt.AlignCenter)
      layout.addWidget(self.l1)
		
      self.sl = QSlider(Qt.Horizontal)
      self.sl.setMinimum(10)
      self.sl.setMaximum(30)
      self.sl.setValue(20)
      self.sl.setTickPosition(QSlider.TicksBelow)
      self.sl.setTickInterval(5)
		
      layout.addWidget(self.sl)
      self.sl.valueChanged.connect(self.valuechange)
      self.setLayout(layout)
      self.setWindowTitle("SpinBox demo")

   def valuechange(self):
      size = self.sl.value()
      self.l1.setFont(QFont("Arial",size))
		
def main():
   app = QApplication(sys.argv)
   ex = sliderdemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −
The font size of the label changes as handle of the slider is moved across the handle.

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Bootstrap Contextual classes

The Bootstrap Contextual Class allows you to change the background color of your table rows or individual cells.
The following are the classes −
The following is an example of the active class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Table</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>
      <table class = "table">
         <thead>
            <tr>
               <th>Subject</th>
               <th>Marks</th>
               <th>Student</th>
            </tr>
         </thead>
         <tbody>
            <tr class = "active">
               <td>Maths</td>
               <td>90</td>
               <td>Amit</td>
            </tr>
            <tr>
               <td>Science</td>
               <td>80</td>
               <td>Aman</td>
            </tr>
            <tr>
               <td>English</td>
               <td>85</td>
               <td>Rahul</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
How to find the cube root of a number in JavaScript?

Using Math object in javascript any kind of operation can be done. Math.cbrt() is a method especially used to find the cube root of a number. It takes a number as a parameter and returns its cube root.
Math.cbrt(64);
It takes a number as a parameter and returns its cube root value as the output.
In the following example, the cube roots of only positive values were found out and displayed in the output.
Live Demo
<html>
<body>
<script>
   document.write(Math.cbrt(64));
   document.write("</br>");
   document.write(Math.cbrt(27));
   document.write("</br>");
   document.write(Math.cbrt(0));
</script>
</body>
</html>
4
3
0
This method can take negative values also. In the following example, the cube roots of the negative values were found out and displayed in the output.
 Live Demo
<html>
<body>
<script>
   document.write(Math.cbrt(-64));
   document.write("</br>");
   document.write(Math.cbrt(-27));
   document.write("</br>");
   document.write(Math.cbrt(0));
   document.write("</br>");
   document.write(Math.cbrt(Infinity));
</script>
</body>
</html>
-4
-3
0
Infinity
Capacity of a List in C#

To get the capacity of a list, the code is as follows −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<string> list1 = new List<string>();
      list1.Add("One");
      list1.Add("Two");
      list1.Add("Three");
      list1.Add("Four");
      list1.Add("Five");
      Console.WriteLine("Elements in List1...");
      foreach (string res in list1){
         Console.WriteLine(res);
      }
      Console.WriteLine("Capacity of List1 = "+list1.Capacity);
      List<string> list2 = new List<string>();
      list2.Add("India");
      list2.Add("US");
      list2.Add("UK");
      list2.Add("Canada");
      list2.Add("Poland");
      list2.Add("Netherlands");
      Console.WriteLine("Elements in List2...");
      foreach (string res in list2){
         Console.WriteLine(res);
      }
      Console.WriteLine("Capacity of List2 = "+list2.Capacity);
      Console.WriteLine("Is List2 equal to List1? = "+list2.Equals(list1));
   }
}
This will produce the following output −
Elements in List1...
One
Two
Three
Four
Five
Capacity of List1 = 8
Elements in List2...
India
US
UK
Canada
Poland
Netherlands Capacity of List2 = 8
Is List2 equal to List1? = False
Let us now see another example −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<string> list = new List<string>();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      Console.WriteLine("Elements in List1...");
      foreach (string res in list){
         Console.WriteLine(res);
      }
      Console.WriteLine("\nCount of elements in list = "+list.Count);
      Console.WriteLine("Capacity of List (updated) = "+list.Capacity);
      list.Clear();
      Console.WriteLine("\nCount of elements in list (updated) = "+list.Count);
      Console.WriteLine("Capacity of List now = "+list.Capacity);
   }
}
This will produce the following output −
Elements in List1...
One
Two
Three
Four
Five
Count of elements in list = 5
Capacity of List (updated) = 8
Count of elements in list (updated) = 0 Capacity of List now = 8
Compute the Covariance between Two Vectors in R Programming - cov() Function - GeeksforGeeks

10 Jun, 2020
cov() function in R Language is used to measure the covariance between two vectors.
Syntax: cov(x, y, method)
Parameters:x, y: Data vectorsmethod: Type of method to be used
Example 1:
# Data vectors x <- c(1, 3, 5, 10)     y <- c(2, 4, 6, 20)     # Print covariance using Pearson methodprint(cov(x, y, method = "pearson")) 
Output:
[1] 30.66667

Example 2:
# Data vectors x <- c(1, 3, 5, 10)     y <- c(2, 4, 6, 20)     # Print covariance using Pearson methodprint(cov(x, y, method = "kendall")) 
Output:
[1] 12

Example 3:
# Data vectors x <- c(1, 3, 5, 10)     y <- c(2, 4, 6, 20)     # Print covariance using Pearson methodprint(cov(x, y, method = "spearman")) 
Output:
[1] 1.666667

R Math-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
How to change Colors in ggplot2 Line Plot in R ?
How to filter R DataFrame by values in a column?
Linear Discriminant Analysis in R Programming
R - Operators
How can I save new Date() in MongoDB?

To save new Date() in MongoDB, you can use new ISODate(). Let us create a collection with documents −
> db.saveDateDemo.insertOne({"UserName":"John","UserLoginDatetime":new ISODate('2018-01-31 12:34:56')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd67d4de8cc557214c0e04")
}
> db.saveDateDemo.insertOne({"UserName":"John","UserLoginDatetime":new ISODate('2019-02-01 04:01:10')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd67e8de8cc557214c0e05")
}
> db.saveDateDemo.insertOne({"UserName":"John","UserLoginDatetime":new ISODate('2019-04-22 12:36:45')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd6805de8cc557214c0e06")
}
Display all documents from a collection with the help of find() method −
> db.saveDateDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cbd67d4de8cc557214c0e04"),
   "UserName" : "John",
   "UserLoginDatetime" : ISODate("2018-01-31T12:34:56Z")
}
{
   "_id" : ObjectId("5cbd67e8de8cc557214c0e05"),
   "UserName" : "John",
   "UserLoginDatetime" : ISODate("2019-02-01T04:01:10Z")
}
{
   "_id" : ObjectId("5cbd6805de8cc557214c0e06"),
   "UserName" : "John",
   "UserLoginDatetime" : ISODate("2019-04-22T12:36:45Z")
}
Pattern.matches() method in Java Regular Expressions

The java.util.regex.Pattern.matches() method matches the regular expression and the given input. It has two parameters i.e. the regex and the input. It returns true if the regex and the input match and false otherwise.
A program that demonstrates the method Pattern.matches() in Java regular expressions is given as follows:
 Live Demo
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      String regex = "a*b";
      String input = "aaab";
      System.out.println("Regex: " + regex);
      System.out.println("Input: " + input);
      boolean match = Pattern.matches(regex, input);
      System.out.println("\nDoes the regex match with the input? " + match);
   }
}
Regex: a*b
Input: aaab
Does the regex match with the input? true
Now let us understand the above program.
The regex and the input values are printed. Then the Pattern.matches() method matches the regular expression and the given input and the result is printed. A code snippet which demonstrates this is as follows:
String regex = "a*b";
String input = "aaab";
System.out.println("Regex: " + regex);
System.out.println("Input: " + input);
boolean match = Pattern.matches(regex, input);
System.out.println("\nDoes the regex match with the input? " + match);
CSS Layout - Horizontal & Vertical Align

To horizontally center a block element (like <div>), use margin: auto;
Setting the width of the element will prevent it from stretching out to the 
edges of its container.
The element will then take up the specified width, and the remaining space 
will be split equally between the two margins:
This div element is centered.
Note: Center aligning has no effect if the width property is not set 
(or set to 100%).
To just center the text inside an element, use text-align: center;
This text is centered.
Tip: For more examples on how to align text, see the CSS Text chapter.
To center an image, set left and right margin to auto and make it into a block element:
One method for aligning elements is to use position: absolute;:
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
Another method for aligning elements is to use the float property:
Note: If an element is taller than the element containing it, and it is floated, it 
will overflow outside of its container. You can use the "clearfix hack" to fix this (see example below).
Then we can add the clearfix hack to the containing element to fix 
this problem:
There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding:
I am vertically centered.
To center both vertically and horizontally, use padding and text-align: center:
I am vertically and horizontally centered.
Another trick is to use the line-height property with a value that is equal 
to the height property:
I am vertically and horizontally centered.
If padding and line-height 
are not options, another solution is to use positioning and the transform property:
I am vertically and horizontally centered.
Tip: You will learn more about the transform property in our 2D Transforms 
Chapter.
You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:
Tip: You will learn more about Flexbox in our CSS Flexbox Chapter.
Use the margin property to make sure that the <div> element is center aligned according to its parent element.
<style>
.intro {
  width: 200px;
  : ;
}
</style>

<body>

<div class="intro">
Lorem ipsum dolor sit amet,consectetur adipiscing elit.Phasellus imperdiet, nulla et dictum interdum,nisi lorem egestas odio,vitae scelerisque enim ligula venenatis dolor.
</div>

</body>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to create a dropdown navigation bar with CSS?

Following is the code to create a dropdown navigation bar −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
.menu-btn {
   background-color: #040008;
   color: white;
   padding: 16px;
   font-size: 20px;
   font-weight: bolder;
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   border: none;
}
.dropdown-menu {
   position: relative;
   display: inline-block;
}
.menu-content {
   display: none;
   position: absolute;
   background-color: #017575;
   min-width: 160px;
   z-index: 1;
}
nav{
   background-color: #017575;
}
.links,.links-hidden{
   display: inline-block;
   color: rgb(255, 255, 255);
   padding: 12px 16px;
   text-decoration: none;
   font-size: 18px;
   font-weight: bold;
}
.links-hidden{
   display: block;
}
.links{
   display: inline-block;
}
.links-hidden:hover,.links:hover {
   background-color: rgb(8, 107, 46);
}
.dropdown-menu:hover .menu-content {
   display: block;
}
.dropdown-menu:hover .menu-btn {
   background-color: #3e8e41;
}
</style>
</head>
<body>
<h2>Hover on the below dropdown button in navbar to open dropdown menu</h2>
<nav>
<a class="links" href="#">HOME</a>
<a class="links" href="#">EMPLOYEES</a>
<a class="links" href="#">CAREER</a>
<div class="dropdown-menu">
<button class="menu-btn">Open <</button>
<div class="menu-content">
<a class="links-hidden" href="#">Contact Us</a>
<a class="links-hidden" href="#">Visit Us</a>
<a class="links-hidden" href="#">About Us</a>
</div>
</div>
</nav>
</body>
</html>
The above code will produce the following output −
On hovering above the open button the following output will be produced −
Using find() to search for nested keys in MongoDB?

For find() to search for nested keys in MongoDB, you can use dot(.) notation. Following is the
syntax
db.yourCollectionName.find({"yourOuterFieldName.yourInnerFieldName":"yourValue"}).pretty();
Let us first create a collection with documents:
>db.searchForNestedKeysDemo.insertOne({"ClientName":"Larry","ClientAge":28,"ClientExtra
Details":{"isEducated":true,"CountryName":"US"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca20e8b66324ffac2a7dc64")
}
>db.searchForNestedKeysDemo.insertOne({"ClientName":"Chris","ClientAge":29,"ClientExtra
Details":{"isEducated":false,"CountryName":"UK"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca20ea366324ffac2a7dc65")
}
>db.searchForNestedKeysDemo.insertOne({"ClientName":"David","ClientAge":39,"ClientExtra
Details":{"isEducated":true,"CountryName":"AUS"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca20eba66324ffac2a7dc66")
}
Following is the query to display all documents from a collection with the help of find() method
> db.searchForNestedKeysDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca20e8b66324ffac2a7dc64"),
   "ClientName" : "Larry",
   "ClientAge" : 28,
   "ClientExtraDetails" : {
      "isEducated" : true,
      "CountryName" : "US"
   }
}
{
   "_id" : ObjectId("5ca20ea366324ffac2a7dc65"),
   "ClientName" : "Chris",
   "ClientAge" : 29,
   "ClientExtraDetails" : {
      "isEducated" : false,
      "CountryName" : "UK"
   }
}
{
   "_id" : ObjectId("5ca20eba66324ffac2a7dc66"),
   "ClientName" : "David",
   "ClientAge" : 39,
   "ClientExtraDetails" : {
      "isEducated" : true,
      "CountryName" : "AUS"
   }
}
Following is the query to search for nested keys in MongoDB
> db.searchForNestedKeysDemo.find({"ClientExtraDetails.CountryName":"UK"}).pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca20ea366324ffac2a7dc65"),
   "ClientName" : "Chris",
   "ClientAge" : 29,
   "ClientExtraDetails" : {
      "isEducated" : false,
      "CountryName" : "UK"
   }
}
How to convert the hashtable to the JSON format using PowerShell?

To convert the hashtable to the JSON format we can use the ConvertTo-Json command. First, we have the following hashtable,
$Body = [PSCustomObject]@{
   AppName = 'StorageXIO'
   AppID ='xo2ss-12233-2nn12'
   License = 'valid'
}
To convert the hashtable to the JSON format,
$Body | ConvertTo-Json
Once you run the above command, properties are converted to the JSON format.
{
   "AppName": "StorageXIO",
   "AppID": "xo2ss-12233-2nn12",
   "License": "valid"
}
HTML hidden Attribute

The HTML hidden attribute is used to communicate to the user that element with hidden attribute is no longer relevant to the document and should not be visible to the user.
Let us see an example of hidden attribute −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML hidden attribute</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>HTML-hidden-attribute</legend>
<input type="text" id="textSelect" placeholder="Your Authorization Level">
<select id="selection1" hidden>
<option>Add user</option>
<option>Delete user</option>
<option>Modify user</option>
</select>
<select id="selection2" hidden>
<option>Mail admin</option>
<option>Call admin</option>
</select>
<input type="button" value="go" onclick="displaySelection()">
<div id="divDisplay">Hello</div>
</fieldset>
</form>
<script>
   var textSelect = document.getElementById("textSelect");
   var divDisplay = document.getElementById("divDisplay");
   var selection1 = document.getElementById("selection1");
   var selection2 = document.getElementById("selection2");
   function displaySelection() {
      if(textSelect.value === 'admin'){
         selection1.hidden = false;
         selection2.hidden = true;
         divDisplay.textContent = 'Welcome Admin';  
      } else if(textSelect.value === 'user'){
         selection2.hidden = false;
         selection1.hidden = true;
         divDisplay.textContent = 'Welcome User';
      } else{
         selection2.hidden = true;
         selection1.hidden = true;
         divDisplay.textContent = 'Your input does not match any authorization';
      }
   }
</script>
</body>
</html>
1) Clicking ‘Go’ button with user authorization level −
2) Clicking ‘Go’ button with admin authorization level −
3) Clicking ‘Go’ button with unauthorized level −
pthread_equal() in C with example - GeeksforGeeks

14 Oct, 2019
Prerequisite : Multithreading, pthread_self() in C with Example
pthread_equal() = This compares two thread which is equal or not. This function compares two thread identifiers. It return ‘0’ and non zero value. If it is equal then return non zero value else return 0.
Syntax:- int pthread_equal (pthread_t t1, pthread_t t2);
 
First Method :- Compare with self thread
// C program to demonstrate working of pthread_equal()#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <pthread.h>  pthread_t tmp_thread;  void* func_one(void* ptr){    // in this field we can compare two thread    // pthread_self gives a current thread id    if (pthread_equal(tmp_thread, pthread_self())) {        printf("equal\n");    } else {        printf("not equal\n");    }}  // driver codeint main(){    // thread one    pthread_t thread_one;      // assign the id of thread one in temporary    // thread which is global declared   r    tmp_thread = thread_one;      // create a thread    pthread_create(&thread_one, NULL, func_one, NULL);      // wait for thread    pthread_join(thread_one, NULL);}
Output:
equal

 
Second Method :- Compare with other thread
// C program to demonstrate working of pthread_equal()#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <pthread.h>  // global declared pthread_t variablepthread_t tmp_thread;  void* func_one(void* ptr){    tmp_thread = pthread_self(); // assign the id of thread one in    // temporary thread which is global declared}  void* func_two(void* ptr){    pthread_t thread_two = pthread_self();      // compare two thread    if (pthread_equal(tmp_thread, thread_two)) {        printf("equal\n");    } else {        printf("not equal\n");    }}  int main(){    pthread_t thread_one, thread_two;      // creating thread one    pthread_create(&thread_one, NULL, func_one, NULL);      // creating thread two    pthread_create(&thread_two, NULL, func_two, NULL);      // wait for thread one    pthread_join(thread_one, NULL);      // wait for thread two    pthread_join(thread_two, NULL);}
Output:
not equal

This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nidhi_biet
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
fork() in C
rand() and srand() in C/C++
Substring in C++
Converting Strings to Numbers in C/C++
std::string class in C++
Enumeration (or enum) in C
How to map array values without using map method in JavaScript ? - GeeksforGeeks

06 Dec, 2021
Array elements can be mapped by using looping methods in JavaScript. The map() method creates a new array with the results of the output of a function called for each element of the array. This can also be implemented using for loop in JavaScript.
Approach: For this, we can create two arrays, in which one array contains the array elements that are to be mapped, and the second array stores all the return values of the corresponding function.  We can use the JavaScript Array push() method to push the return values of the function in the output array.
Syntax:
array.push(element1, element2, element, ... , elementN )
The Array length method can be used to find the length of the corresponding array.
Syntax:
array.length
Return value: Number
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>        JavaScript mapping using loops    </title></head>  <body>    <script>        var arr = [4, 5, 10, 3, 8, 6];        var result = [];        let i;          //square function returns square of a number        const square = function(num){              return num*num;        }          for(i=0; i< arr.length; i++){            result.push(square(arr[i]));        }          console.log(result);        //Expected output: [16 ,25, 100, 9, 64, 36]      </script></body>  </html>
Output: The indices of the elements in the output array are shown before the numbers in the output as well as the length of the output array.
[16, 25, 100, 9, 64, 36]
0: 16
1: 25
2: 100
3: 9
4: 64
5: 36
length: 6
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Output of the program | Dereference, Reference, Dereference, Reference.... - GeeksforGeeks

09 Aug, 2018
Predict the output of below program
#include<stdio.h>int main(){ char *ptr = "geeksforgeeks"; printf("%c\n", *&*&*ptr);    getchar(); return 0;}
Output: g
Explanation: The operator * is used for dereferencing and the operator & is used to get the address. These operators cancel effect of each other when used one after another. We can apply them alternatively any no. of times. For example *ptr gives us g, &*ptr gives address of g, *&*ptr again g, &*&*ptr address of g, and finally *&*&*ptr gives ‘g’
Now try below
#include<stdio.h>int main(){ char *ptr = "geeksforgeeks"; printf("%s\n", *&*&ptr);    getchar(); return 0;}
MOHAKGOEL
C-Output
C-Pointers
C Language
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Arrow operator -> in C/C++ with Examples
delete keyword in C++
Output of C Programs | Set 1
Different ways to copy a string in C/C++
Output of Java Program | Set 1