code-rag-bench/online-tutorials huggingface dataset:
unordered_map hash_function() function in C++ STL - GeeksforGeeks

17 Dec, 2018
The unordered_map::hash_function() is a built in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it.
Syntax:
unordered_map_name.hash_function()

Parameter: The function does not accept any parameter.
Return Value: The function returns the hash function.
Time complexity: Time Complexity of this function is constant O(1).
Below programs illustrate the unordered_map::hash_function() function.
Example 1
// C++ program to illustrate the// unordered_map::hash_function()  #include <bits/stdc++.h>using namespace std;  int main(){      // declaration    unordered_map<string, string> sample;      // inserts key and elements    sample.insert({ "Ankit", "MNNIT" });    sample.insert({ "Ram", "MNNIT" });    sample.insert({ "Manoj", "Trichy" });    sample.insert({ "geeks", "geeks" });      // use of hash_function    unordered_map<string, string>::hasher fn        = sample.hash_function();      cout << fn("geeks") << endl;      // print the key and elements      cout << "Key and Elements: ";    for (auto it = sample.begin(); it != sample.end(); it++) {        cout << "\n{" << it->first << ":"             << it->second << "}, ";    }    return 0;}
15276750567035005396
Key and Elements: 
{geeks:geeks}, 
{Manoj:Trichy}, 
{Ankit:MNNIT}, 
{Ram:MNNIT},

Example 2
// C++ program to illustrate the// unordered_map::hash_function()  #include <bits/stdc++.h>using namespace std;  int main(){      // declaration    unordered_map<int, int> sample;      // inserts key and elements    sample.insert({ 1, 5 });    sample.insert({ 2, 6 });    sample.insert({ 3, 6 });    sample.insert({ 4, 7 });      // use of hash_function    unordered_map<int, int>::hasher fn        = sample.hash_function();      cout << fn(4) << endl;      // print the key and elements      cout << "Key and Elements: ";    for (auto it = sample.begin(); it != sample.end(); it++) {        cout << "\n{" << it->first << ":"             << it->second << "}, ";    }    return 0;}
4
Key and Elements: 
{4:7}, 
{3:6}, 
{1:5}, 
{2:6},

cpp-unordered_map
cpp-unordered_map-functions
C++
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Convert string to char array in C++
Inline Functions in C++
List in C++ Standard Template Library (STL)
new and delete operators in C++ for dynamic memory
std::string class in C++
Find the first repeated word in a string in Python using Dictionary

In a given sentence there may be a word which get repeated before the sentence ends. In this python program, we are going to catch such word which is repeated in sentence. Below is the logical steps we are going to follow to get this result.
Splits the given string into words separated by space.
Then we convert these words into Dictionary using collections
Traverse this list of words and check which first word has the frequency > 1
In the below program we use the counter method from the collections package to keep a count of the words.
 Live Demo
from collections import Counter
def Repeat_word(load):
   word = load.split(' ')
   dict = Counter(word)
   for value in word:
      if dict[value]>1:
         print (value)
            return
if __name__ == "__main__":
   input = 'In good time in bad time friends are friends'
   Repeat_word(input)
Running the above code gives us the following result −
time
Vue.js v-on:keyup Directive

08 Jul, 2020
The v-on:keyup directive is a Vue.js directive used to add an event listener to an button in the keyboard. First, we will create a div element with id as app and let’s apply the v-on:keyup directive to the input element. Further, we can execute a function when we press the associated key.
Syntax:
v-on:keyup="function"
Supported Keys: Following keys are supported:
Enter key: .enter
Tab key: .tab
Delete key: .delete
Esc key: .esc
Up key: .up
Down key: .down
Left key: .left
Right key: .right
Parameters: This directive holds function as a value that will be executed when the key event occurs.Example: This example uses VueJS to toggle the visibility of a element with v-on:keyup using Enter key.
HTML
<!DOCTYPE html><html>  <head>    <title>        VueJS v-on:keyup Directive    </title>      <!-- Load Vuejs -->    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">    </script></head>  <body>    <div style="text-align: center;                width: 600px;">        <h1 style="color: green;">            GeeksforGeeks        </h1>        <b>            VueJS | v-on:keyup directive        </b>    </div>      <div id="canvas" style=            "border:1px solid #000000;            width: 600px;height: 200px;">          <div id="app" style=            "text-align: center;             padding-top: 40px;">            Write anything and press enter              <input v-on:keyup.enter=                "data = !data">            </input>                          <h1 v-if="data">GeeksforGeeks</h1>        </div>    </div>      <script>        var app = new Vue({            el: '#app',            data: {                data: false            }        })    </script></body>  </html>                   
Output:
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Worst-Fit Allocation in Operating Systems

03 Feb, 2021
For both fixed and dynamic memory allocation schemes, the operating system must keep a list of each memory location noting which are free and which are busy. Then as new jobs come into the system, the free partitions must be allocated. 
These partitions may be allocated in 4 ways: 
1. First-Fit Memory Allocation
2. Best-Fit Memory Allocation
3. Worst-Fit Memory Allocation
4. Next-Fit Memory Allocation 
These are Contiguous memory allocation techniques. 
Worst-Fit Memory Allocation : In this allocation technique, the process traverses the whole memory and always search for the largest hole/partition, and then the process is placed in that hole/partition. It is a slow process because it has to traverse the entire memory to search the largest hole. 
Here is an example to understand Worst Fit-Allocation – 
Here Process P1=30K is allocated with the Worst Fit-Allocation technique, so it traverses the entire memory and selects memory size 400K which is the largest, and hence there is an internal fragmentation of 370K which is very large and so many other processes can also utilize this leftover space. 
Advantages of Worst-Fit Allocation : Since this process chooses the largest hole/partition, therefore there will be large internal fragmentation. Now, this internal fragmentation will be quite big so that other small processes can also be placed in that leftover partition. 
Disadvantages of Worst-Fit Allocation : It is a slow process because it traverses all the partitions in the memory and then selects the largest partition among all the partitions, which is a time-consuming process. 
aman singh 34
soumalimukhopadhyay
memory-management
Operating Systems-Memory Management
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack contains() method in Java with Example

24 Dec, 2018
The java.util.Stack.contains() method is used to check whether a specific element is present in the Stack or not. So basically it is used to check if a Stack contains any particular element or not.
Syntax:
Stack.contains(Object element)
Parameters: This method takes a mandatory parameter element which is of the type of Stack. This is the element that needs to be tested if it is present in the Stack or not.
Return Value: This method returns True if the element is present in the Stack otherwise it returns False.
Below programs illustrate the Java.util.Stack.contains() method:
Program 1:
// Java code to illustrate contains()import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Use add() method to add elements into the Stack        stack.add("Welcome");        stack.add("To");        stack.add("Geeks");        stack.add("4");        stack.add("Geeks");          // Displaying the Stack        System.out.println("Stack: " + stack);          // Check for "Geeks" in the Stack        System.out.println("Does the Stack contains 'Geeks'? "                           + stack.contains("Geeks"));          // Check for "4" in the Stack        System.out.println("Does the Stack contains '4'? "                           + stack.contains("4"));          // Check if the Queue contains "No"        System.out.println("Does the Stack contains 'No'? "                           + stack.contains("No"));    }}
Stack: [Welcome, To, Geeks, 4, Geeks]
Does the Stack contains 'Geeks'? true
Does the Stack contains '4'? true
Does the Stack contains 'No'? false

Program 2:
// Java code to illustrate contains()import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<Integer> stack = new Stack<Integer>();          // Use add() method to add elements into the Stack        stack.add(10);        stack.add(15);        stack.add(30);        stack.add(20);        stack.add(5);          // Displaying the Stack        System.out.println("Stack: " + stack);          // Check for "Geeks" in the Stack        System.out.println("Does the Stack contains 'Geeks'? "                           + stack.contains("Geeks"));          // Check for "4" in the Stack        System.out.println("Does the Stack contains '4'? "                           + stack.contains("4"));          // Check if the Stack contains "No"        System.out.println("Does the Stack contains 'No'? "                           + stack.contains("No"));    }}
Stack: [10, 15, 30, 20, 5]
Does the Stack contains 'Geeks'? false
Does the Stack contains '4'? false
Does the Stack contains 'No'? false

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | pop() function

06 May, 2019
The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements.
Syntax: pop(Elements)
Parameters:Elements : This is the number of elements which are to be removed from the end of the given array. If this parameter is not used then it removes and returns the single last element of the given array.
Returns: the removed elements.
Example 1:
# Initializing some arrays of elementsArray = [1, 2, 3, 4, 5, 6, 7]  # Calling pop() functionA = Array.pop B = Array.pop(2)C = Array.pop(3)D = Array  # Printing the removed elements puts "#{A}"puts "#{B}"puts "#{C}"  # Printing the remaining arrayputs "#{D}"
Output:
7
[5, 6]
[2, 3, 4]
[1]
Example 2:
# Initializing some arrays of elementsArray = ["a", "b", "c", "d", "e", "f", "g"]  # Calling pop() functionA = Array.pop B = Array.pop(1)C = Array.pop(2)D = Array.pop(3)E = Array  # Printing the removed elements puts "#{A}"puts "#{B}"puts "#{C}"puts "#{D}"  # Printing the remaining arrayputs "#{E}"
Output:
g
["f"]
["d", "e"]
["a", "b", "c"]
[]

Reference: https://devdocs.io/ruby~2.5/array#method-i-pop
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib – Textbox Widgets

17 Feb, 2022
In this article, we are going to see matplotlib’s textbox widget. Matplotlib is a plotting library for the Python programming language. In this article, we will try to plot a graph for different powers(e.g. t^2, t^3, t^9, etc.) using textbox widget.
The Textbox is a widget that accepts input from the user. Input can also be formulas so that we can generate a graph based on those formulas. To use this widget we use TextBox() function. 
It accepts two parameters
Figure i.e. graph to use.
Text to display with textbox i.e. Label to textBox.
Below is the implementation of this widget:
Python
# Import modulesimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox # Adjust illustrationfig, ax = plt.subplots()fig.subplots_adjust(bottom=0.2) t = np.arange(-4.0, 4.0, 0.01)l, = ax.plot(t, np.zeros_like(t), lw=2) # Function to plot graph# according to expressiondef visualizeGraph(expr):    ydata = eval(expr)    l.set_ydata(ydata)    ax.relim()    ax.autoscale_view()    plt.draw() # Adding TextBox to graphgraphBox = fig.add_axes([0.1, 0.05, 0.8, 0.075])txtBox = TextBox(graphBox, "Plot: ")txtBox.on_submit(visualizeGraph)txtBox.set_val("t**5") # Plot graphplt.show()
Output:
Explanation:
In the above program, we created a graph for t2 as by default graph. In txtBox labelled as Plot: we can enter the formula we want to view the graph for. 
varshagumber28
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashSet toString() method in Java with Example

24 Dec, 2018
The toString() method of Java HashSet is used to return a string representation of the elements of the Collection.
The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation.
Syntax:
public String toString()
Parameter The method does not take any parameters.
Return This method returns a String representation of the collection.
Below examples illustrate the toString() method:
Example 1:
// Java program to demonstrate// HashSet toString() method  import java.util.*;  public class collection {    public static void main(String args[])    {        // Creating an Empty HashSet        HashSet<String> abs            = new HashSet<String>();          // Use add() method        // to add elements to the Collection        abs.add("Welcome");        abs.add("To");        abs.add("Geeks");        abs.add("For");        abs.add("Geeks");          // Using toString() method        System.out.println(abs.toString());    }}
[Geeks, For, Welcome, To]

Example 2:
// Java program to demonstrate// HashSet toString() method  import java.util.*;  public class collection {    public static void main(String args[])    {        // Creating an Empty HashSet        HashSet<Integer> abs            = new HashSet<Integer>();          // Use add() method        // to add elements to the Collection        abs.add(10);        abs.add(20);        abs.add(30);        abs.add(40);          // Using toString() method        System.out.println(abs.toString());    }}
[20, 40, 10, 30]

Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.pyplot.subplots_adjust() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The subplots_adjust() function in pyplot module of matplotlib library is used to tune the subplot layout.
Syntax: matplotlib.pyplot.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
Parameters: This method accept the following parameters that are described below:
left : This parameter is the left side of the subplots of the figure.
right : This parameter is the right side of the subplots of the figure.
bottom : This parameter is the bottom of the subplots of the figure.
top : This parameter is the top of the subplots of the figure.
wspace : This parameter is the amount of width reserved for space between subplots expressed as a fraction of the average axis width.
hspace : This parameter is the amount of height reserved for space between subplots expressed as a fraction of the average axis height.
Below examples illustrate the matplotlib.pyplot.subplots_adjust() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt     x = [1, 12, 3, 9]y = [1, 4, 9, 16]labels = ['Geeks1', 'Geeks2', 'Geeks3', 'Geeks4']   plt.plot(x, y)plt.xticks(x, labels, rotation ='vertical')  plt.margins(0.2)plt.subplots_adjust(bottom = 0.15)  plt.title('matplotlib.pyplot.subplots_adjust() Example')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox    fig, ax = plt.subplots()plt.subplots_adjust(bottom = 0.2)t = np.arange(-2.0, 2.0, 0.001)s = np.sin(t)+np.cos(2 * t)initial_text = "sin(t) + cos(2t)"l, = plt.plot(t, s, lw = 2)  def submit(text):          ydata = eval(text)    l.set_ydata(ydata)    ax.set_ylim(np.min(ydata), np.max(ydata))    plt.draw()  axbox = plt.axes([0.4, 0.05, 0.3, 0.075])text_box = TextBox(axbox, 'Formula Used : ',                    initial = initial_text)  text_box.on_submit(submit)  fig.suptitle('matplotlib.pyplot.subplots_adjust() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Convert integer to string in Python
How to compute the eigenvalues and right eigenvectors of a given square array using NumPY?

02 Sep, 2020
In this article, we will discuss how to compute the eigenvalues and right eigenvectors of a given square array using NumPy library. 
Example:
Suppose we have a matrix as: 
[[1,2],
[2,3]] 

Eigenvalue we get from this matrix or square array is: 
[-0.23606798 4.23606798]

Eigenvectors of this matrix are: 
[[-0.85065081 -0.52573111], 
[ 0.52573111 -0.85065081]] 
To know how they are calculated mathematically see this Calculation of EigenValues and EigenVectors. In the below examples, we have used numpy.linalg.eig() to find eigenvalues and eigenvectors for the given square array. 
Syntax: numpy.linalg.eig()
Parameter: An square array.
Return: It will return two values first is eigenvalues and second is eigenvectors.
Example 1:
Python3
# importing numpy libraryimport numpy as np  # create numpy 2d-arraym = np.array([[1, 2],              [2, 3]])  print("Printing the Original square array:\n",      m)  # finding eigenvalues and eigenvectorsw, v = np.linalg.eig(m)  # printing eigen valuesprint("Printing the Eigen values of the given square array:\n",      w)  # printing eigen vectorsprint("Printing Right eigenvectors of the given square array:\n"      v)
Output:
Printing the Original square array:
 [[1 2]
 [2 3]]
Printing the Eigen values of the given square array:
 [-0.23606798  4.23606798]
Printing Right eigenvectors of the given square array:
 [[-0.85065081 -0.52573111]
 [ 0.52573111 -0.85065081]]
Example 2:
Python3
# importing numpy libraryimport numpy as np  # create numpy 2d-arraym = np.array([[1, 2, 3],              [2, 3, 4],              [4, 5, 6]])  print("Printing the Original square array:\n",      m)  # finding eigenvalues and eigenvectorsw, v = np.linalg.eig(m)  # printing eigen valuesprint("Printing the Eigen values of the given square array:\n",      w)  # printing eigen vectorsprint("Printing Right eigenvectors of the given square array:\n",      v)
Output:
Printing the Original square array:
 [[1 2 3]
 [2 3 4]
 [4 5 6]]
Printing the Eigen values of the given square array:
 [ 1.08309519e+01 -8.30951895e-01  1.01486082e-16]
Printing Right eigenvectors of the given square array:
 [[ 0.34416959  0.72770285  0.40824829]
 [ 0.49532111  0.27580256 -0.81649658]
 [ 0.79762415 -0.62799801  0.40824829]]
Python numpy-Linear Algebra
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Azure – Starting & Stopping a Azure Kubernetes Service Cluster

01 Jun, 2021
In this article, we will learn how to stop and start Azure Kubernetes Service(AKS) clusters. You can stop your entire Azure Kubernetes Service cluster to save costs. To follow along, you will need an existing Azure Kubernetes service that is running. 
To use start and stop for AKS, we need the AKS preview extension for the Azure CLI.  It can be installed using the below command:
extension add --name aks-preview
Let’s make sure that we have the latest version of that using the below command:
az extension update --name aks-preview
Next, we need to register the start/stop preview feature using the below command:
az feature register --namespace "Microsoft.ContainereService" --name "StartStopPreview"
 This can take a while. After a couple of minutes, check if the feature is registered with the below command:
az feature list -o table --query 
    "[?contains(name,'Microsoft.ContainereService/StartStopPreview')].{Name:name,
    State:properties.state}"
Now we need to refresh the container resource provider using the below command:
az provider register --namespace Microsoft.ContainerService
That’s all the preview stuff out of the way. Now, it could be that you don’t need to do all of this when this feature is generally available.
Let’s stop our AKS cluster with the below command:
az aks stop --name YOUR_CLUSTE_NAME --resource-group YOUR_RESOURCE_GROUP
It’s as simple as that. This will result in something like below if we use the below command:
az aks show
The power state is stopped, so the cluster is stopped.
We can just as easily start it up again using the below command:
az aks start --name YOUR_CLUSTE_NAME --resource-group YOUR_RESOURCE_GROUP
We’ll use AKS show to check if it is running as shown below:
Stopping an Azure Kubernetes Service cluster is a great way to save money. You can easily start and stop AKS with an Azure CLI command, which you can, for instance, automate to stop when this surface isn’t used and start during business hours. 
azure-cloud-instances
azure-kubernetes-services
Cloud-Computing
Microsoft Azure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Azure - KQL Query to Get the VM Computer Properties
Microsoft Azure - Resource Tagging and Best Practices
Microsoft Azure - Mount Azure Storage in Container App In App Service
Microsoft Azure - Choosing a Partition Key in Cosmos DB
Microsoft Azure - Map a Network File Share to Azure Windows VM
How Microsoft Azure Works?
Microsoft Azure - Query System Event Log Data Using Azure KQL
Microsoft Azure - Deletion of Snapshots using PowerShell Script
Microsoft Azure - Azure Firewall Flow Logs From Select Source IP
Microsoft Azure - Cloning Web Apps using Azure App Services
How to Convert Array to Set in JavaScript?

31 Jul, 2019
The task is to convert a JavaScript Array to a Set with the help of JavaScript. we’re going to discuss few techniques.
Approach:
Take the JavaScript array into a variable.
Use the new keyword to create a new set and pass the JavaScript array as it first and only argument.
This will automatically create the set of the provided array.
Example 1: In this example, the array is converted into set using the same approach defined above.
<!DOCTYPE HTML><html>  <head>    <title>        JavaScript       | Convert Array to Set.    </title></head>  <body style="text-align:center;"      id="body">    <h1 style="color:green;"         id="h1">              GeeksForGeeks          </h1>    <p id="GFG_UP"        style="font-size: 15px;               font-weight: bold;">    </p>    <button onclick="GFG_Fun()">        click here    </button>    <p id="GFG_DOWN"        style="color:green;               font-size: 20px;              font-weight: bold;">    </p>    <script>        var up = document.getElementById('GFG_UP');        var down = document.getElementById('GFG_DOWN');        var A = [1, 1, 2, 2, 2, 2, 5, 5];                up.innerHTML = "Click on the button to convert"+          " the array to set.<br>" + "Array - [" + A + "]";          function GFG_Fun() {            var set = new Set(A);            down.innerHTML = JSON.stringify([...set]);        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: In this example, the array is converted into set using a bit approach than above.
<!DOCTYPE HTML><html>  <head>    <title>        JavaScript       | Convert Array to Set.    </title></head>  <body style="text-align:center;" id="body">    <h1 style="color:green;" id="h1">              GeeksForGeeks          </h1>    <p id="GFG_UP"        style="font-size: 15px;               font-weight: bold;">    </p>    <button onclick="GFG_Fun()">        click here    </button>    <p id="GFG_DOWN"        style="color:green;               font-size: 20px;               font-weight: bold;">    </p>    <script>        var up = document.getElementById('GFG_UP');        var down = document.getElementById('GFG_DOWN');                var A = ["A", "A", "Computer Science", "portal",                  "for", "for", "Geeks", "Geeks"];                up.innerHTML = "Click on the button to convert "+          "the array to set.<br>" + "Array - [" + A + "]";          function GFG_Fun() {            var set = new Set(A);            down.innerHTML = JSON.stringify([...set.keys()]);        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What does the repr() function do in Python Object Oriented Programming?

The official Python documentation says __repr__() is used to compute the “official” string representation of an object. The repr() built-in function uses __repr__() to display the object. __repr__()  returns a printable representation of the object, one of the ways possible to create this object.  __repr__() is more useful for developers while __str__() is for end users.
The following code shows how __repr__() is used.
class Point:

   def __init__(self, x, y):

     self.x, self.y = x, y

   def __repr__(self):

     return 'Point(x=%s, y=%s)' % (self.x, self.y)

p = Point(3, 4)

print p
This gives the output
Point(x=3, y=4)
Lets consider another example of use of repr() function and create a datetime object −
>>> import datetime
>>> today = datetime.datetime.now()
When I use the built-in function repr() to display today −
>>> repr(today)
'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'
We can see that this returned a string but this string is the “official” representation of a datetime object which means that using this “official” string representation we can reconstruct the object −
>>> eval('datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)')
datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)
The eval() built-in function accepts a string and converts it to a datetime object.
Change the ratio between width and height of an image using Python - Pillow - GeeksforGeeks

23 Dec, 2020
Python Imaging Library (expansion of PIL) is the de facto image processing package for the Python language. It incorporates lightweight image processing tools that aid in editing, creating, and saving images. This module is not preloaded with Python. So to install it execute the following command in the command-line:
pip install pillow
To change the ratio of height and width we will add or subtract any random value from them.
Image.open(fp, mode=’r’) method: This method is used to open the image.
Image.resize(size, resample=0) method: This method is used to resize the image. Interpolation happens during the resize process, due to which the quality of image changes whether it is being upscaled (resized to a higher dimension than original) or downscaled (resized to a lower Image then original).
We will first take an image.
Then we will find its height and width.
Then we will add and subtract any random number from them to change the ratio.
Then we will save the image.
Example:
Image Used:
Python3
# Python program to change the ratio of height and# width of an image from PIL import Image  # Taking image as inputimg = Image.open('logo.png')  # Getting height and width of the imageheight = img.size[0]width = img.size[1]  # Printing ratio before conversionprint('Ratio before conversion:', width/height)  # Changing the height and width of the imagewidth = width + 25height = height - 25  # Resizing the imageimg = img.resize((width ,height), Image.ANTIALIAS)  # Printing the ratio after conversionprint('Ratio after conversion:', width/height)  # Saving the resized imageimg.save('Resized Image.png')
Output:
Ratio before conversion: 1.0
Ratio after conversion: 1.25
Output Image:
Picked
Python-pil
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Normal Probability Plot in R using ggplot2 - GeeksforGeeks

14 Jan, 2022

A normal probability plot is a graphical representation of the data. A normal probability plot is used to check if the given data set is normally distributed or not. It is used to compare a data set with the normal distribution. If a given data set is normally distributed then it will reside in a shape like a straight line.
In this article, we are going to use ggplot2 with qqplotr to plot and check if the dataset is normally distributed using qqplot only.
Install the following necessary libraries by pasting them in r console
install.packages(“ggplot2”)
install.packages(“qqplotr”)
Create a random data set with a different mean and standard deviation that you want to plot.
Plotting data using stat_qq_point() method.
Plotting data points with line using stat_qq_line() function.
Given below is a proper implementation using the above approach 
Example 1: Plotting data using stat_qq_point() method.
R
 

 
 










# importing libraries
library(ggplot2)
library(qqplotr)
 
# creating random data
random_values = rnorm(500, mean = 90, sd = 50)
 
# plotting data without line and labels
ggplot(mapping = aes(sample = random_values)) + stat_qq_point(size = 2)






Output:
Fig. 1 Plotting Data points.
Example 2: Plotting data points with line using stat_qq_line() function.
R
 

 
 










# importing libraries
library(ggplot2)
library(qqplotr)
 
# creating random data
random_values = rnorm(500, mean = 90, sd = 50)
 
# plotting data with proper labels 
# And adding line with proper properties
ggplot(mapping = aes(sample = random_values)) 
+ stat_qq_point(size = 2,color = "red") 
+ stat_qq_line(color="green") 
+ xlab("x-axis") + ylab("y-axis")






Output:
Fig. 2 Adding normal line
adnanirshad158

Picked


R-Charts


R-Graphs


R-plots


R Language

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
R - if statement
How to randomize and shuffle array of numbers in Java?

At first, create an integer array −
int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200};
Now, create a Random class object −
Random rand = new Random();
Loop until the length of the array and shuffle the elements −
for (int i = 0; i < arr.length; ++i) {
   int index = rand.nextInt(arr.length - i);
   int tmp = arr[arr.length - 1 - i];
   arr[arr.length - 1 - i] = arr[index];
   arr[index] = tmp;
}
 Live Demo
import java.util.Arrays;
import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200};
      System.out.println("The integer array = "+Arrays.toString(arr));
      Random rand = new Random();
      for(int i = 0; i < arr.length; ++i) {
         int index = rand.nextInt(arr.length - i);
         int tmp = arr[arr.length - 1 - i];
         arr[arr.length - 1 - i] = arr[index];
         arr[index] = tmp;
      }
      System.out.println("Shuffle integer array = "+Arrays.toString(arr));
   }
}
The integer array = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
Shuffle integer array = [160, 100, 20, 60, 140, 200, 120, 40, 80, 180]
MySQL WHERE Clause

The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified 
condition.
Note: The WHERE clause is not only used in 
SELECT statements, it is also used in UPDATE,
DELETE, etc.!
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement selects all the customers from  
"Mexico":
SQL requires single quotes around text values (most database systems will 
also allow double quotes).
However, numeric fields should not be enclosed in quotes:
The following operators can be used in the WHERE clause:
Select all records where the City column has the value "Berlin".
SELECT * FROM Customers
  = ;

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 list all users in the Mongo shell?

In order to list all users in the Mongo shell, use the getUsers() method or show command.
Case 1 − Using getUsers()
The syntax is as follows −
db.getUsers();
Case 2 − Using show command
The syntax is as follows −
show users;
Let us implement both the syntaxes in order to list all users in the Mongo shell.
Case 1 − The first query is as follows −
> db.getUsers();
The following is the output −
[
   {
      "_id" : "test.John",
      "user" : "John",
      "db" : "test",
      "roles" : [
         {
            "role" : "readWrite",
            "db" : "test"
         },
         {
            "role" : "dbAdmin",
            "db" : "test"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-1",
         "SCRAM-SHA-256"
      ]
   },
   {
      "_id" : "test.admin",
      "user" : "admin",
      "db" : "test",
      "roles" : [
         {
            "role" : "root",
            "db" : "admin"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-1",
         "SCRAM-SHA-256"
      ]
   }
]
Case 2 − The second query is as follows −
> show users;
The following is the output −
{
   "_id" : "test.John",
   "user" : "John",
   "db" : "test",
   "roles" : [
      {
         "role" : "readWrite",
         "db" : "test"
      },
      {
         "role" : "dbAdmin",
         "db" : "test"
      }
   ],
   "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
   ]
}
{
   "_id" : "test.admin",
   "user" : "admin",
   "db" : "test",
   "roles" : [
      {
         "role" : "root",
         "db" : "admin"
      }
   ],
   "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
   ]
}
VBScript Debug Objects

The Debug Objects are global objects that can send output to a script debugger. Here, the debugger what we refer to is Microsoft Script Debugger.
The Debug objects cannot be created like other objects but can be used when we are debugging.
The following methods are supported by Debug Objects. These methods or objects have no effect if the script is NOT executed in debug mode. The Methods supported by Debug Objects are discussed in detail.
The Write method sends strings to the immediate window of the Microsoft Script Debugger at run-time. If the script is not executed in debug mode, then the Write method has no effect.
Write Debug.Write([str1 [, str2 [, ... [, strN]]]])

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim counter
         counter = 42
         Debug.Write "The value of counter is " & counter
       
      </script>
   </body>
</html>
The Writeline method is very similar to Write method. The WriteLine method sends strings, followed by a newline character, to the immediate window of the Microsoft Script Debugger at run time. If the script is not executed in debug mode, then the WriteLine method has no effect.
Debug.WriteLine([str1 [, str2 [, ... [, strN]]]])

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim counter
         counter = 42
         Debug.WriteLine "The value of counter is " & counter
       
      </script>
   </body>
</html>
To enable script in debug mode, following actions to be performed by the user −
On the Tools menu, click Internet Options.
On the Tools menu, click Internet Options.
In the Internet Options dialog box, click the Advanced tab.
In the Internet Options dialog box, click the Advanced tab.
In the Browsing category, clear the Disable script debugging check box.
In the Browsing category, clear the Disable script debugging check box.
Click OK.
Click OK.
Exit and restart Internet Explorer.
Exit and restart Internet Explorer.

    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Map size() Method in Java With Examples

05 Sep, 2020
Map size() method in Java is used to get the total number entries i.e, key-value pair. So this method is useful when you want total entries present on the map. If the map contains more than Integer.MAX_VALUE elements return Integer.MAX_VALUE.
Syntax:
int size();
Parameter: This method does not take any parameter.
Return value: This method returns the number of key-value mappings in this map.
Example 1: For non-generic input
Java
// Java program to illustrate// the Map size() Methodimport java.util.*;  public class MapSizeExample {          // Main Method    public static void main(String[] args)    {        Map map = new HashMap();                  // Adding key-values        map.put(1, "Amit");        map.put(5, "Rahul");        map.put(2, "Jai");        map.put(6, "Amit");                  // using the method        System.out.println("Size of the map is : "                           + map.size());    }}
Output:
Size of the map is : 4
Example 2: For Generic Input
Java
// Java program to illustrate// the Map size() Methodimport java.util.*;  class MapSizeExample {      // Main Method    public static void main(String[] args)    {          Map<Integer, String> map            = new HashMap<Integer, String>();          map.put(1, "one");        map.put(2, "two");        map.put(3, "three");        map.put(4, "four");                    // using the method        System.out.println("Size of map is :"                           + map.size());    }}
Output:
Size of the map is : 4
Java-Collections
java-map
Java-Map-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert String to Tuple

21 Nov, 2019
Interconversion of data types is very common problem one can face while programming. There can be a problem in which we need to convert a string of integers to a tuple. Let’s discuss certain ways in which this can be done.
Method #1 : Using map() + int + split() + tuple()This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple.
# Python3 code to demonstrate working of# Convert String to Tuple# using map() + tuple() + int + split()  # initialize stringtest_str = "1, -5, 4, 6, 7"  # printing original string print("The original string : " + str(test_str))  # Convert String to Tuple# using map() + tuple() + int + split()res = tuple(map(int, test_str.split(', ')))  # printing resultprint("Tuple after getting conversion from String : " + str(res))
The original string : 1, -5, 4, 6, 7
Tuple after getting conversion from String : (1, -5, 4, 6, 7)

 
Method #2 : Using eval()This is the shorthand to perform this task. This converts the string to desired tuple internally.
# Python3 code to demonstrate working of# Convert String to Tuple# Using eval()  # initialize stringtest_str = "1, -5, 4, 6, 7"  # printing original string print("The original string : " + str(test_str))  # Convert String to Tuple# Using eval()res = eval(test_str)  # printing resultprint("Tuple after getting conversion from String : " + str(res))
The original string : 1, -5, 4, 6, 7
Tuple after getting conversion from String : (1, -5, 4, 6, 7)

Python string-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of C programs | Set 44 (Structure & Union)

14 Oct, 2020
Prerequisite: Structure and UnionQUE.1 What is the output of this program? 
C
#include <stdio.h>struct sample {    int a = 0;    char b = 'A';    float c = 10.5;};int main(){    struct sample s;    printf("%d, %c, %f", s.a, s.b, s.c);    return 0;}
OPTION a) Error b) 0, A, 10.5 c) 0, A, 10.500000 d) No Error, No Output 
Answer: a

Explanation: Error: Can not initialize members here. We can only declare members inside the structure, initialization of member with declaration is not allowed in structure declaration.QUE.2 What is the output of this program? 
C
#include <stdio.h>int main(){    struct bitfield {        signed int a : 3;        unsigned int b : 13;        unsigned int c : 1;    };    struct bitfield bit1 = { 2, 14, 1 };    printf("%ld", sizeof(bit1));    return 0;}
OPTION a) 4 b) 6 c) 8 d) 12 
Answer:  a

Explanation: struct bitfield bit1={2, 14, 1}; when we initialize it it will take only one value the will be int and size of int is 4QUE. 3 What is the output of this program? 
C
#include <stdio.h>int main(){    typedef struct tag {        char str[10];        int a;    } har;     har h1, h2 = { "IHelp", 10 };    h1 = h2;    h1.str[1] = 'h';    printf("%s, %d", h1.str, h1.a);    return 0;}
OPTION a) ERROR b) IHelp, 10 c) IHelp, 0 d) Ihelp, 10 
Answer : d

Explanation : It is possible to copy one structure variable into another like h1 = h2. Hence value of h2. str is assigned to h1.str.QUE.4 What is the output? 
C
#include <stdio.h> struct sample {    int a;} sample; int main(){    sample.a = 100;    printf("%d", sample.a);    return 0;}
OPTION a) 0 b) 100 c) ERROR d) Warning Answer 
Answer : b

Explanation : This type of declaration is allowed in c.QUE.5 what is output of this program? 
C
#include <stdio.h>int main(){    union test {        int i;        int j;    };     union test var = 10;    printf("%d, %d\n", var.i, var.j);}
OPTION a) 10, 10 b) 10, 0 c) 0, 10 d) Compile Error
Answer : d

Explanation : Error: Invalid Initialization. You cannot initialize an union variable like this.Next Quiz onStructure and UnionThis article is contributed by Ajay Puri(ajay0007). 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.
BhagyaRana
C-Output
C-Structure & Union
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | time.clock() method

27 Sep, 2019
Time module in Python provides various time related functions.
time.clock() method of time module in Python is used to get the current processor time as a floating point number expressed in seconds.As, Most of the functions defined in time module call corresponding C library function. time.clock() method also call C library function of the same name to get the result. The precision of returned float value depends on the called C library function.
Note: This method is deprecated since Python version 3.3 and will be removed in Python version 3.8. The behaviour of this method is platform dependent.
Syntax: time.clock()
Parameter: No parameter is required.
Return type: This method returns a float value which represents the current processor time in seconds.
Code #1: Use of time.clock() method to get current processor time
# Python program to explain time.clock() method  # importing time moduleimport time  # Get the current processor# time in secondspro_time = time.clock()  # print the current # processor timeprint("Current processor time (in seconds):", pro_time)
Current processor time (in seconds): 0.042379

Code #2: Use of time.clock() method to get current processor time
# Python program to explain time.clock() method   # importing time module import time     # Function to calculate factorial # of the given number def factorial(n):     f = 1    for i in range(n, 1, -1):         f = f * i           return f     # Get the current processor time# in seconds at the # beginning of the calculation # using time.clock() method start = time.clock()   # print the processor time in seconds print("At the beginning of the calculation") print("Processor time (in seconds):", start, "\n")     # Calculate factorial of all # numbers form 0 to 9 i = 0fact = [0] * 10;   while i < 10:     fact[i] = factorial(i)     i = i + 1  # Print the calculated factorial for i in range(0, len(fact)):     print("Factorial of % d:" % i, fact[i])   # Get the processor time# in seconds at the end # of the calculation # using time.clock() method end = time.clock()   print("\nAt the end of the calculation") print("Processor time (in seconds):", end) print("Time elapsed during the calculation:", end - start)     
At the beginning of the calculation
Processor time (in seconds): 0.03451 

Factorial of  0: 1
Factorial of  1: 1
Factorial of  2: 2
Factorial of  3: 6
Factorial of  4: 24
Factorial of  5: 120
Factorial of  6: 720
Factorial of  7: 5040
Factorial of  8: 40320
Factorial of  9: 362880

At the end of the calculation
Processor time (in seconds): 0.034715
Time elapsed during the calculation: 0.0002050000000000038

Reference: https://docs.python.org/3/library/time.html#time.clock
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Concept of setjump and longjump in C

02 Jun, 2017
“Setjump” and “Longjump” are defined in setjmp.h, a header file in C standard library.
setjump(jmp_buf buf) : uses buf to remember current position and returns 0.
longjump(jmp_buf buf, i) : Go back to place buf is pointing to and return i .
// A simple C program to demonstrate working of setjmp() and longjmp()#include<stdio.h>#include<setjmp.h>jmp_buf buf;void func(){    printf("Welcome to GeeksforGeeks\n");      // Jump to the point setup by setjmp    longjmp(buf, 1);      printf("Geek2\n");}  int main(){    // Setup jump position using buf and return 0    if (setjmp(buf))        printf("Geek3\n");    else    {        printf("Geek4\n");        func();    }    return 0;}
Output :
Geek4
Welcome to GeeksforGeeks
Geek3
The main feature of these function is to provide a way that deviates from standard call and return sequence. This is mainly used to implement exception handling in C. setjmp can be used like try (in languages like C++ and Java). The call to longjmp can be used like throw (Note that longjmp() transfers control to the point set by setjmp()).
This article is contributed by Aditya Chatterjee.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Library
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.