code-rag-bench/online-tutorials huggingface dataset:
How to count set bits in a floating point number in C?

21 Jun, 2022
Given a floating point number, write a function to count set bits in its binary representation. For example, floating point representation of 0.15625 has 6 set bits (See this). A typical C compiler uses single precision floating point format. We can use the idea discussed here. The idea is to take address of the given floating point number in a pointer variable, typecast the pointer to char * type and process individual bytes one by one. We can easily count set bits in a char using the techniques discussed here. Following is C implementation of the above idea. 
C
#include <stdio.h> // A utility function to count set bits in a char.// Refer http://goo.gl/eHF6Y8 for details of this function.unsigned int countSetBitsChar(char n){    unsigned int count = 0;    while (n)    {      n &= (n-1);      count++;    }    return count;} // Returns set bits in binary representation of xunsigned int countSetBitsFloat(float x){    // Count number of chars (or bytes) in binary representation of float    unsigned int n = sizeof(float)/sizeof(char);     // typecast address of x to a char pointer    char *ptr = (char *)&x;      int count = 0;   // To store the result    for (int i = 0; i < n; i++)    {         count += countSetBitsChar(*ptr);         ptr++;    }    return count;} // Driver program to test above functionint main(){    float x = 0.15625;    printf ("Binary representation of %f has %u set bits ", x,             countSetBitsFloat(x));    return 0;}
Output: 
Binary representation of 0.156250 has 6 set bits
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
This article is contributed by Vineet Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
surindertarika1234
sooda367
tarakki100
cpp-puzzle
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
Python Data Type - GeeksforGeeks

26 Oct, 2020
A hash function takes a message of arbitrary length and generates a fixed length code.A hash function takes a message of fixed length and generates a code of variable length.A hash function may give the same hash value for distinct messages.
A hash function takes a message of arbitrary length and generates a fixed length code.
A hash function takes a message of fixed length and generates a code of variable length.
A hash function may give the same hash value for distinct messages.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
How to transform a JavaScript iterator into an array?

11 Aug, 2021
The task is to convert an iterator into an array
This can be performed by iterating each value of the iterator and storing the value into another array 
Method: 
To make an iterator for an array:
const it = array[Symbol.iterator](); 
So first we make an iterator for the  “array” named “it”. After creating the iterator we iterate to each value stored in that iterator and push it in another array named “p” with the use of the following code
p.push(word) 
where the word is the value corresponding to the array elements stored in the iterator. After iterating through each of the element we get our final array where all the values of the iterator get stored in p.
Example:  
javascript
<script>    const array = ['Geeks', 'for', 'Geeks'];    p=[]    const it = array[Symbol.iterator]();    document.write(it);    document.write("<br>");     for(let word of it)    {       p.push(word)    }document.write("After the conversion the array becomes");document.write("<br>");document.write(p);</script>
Output:
[object Array Iterator]
After the conversion the array becomes
["Geeks", "for", "Geeks"]
sweetyty
javascript-array
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check if a C# list is empty?

Use the Any method to find whether the list is empty or not.
Set the list −
var subjects = new List<string>();
subjects.Add("Maths");
subjects.Add("Java");
subjects.Add("English");
subjects.Add("Science");
subjects.Add("Physics");
subjects.Add("Chemistry");
Now set the following condition to check whether the list is empty or not −
bool isEmpty = !subjects.Any();
if(isEmpty) {
      Console.WriteLine("Empty");
   }else {
      Console.WriteLine("List is not empty");
   }
The following is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
   public static void Main(string[] args) {
      var subjects = new List<string>();
      subjects.Add("Maths");
      subjects.Add("Java");
      subjects.Add("English");
      subjects.Add("Science");
      subjects.Add("Physics");
      subjects.Add("Chemistry");

      foreach (var sub in subjects) {
         Console.WriteLine(sub);
      }

      bool isEmpty = !subjects.Any();
      if(isEmpty) {
         Console.WriteLine("Empty");
      } else {
         Console.WriteLine("List is not empty");
      }
   }
}
Python | os.getlogin() method

20 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.getlogin() method in Python is used to get the name of the user logged in on the controlling terminal of the process.
Syntax: os.getlogin()
Parameter: Not required
Return Type: This method returns a string that denotes the name of the user logged in on the controlling terminal of the process.
Code #1: use of os.getlogin() method
# Python program to explain os.getlogin() method     # importing os module import os  # Get the name of the user# logged in on the controlling # terminal of the process.user = os.getlogin()    # Print the name of the user# logged in on the controlling # terminal of the process.print(user) 
ihritik

python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Python program to multiply all the items in a dictionary

26 Nov, 2020
Python program to illustrate multiply all the items in a dictionary could be done by creating a dictionary which will store all the key-value pairs, multiplying the value of all the keys and storing it in a variable.
Example:
Input: dict = {‘value1’:5, ‘value2’:4, ‘value3’:3, ‘value4’:2, ‘value5’:1}Output: ans = 120
Input: dict = {‘v1’:10, ‘v2’:7, ‘v3’:2}Output: ans = 140
Approach:
Create a dictionary d and store key-value pairs in it.
Create a variable answer initialized to 1.
Run a loop to traverse through the dictionary d
Multiply each value of key with answer and store the result in answer itself.
Print answer.
Below are the examples of above approach.
Example 1:
Python3
# create a dictionaryd = {    'value1': 5,    'value2': 4,    'value3': 3,    'value4': 2,    'value5': 1,}  # create a variable to store resultanswer = 1  # run a loopfor i in d:    answer = answer*d[i]  # print answerprint(answer)
120

Example 2:
Python3
# create a dictionaryd = {    'a': 10,    'b': 7,    'c': 2,}  # create a variable to store resultanswer = 1  # run a loopfor i in d:    answer = answer*d[i]  # print answerprint(answer)
140

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python - Tkinter pack() Method

This geometry manager organizes widgets in blocks before placing them in the parent widget.
widget.pack( pack_options )

Here is the list of possible options  −
expand − When set to true, widget expands to fill any space not otherwise used in widget's parent.
expand − When set to true, widget expands to fill any space not otherwise used in widget's parent.
fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically).
fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically).
side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT.
side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT.
Try the following example by moving cursor on different buttons −
from Tkinter import *

root = Tk()
frame = Frame(root)
frame.pack()

bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red")
redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="green", fg="green")
greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")
bluebutton.pack( side = LEFT )

blackbutton = Button(bottomframe, text="Black", fg="black")
blackbutton.pack( side = BOTTOM)

root.mainloop()
When the above code is  executed, it produces the following result −
Output of C Program | Set 23

08 May, 2020
Predict the output of following C Program.
#include <stdio.h>#define R 4#define C 4  void modifyMatrix(int mat[][C]){   mat++;   mat[1][1] = 100;   mat++;   mat[1][1] = 200;}  void printMatrix(int mat[][C]){    int i, j;    for (i = 0; i < R; i++)    {        for (j = 0; j < C; j++)            printf("%3d ", mat[i][j]);        printf("\n");    }}  int main(){    int mat[R][C] = { {1, 2, 3, 4},        {5, 6, 7, 8},        {9, 10, 11, 12},        {13, 14, 15, 16}    };    printf("Original Matrix \n");    printMatrix(mat);      modifyMatrix(mat);      printf("Matrix after modification \n");    printMatrix(mat);      return 0;}
Output: The program compiles fine and produces following output:
Original Matrix
  1   2   3   4
  5   6   7   8
  9  10  11  12
 13  14  15  16
Matrix after modification
  1   2   3   4
  5   6   7   8
  9 100  11  12
 13 200  15  16

At first look, the line “mat++;” in modifyMatrix() seems invalid. But this is a valid C line as array parameters are always pointers (see this and this for details). In modifyMatrix(), mat is just a pointer that points to block of size C*sizeof(int). So following function prototype is same as “void modifyMatrix(int mat[][C])”
void modifyMatrix(int (*mat)[C]);
When we do mat++, mat starts pointing to next row, and mat[1][1] starts referring to value 10. mat[1][1] (value 10) is changed to 100 by the statement “mat[1][1] = 100;”. mat is again incremented and mat[1][1] (now value 14) is changed to 200 by next couple of statements in modifyMatrix().
The line “mat[1][1] = 100;” is valid as pointer arithmetic and array indexing are equivalent in C.
On a side note, we can’t do mat++ in main() as mat is 2 D array in main(), not a pointer.
Please write comments if you find above answer/explanation incorrect, or you want to share more information about the topic discussed above
cshivam718
C-Output
Output of C Programs
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Runtime Errors
Different ways to copy a string in C/C++
Output of C++ Program | Set 1
Output of Java Program | Set 3
Output of Java Programs | Set 12
Output of C++ programs | Set 47 (Pointers)
Output of Java Program | Set 7
Output of C programs | Set 59 (Loops and Control Statements)
Output of C Programs | Set 3
unsigned specifier (%u) in C with Examples
Populating Matplotlib subplots through a loop and a function

To populate matplotlib subplots through a loop and a function, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots with number of rows = 3 and number of columns = 2.
Create a figure and a set of subplots with number of rows = 3 and number of columns = 2.
Make a function to iterate the columns of each row and plot the x data points using plot() method at each column index.
Make a function to iterate the columns of each row and plot the x data points using plot() method at each column index.
Iterate rows (Step 2) and create random x data points and call iterate_columns() function (Step 3).
Iterate rows (Step 2) and create random x data points and call iterate_columns() function (Step 3).
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, axes = plt.subplots(3, 2)

""" Iterate column's axes"""
def iterate_columns(cols, x):
   for col in cols:
      col.plot(x, color='red')

""" Iterate row's axes"""
for row in axes:
   x = np.random.normal(0, 1, 100).cumsum()
   iterate_columns(row, x)

plt.show()
click method – Action Chains in Selenium Python

11 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around click method on Action Chains in Python Selenium. click method is used to click on an element or current position.
Syntax –
click(on_element=None)
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use click method as an Action chain as below –
click(on_element=element)

To demonstrate, click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # create action chain objectaction = ActionChains(driver)  # click the itemaction.click(on_element = element)  # perform the operationaction.perform()
Output –
Python-selenium
selenium
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
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
BigIntegerMath factorial() function | Guava | Java - GeeksforGeeks

26 Jul, 2021
The method factorial(int n) of Guava’s BigIntegerMath class is used to find the factorial of the given number. It returns n!, that is, the product of the first n positive integers.Syntax:  
public static BigInteger factorial(int n)
Parameters: This method takes the number n as parameter whose factorial is to be found.Return Value: This method returns the factorial of the given number n.Exceptions: This method throws IllegalArgumentException if n < 0.Note:  
The method returns 1 if n == 0.
The result takes O(n log n) space, so use cautiously.
This uses an efficient binary recursive algorithm to compute the factorial with balanced multiplies.
Below examples illustrates the BigIntegerMath.factorial() method:Example 1: 
Java
// Java code to show implementation of// factorial() method of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG {     // Driver code    public static void main(String args[])    {        int n1 = 10;         // Using factorial(int n) method of        // Guava's BigIntegerMath class        BigInteger ans1 = BigIntegerMath.factorial(n1);         System.out.println("Factorial of " + n1                           + " is: " + ans1);         int n2 = 12;         // Using factorial(int n) method of        // Guava's BigIntegerMath class        BigInteger ans2 = BigIntegerMath.factorial(n2);         System.out.println("Factorial of " + n2                           + " is: " + ans2);    }}
Factorial of 10 is: 3628800
Factorial of 12 is: 479001600
 
Example 2: 
Java
// Java code to show implementation of// factorial() method of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG {     // Driver code    public static void main(String args[])    {         try {            int n1 = -5;             // Using factorial(int n) method of            // Guava's BigIntegerMath class            // This should throw "IllegalArgumentException"            // as n < 0            BigInteger ans1 = BigIntegerMath.factorial(n1);             System.out.println("Factorial of " + n1                               + " is: " + ans1);        }        catch (Exception e) {            System.out.println("Exception: " + e);        }    }}
Exception: java.lang.IllegalArgumentException: n (-5) must be >= 0
 
Reference: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#factorial-int- 
manikarora059
Java-BigInteger
java-guava
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
How to create boxplot with multiple factor levels using ggplot2 in R?

To create a boxplot, we have one factor and one numerical column and the boxplot is created for each category or levels in that factor. Now if we have two factors then the boxplot can be created for both factor levels by passing fill argument in geom_boxplot. This will help us to differentiate between the boxplots for the two factors. Check out the below examples to understand how it works.
Consider the below data frame −
Live Demo
> x<-sample(c("Male","Female"),30,replace=TRUE)
> y<-rnorm(30)
> grp<-sample(letters[1:3],30,replace=TRUE)
> df<-data.frame(x,y,grp)
> df
       x              y  grp
1 Female    0.790349405    b
2   Male    0.868186299    b
3 Female   -2.108607808    b
4 Female    0.284872060    c
5   Male   -1.128470452    b
6   Male    0.001181183    b
7 Female   -2.915847134    c
8   Male   -1.416607857    c
9 Female   -1.784574028    a
10  Male    0.685830764    a
11 Female   0.581216168    c
12   Male   0.387109500    c
13 Female   0.611448059    c
14 Female   0.603614728    c
15   Male   0.207989975    c
16   Male   0.357018523    b
17 Female  -0.196608618    c
18   Male   1.165436068    c
19   Male   0.466733550    c
20 Female  -1.293515169    b
21   Male  -1.046339186    b
22 Female   1.692938740    c
23 Female   1.360998968    a
24 Female  -0.141122217    c
25   Male  -0.946920446    a
26 Female   1.091516275    c
27   Male   0.216101163    a
28 Female   0.935390544    a
29   Male  -0.636606941    a
30 Female   0.266238867    b
Loading ggplot2 and creating the boxplot −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_boxplot(aes(fill=grp))
Design Patterns - Iterator Pattern 

Iterator pattern is very commonly used design pattern in Java and .Net programming environment. This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. 
Iterator pattern falls under behavioral pattern category.
We're going to create a Iterator interface which narrates navigation method and a Container interface which retruns the iterator . Concrete classes implementing the Container interface will be responsible to implement Iterator interface and use it 
IteratorPatternDemo, our demo class will use NamesRepository, a concrete class implementation to print a Names stored as a collection in NamesRepository.
Create interfaces.
Iterator.java
public interface Iterator {
   public boolean hasNext();
   public Object next();
}
Container.java
public interface Container {
   public Iterator getIterator();
}
Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface.
NameRepository.java
public class NameRepository implements Container {
   public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};

   @Override
   public Iterator getIterator() {
      return new NameIterator();
   }

   private class NameIterator implements Iterator {

      int index;

      @Override
      public boolean hasNext() {
      
         if(index < names.length){
            return true;
         }
         return false;
      }

      @Override
      public Object next() {
      
         if(this.hasNext()){
            return names[index++];
         }
         return null;
      }		
   }
}
Use the NameRepository to get iterator and print names.
IteratorPatternDemo.java
public class IteratorPatternDemo {
	
   public static void main(String[] args) {
      NameRepository namesRepository = new NameRepository();

      for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
         String name = (String)iter.next();
         System.out.println("Name : " + name);
      } 	
   }
}
Verify the output.
Name : Robert
Name : John
Name : Julie
Name : Lora


    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Python | Minimum element in tuple list - GeeksforGeeks

11 Nov, 2019
Sometimes, while working with data in form of records, we can have a problem in which we need to find the minimum element of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using min() + generator expression
This is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the minimum element using min().
# Python3 code to demonstrate working of# Minimum element in tuple list# using min() + generator expression  # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]  # printing original list print("The original list : " + str(test_list))  # Minimum element in tuple list# using min() + generator expressionres = min(int(j) for i in test_list for j in i)  # printing resultprint("The Minimum element of list is : " + str(res))
The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
The Minimum element of list is : 1

 
Method #2 : Using min() + map() + chain.from_iterable()
The combination of above methods can also be used to perform this task. In this, the extension of finding minimum is done by combination of map() and from_iterable().
# Python3 code to demonstrate working of# Minimum element in tuple list# using min() + map() + chain.from_iterable()from itertools import chain  # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]  # printing original list print("The original list : " + str(test_list))  # Minimum element in tuple list# using min() + map() + chain.from_iterable()res = min(map(int, chain.from_iterable(test_list)))  # printing resultprint("The Minimum element of list is : " + str(res))
The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
The Minimum element of list is : 1

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
SaltStack - Python API

Salt provides programmatic access to all of its commands. Salt provides different modules for every section of the Salt system. Let us learn the basics of the python API and about how to run the basic salt commands in this chapter.
The salt.config module is used to access Salt configuration details.
import salt.config
opts = salt.config.client_config('/etc/salt/master')

Here, the client_config reads the salt configuration file and returns the configuration details as dictionary.
The salt.loader module is used to load each modules in Salt such as grains, minions, etc.
import salt.loader
opts = salt.config.minion_config('/etc/salt/minion')
grains = salt.loader.grains(opts)

Here, grains reads the details of the grains in the Salt system and returns it.
The salt.client module is used to execute salt, salt-call and the salt-SSH commands programmatically.
The most important python classes are as follows −
salt.client.LocalClient
salt.client.Caller
salt.client.ssh.client.SSHClient
The main function provided by most of the client module is cmd. This function wraps the CLI options and executes it, which is similar to the command line and returns the results as python data structures.
The LocalClient is used to send commands from the master to the salt minions and return the results to the master.
import salt.client

local = salt.client.LocalClient()
local.cmd('*', 'test.ping')
It will produce the following output −
{'minion1': True, 'minion2': True }

The Caller is used to run salt-call programmatically and return the results.
import salt.client
caller = salt.client.Caller()
caller.cmd('test.ping')
It will produce the following output −
True

The SSHCient is used to run the salt-ssh programmatically and return the results.
import salt.client.ssh.client
ssh = salt.client.ssh.client.SSHClient()
ssh.cmd('*', 'test.ping')

It will produce the following output −
{'minion1': True, 'minion2': True }

The salt.cloud module is used to execute the salt-cloud commands programmatically.
client = salt.cloud.CloudClient(path = '/etc/salt/cloud')

Cloud module provides functions to create VMs (create), to destroy VMs (destroy), list images provided by a cloud provider (list_images), list locations of a cloud provider (list_locations), list machine sizes of a cloud provider (list_sizes), etc.
 Print
 Add Notes
 Bookmark this page
Check whether a Stack is empty or not in Java

The method java.util.Stack.empty() is used to check if a stack is empty or not. This method requires no parameters. It returns true if the stack is empty and false if the stack is not empty.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.Stack;
public class Demo {
   public static void main (String args[]) {
      Stack stack = new Stack();
      stack.push("Amy");
      stack.push("John");
      stack.push("Mary");
      System.out.println("The stack elements are: " + stack);
      System.out.println("The stack is empty? " + stack.empty());
      System.out.println("\nThe element that was popped is: " + stack.pop());
      System.out.println("The element that was popped is: " + stack.pop());
      System.out.println("The element that was popped is: " + stack.pop());
      System.out.println("\nThe stack elements are: " + stack);
      System.out.println("The stack is empty? " + stack.empty());
   }
}
The stack elements are: [Amy, John, Mary]
The stack is empty? false
The element that was popped is: Mary
The element that was popped is: John
The element that was popped is: Amy
The stack elements are: []
The stack is empty? true
Now let us understand the above program.
The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed and then the Stack.empty() method is used to check if a stack is empty or not. A code snippet which demonstrates this is as follows −
Stack stack = new Stack();
stack.push("Amy");
stack.push("John");
stack.push("Mary");
System.out.println("The stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
The Stack.pop() method is used to pop the three stack elements. The stack is displayed and then the Stack.empty() method is used to check if a stack is empty or not. A code snippet which demonstrates this is as follows −
System.out.println("\nThe element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("\nThe stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
Create a Boolean object from Boolean value in Java

To create a Boolean object from Boolean value is quite easy. Create an object with Boolean and set the Boolean value “true” or “false”, which are the Boolean literals.
Let us now see how “true” value is added.
Boolean bool = new Boolean("true");
In the same way, “False” value is added.
Boolean bool = new Boolean("false");
The following is an example displaying how to create a Boolean object from Boolean value.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      Boolean bool = new Boolean("true");
      System.out.println(bool);
      bool = new Boolean("false");
      System.out.println(bool);
   }
}
True
False
Python OpenCV - imdecode() Function - GeeksforGeeks

05 Nov, 2021
Python cv2.imdecode() function is used to read image data from a memory cache and convert it into image format. This is generally used for loading the image efficiently from the internet. 
Syntax: cv2.imdecode(buf,flags)
Parameters:
buf – It is the image data received  in bytes
flags – It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR
Return: Image array
Note: If buf given is not image data then NULL will be returned.
Example 1:
Python3
#import modulesimport numpy as npimport urllib.requestimport cv2  # read the image urlurl = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'    with urllib.request.urlopen(url) as resp:        # read image as an numpy array    image = np.asarray(bytearray(resp.read()), dtype="uint8")          # use imdecode function    image = cv2.imdecode(image, cv2.IMREAD_COLOR)      # display image    cv2.imwrite("result.jpg", image)
Output:
Example 2: If grayscale is required, then 0 can be used as flag.
Python3
# import necessary modulesimport numpy as npimport urllib.requestimport cv2  # read image urlurl = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'  with urllib.request.urlopen(url) as resp:      # convert to numpy array    image = np.asarray(bytearray(resp.read()), dtype="uint8")          # 0 is used for grayscale image    image = cv2.imdecode(image, 0)          # display image    cv2.imwrite("result.jpg", image)
Output:
Example 3: Reading image from a file
Input Image:
Python3
# import necessayr modulesimport numpy as npimport urllib.requestimport cv2  # read th imagewith open("image.jpg", "rb") as image:        f = image.read()          # convert to numpy array    image = np.asarray(bytearray(f))          # RGB to Grayscale    image = cv2.imdecode(image, 0)          # display image    cv2.imshow("output", image)
Output:
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Tryit Editor v3.6 - Show Python

mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  password="mypassword",
  database="mydatabase"
)
​
mycursor = mydb.cursor()
C++ Program to Generate Multiplication Table

The multiplication table is used to define a multiplication operation for any number. It is normally used to lay the foundation of elementary arithmetic operations with base ten numbers.
The multiplication table of any number is written till 10. In each row, the product of the number with 1 to 10 is displayed. An example of the multiplication table of 4 is as follows −
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
4 * 10 = 40
A program that generates the multiplication table of the given number is as follows.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int n = 7, i;
   cout<<"The multiplication table for "<< n <<" is as follows:"<< endl;
   for (i = 1; i <= 10; i++)
   cout << n << " * " << i << " = " << n * i << endl;
   return 0;
}
The multiplication table for 7 is as follows:
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
In the above program, a for loop is used from 1 to 10. In each iteration of the for loop, the number is multiplied with i and the product is displayed. This is demonstrated by the following code snippet.
for (i = 1; i <= 10; i++)
cout << n << " * " << i << " = " << n * i <<endl;
Absolute and Relative Frequency in R Programming - GeeksforGeeks

04 May, 2020
In statistics, frequency or absolute frequency indicates the number of occurrences of a data value or the number of times a data value occurs. These frequencies are often plotted on bar graphs or histograms to compare the data values. For example, to find out the number of kids, adults, and senior citizens in a particular area, to create a poll on some criteria, etc.In R language, frequencies can be depicted as absolute frequency and relative frequency.
Absolute frequency shows the number of times the value is repeated in the data vector.
Formula:
where,
 is represented as absolute frequency of each valueN represents total number of data values
In R, frequency table of a data vector can be created using table() function.Syntax:
table(x)

where,x is data vector
Example:Assume, “M” represents males and “F” represents females in the data vector below.
# Defining vectorx <- c("M", "M", "F", "M", "M", "M", "F", "F", "F", "M")  # Absolute frequency tableaf <- table(x)  # Printing frequency tableprint(af)  # Check the classclass(af)
Output:
x
F M 
4 6 
[1] "table"

Relative frequency is the absolute frequency of that event divided by the total number of events. It represents the proportion of a particular data category present in the data vector. Mathematically,
where,
 represents the relative frequency of  event is represented as absolute frequency of each valueN represents total number of data values
In R language, table() function and length of data vector is used together to find relative frequency of data vector.Syntax:
table(x)/length(x)

Example:
# Defining vectorx <- c("M", "M", "F", "M", "M", "M", "F", "F", "F", "M")  # Relative frequency tablerf <- table(x)/length(x)  # Printing frequency tableprint(rf)  # Check the classclass(rf)
Output:
x
  F   M 
0.4 0.6
[1] "table"

R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Remove rows with NA in one column of R DataFrame
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?
K-Means Clustering in R Programming
R Programming Language - Introduction
How to clone a generic list in C#?

A list is a Generic collection to hold elements of same datatypes.
To clone a list, you can use the CopyTo method.
Declare a list and add elements −
List < string > myList = new List < string > ();
myList.Add("Programming");
myList.Add("Web Dev");
myList.Add("Database");
Now create a new array and clone the list into it −
string[] arr = new string[10];
myList.CopyTo(arr);
Here is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {

      List < string > myList = new List < string > ();
      myList.Add("Programming");
      myList.Add("Web Dev");
      myList.Add("Database");
      Console.WriteLine("First list...");

      foreach(string value in myList) {
         Console.WriteLine(value);
      }
      string[] arr = new string[10];
      myList.CopyTo(arr);
      Console.WriteLine("After cloning...");

      foreach(string value in arr) {
         Console.WriteLine(value);
      }
   }
}
First list...
Programming
Web Dev
Database
After cloning...
Programming
Web Dev
Database
Difference between Antivirus and Internet Security - GeeksforGeeks

24 May, 2020
Antivirus:Antivirus is an application or software which provides security from the malicious software coming from the internet. An antivirus chases the method in which it performs 3 actions which are:
1. Detection
2. Identification
3. Removal 
Antivirus deals with both external threats and internal threats. It is implemented only software not in hardware also.
Internet Security:Internet Security has the antivirus feature as well as some other features. It deals with protection and privacy against viruses, phishing, spyware etc. It also deals with all internet threats and cyber attacks. Internet security includes firewall, features of antivirus, email protection and parent control. Internet security deals with the protection of data, sent over the Internet for example: debit card number, credit card number, email_passwords, bank account details etc.
Let’s see the difference between Antivirus and Internet Security:
ashushrma378
pp_pankaj
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Multiple Access Protocols in Computer Network
GSM in Wireless Communication
Cryptography and its Types
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Difference Between == and .equals() Method in Java
Difference between Process and Thread
Conditional wait and signal in multi-threading - GeeksforGeeks

06 Jul, 2021
What are conditional wait and signal in multi-threading? Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait() to wait or sleep. On the other hand, there is a function pthread_cond_signal() to wake up sleeping or waiting thread. Threads can wait on a condition variable. 
Prerequisite : Multithreading
Syntax of pthread_cond_wait() : 
int pthread_cond_wait(pthread_cond_t *restrict cond, 
                   pthread_mutex_t *restrict mutex);
Parameter :  
cond : condition variable
mutex : is mutex lock 
Return Value :  
On success, 0 is returned ; otherwise, an error 
number shall be returned to indicate the error. 
The pthread_cond_wait() release a lock specified by mutex and wait on condition cond variable. 
Syntax of pthread_cond_signal() :  
int pthread_cond_signal(pthread_cond_t *cond);
Parameter : 
cond : condition variable
Return Value :  
On success, 0 is returned ; otherwise, an error number
shall be returned to indicate the error. 
The pthread_cond_signal() wake up threads waiting for the condition variable. 
Note : The above two functions works together. 
Below is the implementation of condition, wait and signal functions.  
C
// C program to implement cond(), signal()// and wait() functions#include <pthread.h>#include <stdio.h>#include <unistd.h> // Declaration of thread condition variablepthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; // declaring mutexpthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int done = 1; // Thread functionvoid* foo(){     // acquire a lock    pthread_mutex_lock(&lock);    if (done == 1) {         // let's wait on condition variable cond1        done = 2;        printf("Waiting on condition variable cond1\n");        pthread_cond_wait(&cond1, &lock);    }    else {         // Let's signal condition variable cond1        printf("Signaling condition variable cond1\n");        pthread_cond_signal(&cond1);    }     // release lock    pthread_mutex_unlock(&lock);     printf("Returning thread\n");     return NULL;} // Driver codeint main(){    pthread_t tid1, tid2;     // Create thread 1    pthread_create(&tid1, NULL, foo, NULL);     // sleep for 1 sec so that thread 1    // would get a chance to run first    sleep(1);     // Create thread 2    pthread_create(&tid2, NULL, foo, NULL);     // wait for the completion of thread 2    pthread_join(tid2, NULL);     return 0;}
Output:  
nidhi_biet
surinderdawra388
cpp-multithreading
mutli-threading
system-programming
C Programs
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
How to Append a Character to a String in C
C program to sort an array in ascending order
time() function in C
C Program to Swap two Numbers
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
Check if the Object is a Matrix in R Programming - is.matrix() Function - GeeksforGeeks

12 Jun, 2020
is.matrix() function in R Language is used to return TRUE if the specified data is in the form of matrix else return FALSE.
Syntax: is.matrix(x)
Parameters:x: specified matrix
Example 1:
# R program to illustrate# is.matrix function  # Specifying some different types of arraysA <- matrix(c(1:5))B <- matrix(c(1:12), nrow = 4, byrow = TRUE)C <- matrix(c(1:12), nrow = 4, byrow = FALSE)  # Calling is.matrix() functionis.matrix(A)is.matrix(B)is.matrix(C)
Output:
[1] TRUE
[1] TRUE
[1] TRUE

Example 2:
# R program to illustrate# is.matrix function  # Specifying Biochemical oxygen demand datax <- BOD  # Calling is.matrix() functionis.matrix(x)  # Calling is.matrix() function# over different types of datais.matrix(4)is.matrix("2")is.matrix("a")
Output:
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE

R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame
Python OpenCV - Depth map from Stereo Images - GeeksforGeeks

12 Dec, 2021
OpenCV is the huge open-source library for the computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems.Note: For more information, refer to Introduction to OpenCV
Depth Map : A depth map is a picture where every pixel has depth information(rather than RGB) and it normally represented as a grayscale picture. Depth information means the distance of surface of scene objects from a viewpoint. An example of pixel value depth map can be found here : Pixel Value Depth Map using Histograms
Stereo Images : Two images with slight offset. For example, take a picture of an object from the center. Move your camera to your right by 6cms while keeping the object at the center of the image. Look for the same thing in both pictures and infer depth from the difference in position. This is called stereo matching. To have best results, avoid distortions.
Approach  
Collect or take stereo images.
Import OpenCV and matplotlib libraries.
Read both left and right images.
Calculate disparity using stereo.compute.
Example :Sample Images: 
Left
 
Right
 
Python3
# import OpenCV and pyplotimport cv2 as cvfrom matplotlib import pyplot as plt # read left and right imagesimgR = cv.imread('right.png', 0)imgL = cv.imread('left.png', 0) # creates StereoBm objectstereo = cv.StereoBM_create(numDisparities = 16,                            blockSize = 15) # computes disparitydisparity = stereo.compute(imgL, imgR) # displays image as grayscale and plottedplt.imshow(disparity, 'gray')plt.show()
Output: 
Disparity Map Output
 
adnanirshad158
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
MongoDB - Logical Query Operators - GeeksforGeeks

10 May, 2020
MongoDB supports logical query operators. These operators are used for filtering the data and getting precise results based on the given conditions. The following table contains the comparison query operators:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are retrieving only those employee’s documents whose branch is CSE and joiningYear is 2018.
db.contributor.find({$and: [{branch: "CSE"}, {joiningYear: 2018}]}).pretty()
In this example, we are retrieving only those employee’s documents whose salary is not 3000 and whose branch is not ECE.
db.contributor.find({$nor: [{salary: 3000}, {branch: "ECE"}]}).pretty()
In this example, we are retrieving only those employee’s documents whose branch is ECE or joiningYear is 2017.
db.contributor.find({$or: [{branch: "ECE"}, {joiningYear: 2017}]}).pretty()
In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000.
db.contributor.find({salary: {$not: {$gt: 2000}}}).pretty()
MongoDB
MongoDB-operators
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - Distinct() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
Export data from MongoDB
MongoDB - sort() Method
MongoDB - Regex
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()