code-rag-bench/online-tutorials huggingface dataset:
How to perform fisher test in R?

The fisher test helps us to understand whether there exists a significant non-random relationship among categorical variables or not. It is applied on contingency tables because these tables are used to represent the frequency for categorical variables and we can apply it on a matrix as well as matrices have the similar form. In R, we can use fisher.test function to perform the fisher test.
 Live Demo
M1<-matrix(1:9,ncol=3)
M1
   [,1] [,2] [,3]
[1,] 1    4    7 
[2,] 2    5    8
[3,] 3    6    9
fisher.test(M1)
Fisher's Exact Test for Count
Data
data: M1
p-value = 0.9888
alternative hypothesis: two.sided
 Live Demo
M2<-matrix(1:16,ncol=4)
M2
     [,1] [,2] [,3] [,4]
[1,]   1    5    9    13
[2,]   2    6    10   14
[3,]   3    7    11   15
[4,]   4    8    12   16
fisher.test(M2)
Fisher's Exact Test for Count Data
data: M2
p-value = 0.9993
alternative hypothesis: two.sided
 Live Demo
M3<-matrix(sample(0:4,9,replace=TRUE),nrow=3)
M3
   [,1] [,2] [,3]
[1,] 0    0    4
[2,] 4    0    4
[3,] 1    2    3
fisher.test(M3)
Fisher's Exact Test for Count
Data
data: M3
p-value = 0.5567
alternative hypothesis: two.sided
 Live Demo
M4<-matrix(c(14,27,15,24,27,17,39,19,24),nrow=3)
M4
    [,1] [,2] [,3]
[1,] 14   24   39
[2,] 27   27   19
[3,] 15   17   24
fisher.test(M4)
Fisher's Exact Test for Count Data
data: M4
p-value = 0.02126
alternative hypothesis: two.sided
fisher.test(M4,alternative="greater")
Fisher's Exact Test for Count Data
data: M4
p-value = 0.02126
alternative hypothesis: greater
fisher.test(M4,alternative="less")
Fisher's Exact Test for Count Data
data: M4
p-value = 0.02126
alternative hypothesis: less
 Live Demo
M5<-matrix(sample(c(545,501,576),4,replace=TRUE),nrow=2)
M5
    [,1] [,2]
[1,] 545 545
[2,] 545 545
fisher.test(M5)
Fisher's Exact Test for Count Data
data: M5
p-value = 1
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval: 0.8391933 1.1916205
sample estimates:
odds ratio
1
fisher.test(M5,alternative="greater")
Fisher's Exact Test for Count Data
data: M5
p-value = 0.5175
alternative hypothesis: true odds ratio is greater than 1
95 percent confidence interval: 0.8626582 Inf
sample estimates:
odds ratio
1
fisher.test(M5,alternative="less")
Fisher's Exact Test for Count Data
data: M5 p-value = 0.5175
alternative hypothesis: true
odds ratio is less than 1
95 percent confidence interval: 0.000000 1.159208
sample estimates:
odds ratio
1
Java - String replaceFirst() Method

This method replaces the first substring of this string that matches the given regular expression with the given replacement.
Here is the syntax  of this method −
public String replaceFirst(String regex, String replacement)

Here is the detail of parameters −
regex − the regular expression to which this string is to be matched.
regex − the regular expression to which this string is to be matched.
replacement − the string which would replace found expression.
replacement − the string which would replace found expression.
This method returns a resulting String.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");

      System.out.print("Return Value :" );
      System.out.println(Str.replaceFirst("(.*)Tutorials(.*)", "AMROOD"));

      System.out.print("Return Value :" );
      System.out.println(Str.replaceFirst("Tutorials", "AMROOD"));
   }
}
This will produce the following result −
Return Value :AMROOD
Return Value :Welcome to AMROODpoint.com


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
MySQL - GROUP BY Clause

You can use GROUP BY to group values from a column, and, if you wish, perform calculations on that column. You can use COUNT, SUM, AVG, etc., functions on the grouped column.
To understand GROUP BY clause, consider an employee_tbl table, which is having the following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   3  | Jack | 2007-04-06 |        100         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
|   5  | Zara | 2007-02-06 |        350         |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, suppose based on the above table we want to count number of days each employee did work.
If we will write a SQL query as follows, then we will get the following result −
mysql> SELECT COUNT(*) FROM employee_tbl;
+---------------------------+
|          COUNT(*)         |
+---------------------------+
|             7             |
+---------------------------+
But this is not serving our purpose, we want to display total number of pages typed by each person separately. This is done by using aggregate functions in conjunction with a GROUP BY clause as follows −
mysql> SELECT name, COUNT(*)
   -> FROM   employee_tbl 
   -> GROUP BY name;
+------+----------+
| name | COUNT(*) |
+------+----------+
| Jack |     2    |
| Jill |     1    |
| John |     1    |
| Ram  |     1    |
| Zara |     2    |
+------+----------+
5 rows in set (0.04 sec)
We will see more functionality related to GROUP BY in other functions like SUM, AVG, etc.

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
How to read the windows host file using PowerShell?

Windows Host file that maps the hostname and the IP address is the plain text file. So reading the host file is simpler. We just need to use the Get-Content command to retrieve the file content.
Generally, the host file is stored at the location c:\windows\System32\drivers\etc\.  If the OS is installed at that location.
Or you can use $env:Windir to get the windows directory.
To get the file content,
Get-Content $env:windir\system32\drivers\etc\hosts
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#       127.0.0.1       localhost
#       ::1             localhost
To get the host file from the remote server,
Get-Content \\Computer1\c$\windows\system32\drivers\etc\hosts
set::key_comp() in C++ STL - GeeksforGeeks

25 Jun, 2018
set::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container. By default, this is a less object, which returns the same as operator ‘<'. This object determines the order of the elements in the container. It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the first argument is considered to go before the second in the strict weak ordering it defines or false otherwise. Two elements of a set are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
Syntax:
key_compare set_name.key_comp() 

Parameters: This function does not accept any parameter.
Return value: The function returns a copy of the comparison object used by the container.
Program to demonstrate the above function:
// C++ program to illustrate the// set::key_comp() function#include <bits/stdc++.h>using namespace std;  int main(){    // creating a set named 'a'    set<int> a;      set<int>::key_compare comp = a.key_comp();      // Inserting elements into set    for (int i = 0; i <= 10; i++)        a.insert(i);      cout << "Set a has the numbers: ";      // stores the last value of the set    int l = *a.rbegin();      // initialising the iterator    set<int>::iterator it = a.begin();      // printing elements of all set    do {        cout << *it << " ";    } while (comp(*(++it), l));      return 0;}
Set a has the numbers: 0 1 2 3 4 5 6 7 8 9

CPP-Functions
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Socket Programming in C/C++
C++ Classes and Objects
Operator Overloading in C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Bitwise Operators in C/C++
Constructors in C++
Templates in C++ with Examples
Copy Constructor in C++
Python | Element indices Summation - GeeksforGeeks

19 Feb, 2020
Usually, we require to find the sum of index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list. Lets discuss certain ways to do so.
Method #1 : Naive Method + sum()We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task. The sum() is used to perform sum of list.
# Python code to demonstrate # Element indices Summation# using naive method + sum()  # initializing list test_list = [1, 3, 4, 3, 6, 7]  # printing initial list print ("Original list : " + str(test_list))  # using naive method# Element indices Summation# to find indices for 3res_list = []for i in range(0, len(test_list)) :    if test_list[i] == 3 :        res_list.append(i)res = sum(res_list)  # printing resultant list print ("New indices summation : " + str(res))
Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

 
Method #2 : Using list comprehension + sum()List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time. The sum() is used to perform sum of list.
# Python code to demonstrate # Element indices Summation# using list comprehension + sum()  # initializing list test_list = [1, 3, 4, 3, 6, 7]  # printing initial list print ("Original list : " + str(test_list))  # using list comprehension + sum()# Element indices Summation# to find indices for 3res_list = [i for i in range(len(test_list)) if test_list[i] == 3]res = sum(res_list)  # printing resultant list print ("New indices summation : " + str(res))
Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
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
Java Program to Find the Roots of Quadratic Equation - GeeksforGeeks

04 Dec, 2020
The roots of a function are the x-intercepts. By definition, the y-coordinate of points lying on the x-axis is zero. Therefore, to find the roots of a quadratic function, we set f (x) = 0, and solve the equation, ax2 + bx + c = 0.
Conditions for a quadratic equation – 
ax^2 + bx + c = 0 

where 
a, b, c are real numbers and cannot be zero ie, there value must be from {-∞ to -1} and {1 to ∞}
A mathematical formula for finding the roots of a quadratic equation – 
roots = (-b ± √(b2-4ac)) / (2a)

± represents there are two roots.
The roots of the quadratic equations are – 
first = (-b + √(b2-4ac)) / (2a)
second = (-b - √(b2-4ac)) / (2a)
The (b^2 – 4ac) which is the determinant, tells us about the nature of the roots –
if (b^2 – 4ac) > 0, roots are real and differentif (b^2 – 4ac) == 0, roots are real and equalif (b^2 – 4ac) < 0, roots are complex and different
if (b^2 – 4ac) > 0, roots are real and different
if (b^2 – 4ac) == 0, roots are real and equal
if (b^2 – 4ac) < 0, roots are complex and different
Code to find roots of a quadratic equation:
Java
// Java program to find the roots of// quadratic equation  public class Main {      public static void main(String[] args)    {          // value of the constants a, b, c        double a = 7.2, b = 5, c = 9;          // declared the two roots        double firstroot, secondroot;          // determinant (b^2 - 4ac)        double det = b * b - 4 * a * c;          // check if determinant is greater than 0        if (det > 0) {              // two real and distinct roots            firstroot = (-b + Math.sqrt(det)) / (2 * a);            secondroot = (-b - Math.sqrt(det)) / (2 * a);              System.out.format(                "First Root = %.2f and Second Root = %.2f",                firstroot, secondroot);        }          // check if determinant is equal to 0        else if (det == 0) {              // two real and equal roots            // determinant is equal to 0            // so -b + 0 == -b            firstroot = secondroot = -b / (2 * a);              System.out.format(                "First Root = Second Root = %.2f;",                firstroot);        }          // if determinant is less than zero        else {              // roots are complex number and distinct            double real = -b / (2 * a);              double imaginary = Math.sqrt(-det) / (2 * a);              System.out.printf("First Root = %.2f+%.2fi",                              real, imaginary);            System.out.printf("\nSecond Root = %.2f-%.2fi",                              real, imaginary);        }    }}
First Root = -0.35+1.06i
Second Root = -0.35-1.06i
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
How to convert timestamp string to datetime object in Python?

You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp. 
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
This will give the output −
2017-07-14 08:10:00
How do I get an ISO 8601 date in string format in Python?

To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'. 
You can use it as follows −
from datetime import datetime
my_date = datetime.now()
print(my_date.isoformat())
This will give the output −
2018-01-02T22:08:12.510696
In older python versions, you can use the strftime function to format the datetime object such that you get the desired result. 
from datetime import datetime
my_date = datetime.now()
print(my_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))
This will give the output −
2018-01-02T22:10:05.284208
Avoiding class data shared among the instances in Python

When we instantiate a class in Python, all its variables and functions also get inherited to the new instantiated class. But there may be e occasions when we do not want some of the variables of the parent class to be inherited by the child class. In this article, we will explore two ways to do that.
In the below example we show how the variables are instance heated from a given class and how the variables are shared across all the instantiated classes.
 Live Demo
class MyClass:
   listA= []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)
Running the above code gives us the following result −
Instance X: [10, 20, 30, 40]
Instance Y: [10, 20, 30, 40]
We can use the I need a method to make the variables inside a class as private. These variables will not be shared across the classes when the parent class is instantiated.
 Live Demo
class MyClass:
   def __init__(self):
      self.listA = []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)
Running the above code gives us the following result −
Instance X: [10, 30]
Instance Y: [20, 40]
In this approach, we will re-declare the variables outside the class. As the variables get initialized again that do not get shared across the instantiated classes.
 Live Demo
class MyClass:
   listA = []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

x.listA = []
y.listA = []
# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)
Output
Running the above code gives us the following result −
Instance X: [10, 30]
Instance Y: [20, 40]
Flip Effect with CSS

The flip effect is used to create a mirror image of the object. The following parameters can be used in this filter
To set flip effect
Live Demo
<html>
   <head>
   </head>
   <body>
      <img src = "/css/images/logo.png" alt = "CSS Logo" style = "Filter: FlipH">
      <img src = "/css/images/logo.png" alt = "CSS Logo" style = "Filter: FlipV">
      <p>Text Example:</p>
      <div style = "width: 300;
         height: 50;
         font-size: 30pt;
         font-family: Arial Black;
         color:red;
         Filter: FlipV">CSS Tutorials</div>
   </body>
</html>
GATE | GATE-CS-2009 | Question 10 - GeeksforGeeks

28 Jun, 2021
What is the number of swaps required to sort n elements using selection sort, in the worst case?(A) (n)(B) (n log n)(C) (n^2 )(D) (n^2 log n)(A) Theta(n)(B) Theta(nLogn)(C) Theta(n*n)(D) Theta(n*nLogn)Answer: (A)Explanation: Here is Selection Sort algorithm for sorting in ascending order.
   1. Find the minimum value in the list
   2. Swap it with the value in the first position
   3. Repeat the steps above for the remainder of the list (starting at
      the second position and advancing each time)
As we can see from the algorithm, selection sort performs swap only after finding the appropriate position of the current picked element. So there are O(n) swaps performed in selection sort.Because swaps require writing to the array, selection sort is preferable if writing to memory is significantly more expensive than reading. This is generally the case if the items are huge but the keys are small. Another example where writing times are crucial is an array stored in EEPROM or Flash. There is no other algorithm with less data movement.
References:http://en.wikipedia.org/wiki/Selection_sortQuiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2007 | Question 64
PySide2 - Create Tooltip - GeeksforGeeks

29 Aug, 2020
In this article, we are going to learn how to create a tooltip. A tooltip is often used to specify extra information about something when the user moves the mouse pointer over an element. In order to make it, we use setToolTip() function which is defined in PySide2.QtWidgets. 
Steps to create tooltip:
1. Import PySide2 Widgets and Gui modules in your code2. Create window with title and font setting3. Set tooltip ‘Our Main Window’ to entire window4. Set icons in two states active and disable with tooltip as “Active Icon” and “Disable Icon” respectively.
Input Image : 
Python3
# import system moduleimport sys  # import QtWidget Modulesfrom PySide2.QtWidgets import QApplication, QWidget, QLabel, QToolTip  # import QtGui modulesfrom PySide2.QtGui import QIcon, QPixmap, QFont  class Window(QWidget):    def __init__(self):        super().__init__()          # set window title        self.setWindowTitle("GeeksforGeeks - ToolTip")                  # set window geometry         self.setGeometry(300, 300, 500, 400)          # set tooltip font and font type        QToolTip.setFont(QFont("Decorative", 30, QFont.Bold))                  # set tooltip        self.setToolTip('Our Main Window')      def setIconModes(self):        # set icon         icon1 = QIcon("geeksforgeeks.png")        # set label         label1 = QLabel('Sample', self)        # set image in Active state        pixmap1 = icon1.pixmap(100, 100, QIcon.Active, QIcon.On)        # set Pixmap        label1.setPixmap(pixmap1)        # set tooltip text        label1.setToolTip("Active Icon")          # set icon         icon2 = QIcon("geeksforgeeks.png")        # set label        label2 = QLabel('Sample', self)        # set image in Disabled state        pixmap2 = icon2.pixmap(100, 100, QIcon.Disabled, QIcon.Off)        # set P        label2.setPixmap(pixmap2)        label2.move(100, 0)        label2.setToolTip("Disable Icon")  myApp = QApplication(sys.argv)window = Window()window.setIconModes()window.show()  myApp.exec_()sys.exit(0)
Output Image: 
Active State: 
Disable State:
Python-gui
Python-PySide2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to get objects by ID, Class, Tag, and Attribute in jQuery?

Here’s how you can get objects by ID Selector (#id), by Class Selector (.class), by Tag, and Attribute (.attr()).
Get Object by Class Selector
The element class selector selects all the elements which match with the given class of the elements.
Live Demo
<html>
   <head>
      <title>jQuery Selector</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
      <script>
         $(document).ready(function() {    
            $(".big").css("background-color", "yellow");
         });
      </script>
   </head>
   
   <body>

      <div class = "big" id="div1">
         <p>This is first division of the DOM.</p>
      </div>

      <div class = "medium" id = "div2">
         <p>This is second division of the DOM.</p>
      </div>

   </body>
</html>
Get Object by ID Selector
The element ID selector selects a single element with the given id attribute:
Live Demo
<html>
   <head>
      <title>jQuery Selector</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(function(){
           $("#submit").click(function(){      
             alert($('input:radio:checked').val());
          });
         });
      </script>
   </head>
   <body>
      <form id="myForm">
         Select a number:<br>
         <input type="radio" name="q1" value="1">1
         <input type="radio" name="q1" value="2">2
         <input type="radio" name="q1" value="3">3<br>
         <button id="submit">Result</button>
      </form>
   </body>
</html>
Get Object by Tag
For this, pass the name of the specific tag i.e. <a> tag below:
Live Demo
<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
          $("a").click(function(){
            $("a.active").removeClass("active");
            $(this).addClass("active");
           });
         });
      </script>
      <style>
         .active {
            font-size: 22px;  
         }
      </style>
   </head>
   <body>
      <a href="#" class="">One</a>
      <a href="#" class="">Two</a>
      <p>Click any of the link above and you can see the changes.</p>
   </body>
</html>
Get Object by Attribute
Using the .attr(), you can get any attribute of any tag. Here’s an example showing how to get an attribute value:
Live Demo
<html>

   <head>
      <title>jQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

      <script>
      $(document).ready(function(){
         $("button").click(function(){
            $("img").attr("height", "200");
         });
      });
      </script>
   </head>
   
   <body>
      <img src="/green/images/logo.png" alt="logo" width="450" height="160"><br>
      <button>Change the height</button>
   </body>
   
</html>
What is dependency inversion principle and how to implement in C#?

High-level modules should not depend on low-level modules. Both should depend on abstractions.Abstractions should not depend on details. Details should depend on abstractions.This principle is primarily concerned with reducing dependencies among the code modules.
Code Before Dependency Inversion
using System;
namespace SolidPrinciples.Dependency.Invertion.Before{
   public class Email{
      public string ToAddress { get; set; }
      public string Subject { get; set; }
      public string Content { get; set; }
      public void SendEmail(){
         //Send email
      }
   }
   public class SMS{
      public string PhoneNumber { get; set; }
      public string Message { get; set; }
      public void SendSMS(){
         //Send sms
      }
   }
   public class Notification{
      private Email _email;
      private SMS _sms;
      public Notification(){
         _email = new Email();
         _sms = new SMS();
      }
      public void Send(){
         _email.SendEmail();
         _sms.SendSMS();
      }
   }
}
Code After Dependency Inversion
using System.Collections.Generic;
namespace SolidPrinciples.Dependency.Invertion.Before{
   public interface IMessage{
      void SendMessage();
   }
   public class Email: IMessage{
      public string ToAddress { get; set; }
      public string Subject { get; set; }
      public string Content { get; set; }
      public void SendMessage(){
         //Send email
      }
   }
   public class SMS: IMessage{
      public string PhoneNumber { get; set; }
      public string Message { get; set; }
      public void SendMessage(){
         //Send Sms
      }
   }
   public class Notification{
      private ICollection<IMessage> _messages;
      public Notification(ICollection<IMessage> messages){
         this._messages = messages;
      }
      public void Send(){
         foreach (var message in _messages){
            message.SendMessage();
         }
      }
   }
}
How to work with images in Bokeh (Python)?

To work with images in Bokeh, use image_url() method and pass a list of images.
Configure the default output state to generate output saved to a file when :func:'show' is called.
Create a new Figure for plotting.
Render the images loaded from the given URLs.
Immediately display a Bokeh object or application.
from bokeh.plotting import figure, show, output_file

output_file('image.html')

p = figure(x_range=(0, 1), y_range=(0, 1))
p.image_url(url=['bird.jpg'], x=0, y=1, w=0.8, h=0.6)
show(p)
How to delete empty files and folders using PowerShell?

To delete empty files and folders, we need to first retrieve the list and which has been shown in the earlier articles.
In this article, we are using the logic that if we find an empty file or folder we will delete them. To implement that logic, use the below script.
gci C:\Temp -Recurse | foreach {
   if($_.Length -eq 0){
      Write-Output "Removing Empty File $($_.FullName)"
      $_.FullName | Remove-Item -Force
   }
   if( $_.psiscontainer -eq $true){
      if((gci $_.FullName) -eq $null){
         Write-Output "Removing Empty folder $($_.FullName)"
         $_.FullName | Remove-Item -Force
      }
}
The above command will remove empty files and folders/sub-folders from the C:\temp path.
You will see the output something like this.
What is the correct use of schema.org SiteNavigationElement in HTML?

The schema.org SiteNavigationElement extends WebPageElement. It is used to mark-up links that would make amazing contextual links.
<nav role = "navigation" itemscope itemtype = "http://schema.org/SiteNavigationElement">
<ul>
   <li>
      <a href = "https://example.com/" title = "Link to home page" itemprop = "url">
         <span itemprop="name">Home page</span>
      </a>
   </li>
   <li>
      <a href = "https://examplecom/demo" title="Link to demo page" itemprop = "url">
         <span itemprop = "name">My demo page</span>
      </a>
   </li>
</ul>
Modulus function in C++ STL

In this article, we will be discussing the working, syntax, and examples of modulus functions in C++.
modulus function object class in C++, which is defined in <functional> header file. modulus
function is a binary function object class used to get the result of the modulus operation of the
two arguments. This function works the same as the operator ‘% ‘.
Template struct modulus : binary_function
{
   T operator() (const T& a, const T& b) const {return a%b; }
};
The function accepts the following parameter(s) −
T − This is the type of the argument passed to function call.
T − This is the type of the argument passed to function call.
 Live Demo
#include <iostream>
#include <algorithm>
#include <functional&g;
using namespace std;
int main(){
   //create an array
   int arr[] = { 10, 20, 35, 45, 50, 61 };
   int rem[6];
   transform(arr, arr + 6, rem,bind2nd(modulus<int>(), 2));
   for (int i = 0; i < 5; i++){
      cout << arr[i] << " is a "<<(rem[i] == 0 ? "even" : "odd")<<"\n";
   }
   return 0;
}
If we run the above code it will generate the following output −
10 is a even
20 is a even
35 is a odd
45 is a odd
50 is a even
Go Data Types

Data type is an important concept in programming. Data type specifies the size and type of variable values.
Go is statically typed, meaning that once a variable type is defined, it can only store data of that type.
Go has three basic data types:
bool: represents a boolean value and is either true or false
Numeric: represents integer types, floating point values, 
  and complex types
string: represents a string value
This example shows some of the different data types in Go:
Add the correct data type for the following variables:
package main   
import ("fmt") 
func main() {
  var myNum   = 90
  var myWord   = "Hello"
  var myBool   = true
}

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 use JavaScript to check if a number has a decimal place or it’s a whole number?

Use the Math.floor method to check whether a number has a decimal place or not.
You can try to run the following code to check if a number has a decimal place or not −
Live Demo
<html>
   <head>
      <title>JavaScript Numbers</title>
   </head>
   
   <body>
      <script>
         var num = 10.2;
         if (num == Math.floor(num)) {
            alert("Whole Number")
         } else {
            alert("Decimal Number")
         }
      </script>
   </body>
</html>
Display USD currency records with the correct format in MySQL

Use FORMAT() in MySQL to display USD currency records in the correct form. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Amount DECIMAL(15,4)
   -> );
Query OK, 0 rows affected (0.75 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(90948484);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(1000000000);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(1535353536);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(773646463);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output−
+-----------------+
| Amount          |
+-----------------+
| 90948484.0000   |
| 1000000000.0000 |
| 1535353536.0000 |
| 773646463.0000  |
+-----------------+
4 rows in set (0.00 sec)
Here is the query to display currency records correctly in MySQL−
mysql> select concat('USD ',format(Amount,2)) as Currency from DemoTable;
This will produce the following output. Here, we are displaying USD currency records in the correct format−
+----------------------+
| Currency             |
+----------------------+
| USD 90,948,484.00    |
| USD 1,000,000,000.00 |
| USD 1,535,353,536.00 |
| USD 773,646,463.00   |
+----------------------+
4 rows in set (0.23 sec)
How to calculate sum in MongoDB with aggregate()?

To get the sum, use $sum along with aggregate(). Let us create a collection with documents −
> db.demo337.insertOne({"Amount":100});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5231e5f8647eb59e56209b")
}
> db.demo337.insertOne({"Amount":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5231e9f8647eb59e56209c")
}
> db.demo337.insertOne({"Amount":400});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5231ebf8647eb59e56209d")
}
Display all documents from a collection with the help of find() method −
> db.demo337.find();
This will produce the following output −
{ "_id" : ObjectId("5e5231e5f8647eb59e56209b"), "Amount" : 100 }
{ "_id" : ObjectId("5e5231e9f8647eb59e56209c"), "Amount" : 500 }
{ "_id" : ObjectId("5e5231ebf8647eb59e56209d"), "Amount" : 400 }
Following is the query to calculate sum in MongoDB −
> db.demo337.aggregate(
...    [
...       {
...          $group:
...          {
...             _id:null,
...             totalAmount: { $sum:"$Amount" }
...          }
...       }
...    ]
... );
This will produce the following output −
{ "_id" : null, "totalAmount" : 1000 }
Select distinct combinations from two columns in MySQL?

To select distinct combinations from two columns, you can use CASE statement. Let us create a table with some columns.
The query to create a table is as follows −
mysql> create table select_DistinctTwoColumns
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> FirstValue char(1),
   -> SecondValue char(1),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.57 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('s','t');
Query OK, 1 row affected (0.12 sec)

mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('t','u');
Query OK, 1 row affected (0.24 sec)

mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','v');
Query OK, 1 row affected (0.12 sec)

mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','t');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from select_DistinctTwoColumns;
The following is the output −
+----+------------+-------------+
| Id | FirstValue | SecondValue |
+----+------------+-------------+
| 1  | s          | t          |
| 2  | t          | u          |
| 3  | u          | v          |
| 4  | u          | t          |
+----+------------+-------------+
4 rows in set (0.00 sec)
Here is the query to select distinct combinations from two column using case statement. The first column is ‘FirstValue’ and the second column name is ‘SecondValue’. The query is as follows −
mysql> SELECT distinct
   -> CASE
   ->    WHEN FirstValue<SecondValue THEN FirstValue
   ->    ELSE SecondValue
   ->    END AS FirstColumn,
   -> CASE
   ->    WHEN FirstValue > SecondValue THEN FirstValue
   ->    ELSE SecondValue
   ->    END AS SecondColumn
   -> FROM select_DistinctTwoColumns;
The following is the output:
+-------------+--------------+
| FirstColumn | SecondColumn |
+-------------+--------------+
| s           | t            |
| t           | u            |
| u           | v            |
+-------------+--------------+
3 rows in set (0.00 sec)
Delete a Node from linked list without head pointer in C++

In this tutorial, we are going to learn how to delete a node without head pointer in a singly linked list.
Let's see the steps to solve the problem.
Write struct with data, and next pointer.
Write struct with data, and next pointer.
Write a function to insert the node into the singly linked list.
Write a function to insert the node into the singly linked list.
Initialize the singly linked list with dummy data.
Initialize the singly linked list with dummy data.
Take a node from the linked list using the next pointer.
Take a node from the linked list using the next pointer.
Move the delete node to the next node.
Move the delete node to the next node.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void deleteNodeWithoutHead(struct Node* deletingNode) {
   if (deletingNode == NULL) {
      return;
   }
   else {
      if (deletingNode->next == NULL) {
         cout << "Can't delete last node without head" << endl;
         return;
      }
      struct Node* temp = deletingNode->next;
      deletingNode->data = temp->data;
      deletingNode->next = temp->next;
      free(temp);
   }
}
void printLinkedList(Node* head) {
   Node* temp = head;
   while (temp) {
      cout << temp->data << " -> ";
      temp = temp->next;
   }
}
void insertNode(struct Node** head_ref, int new_data) {
   struct Node* new_node = new Node();
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
int main() {
   struct Node* head = NULL;
   insertNode(&head, 1);
   insertNode(&head, 2);
   insertNode(&head, 3);
   insertNode(&head, 4);
   insertNode(&head, 5);
   insertNode(&head, 6);
   cout << "Linked List before deletion:" << endl;
   printLinkedList(head);
   Node* del = head->next;
   deleteNodeWithoutHead(del);
   cout << "\nLinked List after deletion:" << endl;
   printLinkedList(head);
   return 0;
}
If you run the above code, then you will get the following result.
Linked List before deletion:
6 -> 5 -> 4 -> 3 -> 2 -> 1 ->
Linked List after deletion:
6 -> 4 -> 3 -> 2 -> 1 ->
If you have any queries in the tutorial, mention them in the comment section.
Matplotlib.ticker.PercentFormatter class in Python

21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.ticker.PercentFormatter class is used to format numbers as a percentage.
Syntax: class matplotlib.ticker.PercentFormatter(xmax=100, decimals=None, symbol=’%’, is_latex=False)
Parameters:
xmax: It is a float value that determines how the number is converted into a percentage.
decimals: It is either an integer value or None. It determines the number of decimal places to place after the point. If None (the default), the number will be computed automatically.
symbol : It is either a string or none that gets appended to the label.
is_latex: It is a boolean value. If False, reserved LaTeX characters in symbol are eliminated.
Example 1:
import pandas as pdimport numpy as npimport matplotlib.ticker as mtickfrom matplotlib.ticker import PercentFormatter  df = pd.DataFrame(np.random.randn(100, 5))  ax = df.plot()ax.yaxis.set_major_formatter(mtick.PercentFormatter(5.0)) 
Output:
Example 2:
import matplotlib.pyplot as pltimport numpy as npimport matplotlib.ticker as mtickfrom matplotlib.ticker import PercentFormatter  data = [8, 12, 15, 17, 18, 18.5]perc = np.linspace(0, 100, len(data))  fig = plt.figure(1, (7, 4))ax = fig.add_subplot(1, 1, 1)  ax.plot(perc, data)  xticks = mtick.PercentFormatter(0.5)ax.xaxis.set_major_formatter(xticks)  plt.show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are Widgets in Tkinter?

22 May, 2020
Tkinter is Python’s standard GUI (Graphical User Interface) package. tkinter provides us with a variety of common GUI elements which we can use to build out interface – such as buttons, menus and various kind of entry fields and display areas. We call these elements Widgets.
In general,  Widget is an element of Graphical User Interface (GUI) that displays/illustrates information or gives a way for the user to interact with the OS.  In Tkinter , Widgets are objects ; instances of classes that represent buttons, frames, and so on.  
Each separate widget is a Python object. When creating a widget, you must pass its parent as a parameter to the widget creation function. The only exception is the “root” window, which is the top-level window that will contain everything else and it does not have a parent. 
Example : 
Python
from tkinter import *    # create root windowroot = Tk()                             # frame inside root windowframe = Frame(root)                    # geometry methodframe.pack()                            # button inside frame which is # inside rootbutton = Button(frame, text ='Geek')  button.pack()                           # Tkinter event looproot.mainloop()                       
Output : 
Tkinter supports the below mentioned core widgets –
Creating a new widget doesn’t mean that it will appear on the screen. To display it, we need to call a special method: either grid, pack(example above), or place. 
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
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 ?
Iterate over a list in Python
Print numbers in sequence using thread synchronization

23 Dec, 2021
The problem is to synchronize n number of threads using pthread library. The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread, ..... print n in nth thread and again repeat from thread 1 infinitely. Prerequisite : Multithreading
Examples : 
Input : Thread count
Output : 1 2 3 ... thread count 1 2 3 ... thread 
count 1 2 3 ... thread count ....

Input : 5
Output : 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 
1 2 3 4 5 1 2 3 4 5 ....
 Below is the implementation:
CPP
// C code to synchronize threads#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t* cond = NULL;  int threads;volatile int cnt = 0;  // function to synchronize threadsvoid* foo(void* arg){    // turn is a basically to identify a thread    int turn = *(int*)arg;      while (1) {        pthread_mutex_lock(&mutex);          // cnt is used to determine which thread should        // enter into critical section(printf() statement)        if (turn != cnt) {              // put all thread except one thread in waiting            // state            pthread_cond_wait(&cond[turn], &mutex);        }          // it's a time to print turn can have        // values starting from 0. Hence + 1        printf("%d ", turn + 1);          // determine which thread need to be scheduled now        if (cnt < threads - 1) {            cnt++;        }        else {            cnt = 0;        }          // wake up next thread        pthread_cond_signal(&cond[cnt]);        pthread_mutex_unlock(&mutex);    }      return NULL;}  // Driver codeint main(){    pthread_t* tid;    volatile int i;    int* arr;      printf("\nEnter number of threads: ");    scanf("%d", &threads);      // allocate memory to cond (conditional variable),    // thread id's and array of size threads    cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)                                   * threads);    tid = (pthread_t*)malloc(sizeof(pthread_t) * threads);    arr = (int*)malloc(sizeof(int) * threads);      // Initialize cond (conditional variable)    for (int i = 0; i < threads; i++) {        if (pthread_cond_init(&cond[i], NULL) != 0) {            perror("pthread_cond_init() error");            exit(1);        }    }      // create threads    for (i = 0; i < threads; i++) {        arr[i] = i;        pthread_create(&tid[i], NULL, foo, (void*)&arr[i]);    }      // waiting for thread    for (i = 0; i < threads; i++) {        pthread_join(tid[i], NULL);    }      return 0;}
Output :  
 
jeff1jeffo
kalrap615
nishanthsmenon
cpp-multithreading
Processes & Threads
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strdup() and strndup() functions in C/C++

23 Jun, 2022
The strdup() and strndup() functions are used to duplicate a string. strdup() : Syntax : char *strdup(const char *s); This function returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by s. The memory obtained is done dynamically using malloc and hence it can be freed using free(). It returns a pointer to the duplicated string s.Below is the C implementation to show the use of strdup() function in C: 
C
// C program to demonstrate strdup()#include<stdio.h>#include<string.h> int main(){    char source[] = "GeeksForGeeks";     // A copy of source is created dynamically    // and pointer to copy is returned.    char* target = strdup(source);     printf("%s", target);    return 0;}
Output: 
GeeksForGeeks
strndup() : syntax: char *strndup(const char *s, size_t n); This function is similar to strdup(), but copies at most n bytes. Note: If s is longer than n, then only n bytes are copied, and a NULL (‘\0’) is added at the end.Below is the C implementation to show the use of strndup() function in C: 
C
// C program to demonstrate strndup()#include<stdio.h>#include<string.h> int main(){    char source[] = "GeeksForGeeks";     // 5 bytes of source are copied to a new memory    // allocated dynamically and pointer to copied    // memory is returned.    char* target = strndup(source, 5);     printf("%s", target);    return 0;}
Output:
Geeks
Let us see the differences in a tabular form -:
Its syntax is -:
char *strndup( const char *str, size_t size );
It takes two parameters that are -:1.pointer to the null-terminated byte string to duplicate
2. max number of bytes to copy from str
Reference: Linux man(7)This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
MattCT
riusjeff
koushikpmv
mayank007rawa
C-Library
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.