code-rag-bench/online-tutorials huggingface dataset:
p5.js | createButton() Function

11 Jul, 2019
The createButton() function is used to create a button element in the DOM (Document Object Model). The .size() function is used to set the size of button element. The .mousePressed() function is used to specify the behavior of mouse button when pressing it.Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file.
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script>
Syntax:
createButton( label, value )
Parameters: This function accepts two parameters as mentioned above and described below:
label: This parameter holds the label displayed on the button.
value: This parameter holds the value of the button.
Return Value: It returns a pointer element holding the created node object.
Note: This button element can be linked with various JavaScript events like mouse pressed, mouse clicked, mouse released, etc.
Example: This example uses createButton() function to change the background color using the p5.js button element.
// Create a variable for button objectvar color_button;   // Create a function to change the background-colorfunction change_background() {          // Pick a random number for r value    r = random(255);          // Pick a random number for g value    g = random(255);          // Pick a random number for b value    b = random(255);          // Set a random background-color    background(r, g, b);}   function setup() {          // Create a canvas    createCanvas(400, 400);          // Set an initial background-color    background(50);          // Create the button    color_button = createButton("Change Color");          // Position the button    color_button.position(150, 200);          // When the button is clicked change_background()    // function is called    color_button.mouseClicked(change_background);}
Output:
After clicking the button:
After clicking the button again:
Reference: https://p5js.org/reference/#/p5/createButton
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Java Program to Get Today’s Date

06 Jun, 2021
Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, which is how to get today’s or current date using Java.
Methods:
There are two ways to get today’s date as listed below:
Using now() method of LocalDate classUsing java.sql.Date() function
Using now() method of LocalDate class
Using java.sql.Date() function
Let us go through them one by one to get a fair understanding of them.
Method 1: Using now() method of LocalDate class
now() method of a LocalDate class used to obtain the current date from the system clock in the default time-zone. This method will return LocalDate based on the system clock with the default time-zone to obtain the current date.
Example 
Java
// Java Program to Get Today's Date// Using now() method of LocalDate class  // Importing required classesimport java.text.SimpleDateFormat;import java.util.Date;  // Main class// Day of Todaypublic class GFG {      // Main Driver Method    public static void main(String[] args) {          // Printing Today's date by calling        // java.time.LocalDate.now() function        System.out.println(java.time.LocalDate.now());    }}
2021-05-31

Method 2: Using java.sql.Date() function
Java
// Java Program to Get Today's Date// Using java.sql.Date() function  // Importing required classesimport java.text.SimpleDateFormat;import java.util.Date;  // Main classpublic class GFG {      // Main Driver Method    public static void main(String[] args)    {          // Printing Today's date by calling        // java.sql.Date() function        long millis = System.currentTimeMillis();        java.sql.Date date = new java.sql.Date(millis);        System.out.println(date);    }}
2021-05-31

Java-Date-Time
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to read/write data from/to .properties file in Java?

The .properties is an extension in java which is used to store configurable application. It is represented by the Properties class in Java, you can store a properties file and read from it using the methods of this class. This class inherits the HashTable class.
Creating a .properties file −
To create a properties file −
Instantiate the Properties class.
Instantiate the Properties class.
Populate the created Properties object using the put() method.
Populate the created Properties object using the put() method.
Instantiate the FileOutputStream class by passing the path to store the file, as a parameter.
Instantiate the FileOutputStream class by passing the path to store the file, as a parameter.
The Following Java program creates a properties file in the path D:/ExampleDirectory/
 Live Demo
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class CreatingPropertiesFile {
   public static void main(String args[]) throws IOException {
      //Instantiating the properties file
      Properties props = new Properties();
      //Populating the properties file
      props.put("Device_name", "OnePlus7");
      props.put("Android_version", "9");
      props.put("Model", "GM1901");
      props.put("CPU", "Snapdragon855");
      //Instantiating the FileInputStream for output file
      String path = "D:\\ExampleDirectory\\myFile.properties";
      FileOutputStream outputStrem = new FileOutputStream(path);
      //Storing the properties file
      props.store(outputStrem, "This is a sample properties file");
      System.out.println("Properties file created......");
   }
}
Properties file created......
If you observe the output file you can see the created contents as −
You can store the properties file in XML format using the stored XML() method.
 Live Demo
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class CreatingPropertiesFile {
   public static void main(String args[]) throws IOException {
      //Instantiating the properties file
      Properties props = new Properties();
      //Populating the properties file
      props.put("Device_name", "OnePlus7");
      props.put("Android_version", "9");
      props.put("Model", "GM1901");
      props.put("CPU", "Snapdragon855");
      //Instantiating the FileInputStream for output file
      String outputPath = "D:\\ExampleDirectory\\myFile.xml";
      FileOutputStream outputStrem = new FileOutputStream(outputPath);
      //Storing the properties file in XML format
      props.storeToXML(outputStrem, "This is a sample properties file");
      System.out.println("Properties file created......");
   }
}
Properties file created......
ReactJS – bind() method

In this article, we are going to see how to pass arguments to a function in a React application
React has a predefined bind() method which we can use to pass the arguments to a function in the class based components.
this.func.bind(this,[args...])
It accepts two parameters, this keyword and the arguments. 'this' keyword is used to pass the reference to that function while the second parameter is passed as arguments to the function.
In this example, we will build a React application that passes the arguments to a function when a button is clicked.
App.jsx
import React from 'react';

class App extends React.Component {
   constructor(){
      super();
      this.state = {
         name: 'Rahul Bansal',
         email: null,
      };
   }

   fetch = (email) => {
      this.setState({ email: email });
   };
   render() {
      return (
         <div>
            <h1>Name: {this.state.name}</h1>
            <h1>{this.state.email ? 'Email: ${this.state.email}' : null}</h1>
            <button onClick={this.fetch.bind(this, 'qwerty@gmail.com')}>
               Fetch Email
            </button>
         </div>
      );
   }
}
export default App;
How to sort one-dimensional array in ascending order using non-static method?

Set the unsorted array first.
int[] list = {87, 45, 56, 22, 84, 65};
Now use a nested for loop to sort the list, which is passed to a function.
for(int i=0; i< arr.Length; i++) {
   for(int j=i+1; j<arr.Length; j++) {
      if(arr[i]>=arr[j]) {
         temp=arr[j];
         arr[j]=arr[i];
         arr[i]=temp;
      }
   }
   Console.Write(arr[i] + " ");
}
The following is the complete code to sort one-dimensional array in ascending order using non-static method.
 Live Demo
using System;
namespace Demo {
   public class MyApplication {
      public static void Main(string[] args) {
         int[] list = {87, 45, 56, 22, 84, 65};
         Console.WriteLine("Original Unsorted List");
         foreach (int i in list) {
            Console.Write(i + " ");
         }
         MyApplication m = new MyApplication();
         m.sortFunc(list);
      }
      public void sortFunc(int[] arr) {
         int temp = 0;
         Console.WriteLine("\nSorted List");
         for(int i=0; i< arr.Length; i++) {
            for(int j=i+1; j<arr.Length; j++) {
               if(arr[i]>=arr[j]) {
                  temp=arr[j];
                  arr[j]=arr[i];
                  arr[i]=temp;
               }
            }
            Console.Write(arr[i] + " ");
         }
      }
   }
}
Original Unsorted List
87 45 56 22 84 65
Sorted List
22 45 56 65 84 87
How to execute a cube of numbers of a given array in JavaScript?

To find the cubes of elements of given array we need to run a for loop to access each and every element and we need to use "=" operator to replace elements with their cubes.To get the desired values the below steps need to be followed.
1) Declared an array a = [1,2,3,4,5]
2) For loop was introduced to access each and every element in the array(a[i]).
3) Inside for loop "=" operator is used to replace the element with their cubic values(a[i]*a[i]*a[i]).
so, from the above steps the output obtained will be 1,8,27,64,125.By following the above steps we can get not only cubes but also any power of elements in a provided array.
Live Demo
<html>
<body>
<script>
   var a = [1,2,3,4,5];
   for ( var i = 0; i < a.length;i++) {
      a[i] = a[i]*a[i]*a[i];
   }
   document.write(a);
</script>
</body>
</html>
[1, 8, 27, 64, 125]
Algorithm to get the combinations of all items in array JavaScript

We are required to write a JavaScript function that takes in an array of string literals. The function should generate and return all possible combinations of the strings in the array.
For example −
If the input array is −
const arr = ['a', 'b', 'c', 'd'];
Then the output should be −
const output = ["a", "ab", "abc", "abcd", "abd", "ac", "acd", "ad", "b", "bc", "bcd", "bd", "c", "cd", "d"];
const getCombinations = (arr = []) => {
   const combine = (sub, ind) => {
      let result = []
      let i, l, p;
      for (i = ind, l = arr.length; i < l; i++) {
         p = sub.slice(0);
         p.push(arr[i]);
         result = result.concat(combine(p, i + 1));
         result.push(p.join(''));
      };
      return result;
   }
   return combine([], 0);
};
console.log(getCombinations(["a", "b", "c", "d"]));
And the output in the console will be −
[
   'abcd', 'abc', 'abd',
   'ab', 'acd', 'ac',
   'ad', 'a', 'bcd',
   'bc', 'bd', 'b',
   'cd', 'c', 'd'
]
Array Copy in C#

Use the array. copy method in C# to copy a section of one array to another.
Our original array has 10 elements −
int [] n = new int[10]; /* n is an array of 10 integers */
Our new array that would copy a section of array 1 has 5 elements −
int [] m = new int[5]; /* m is an array of 5 integers */
The array.copy() method allow you to add the source and destination array. With that, include the size of the section of the first array that includes in the second array.
You can try to run the following to implement Array copy in C# −
Live Demo
using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[10]; /* n is an array of 10 integers */
         int [] m = new int[5]; /* m is an array of 5 integers */
         for ( int i = 0; i < 10; i++ ) {
            n[i] = i + 100;
         }
         Console.WriteLine("Original Array...");
         foreach (int j in n ) {
            int i = j-100;
            Console.WriteLine("Element[{0}] = {1}", i, j);
         }
         Array.Copy(n, 0, m, 0, 5);
         Console.WriteLine("New Array...");
         foreach (int res in m) {
            Console.WriteLine(res);
         }
         Console.ReadKey();
      }
   }
}
Original Array...
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
New Array...
100
101
102
103
104
TestNG - Exception Test

TestNG provides an option of tracing the exception handling of code. You can test whether a code throws a desired exception or not. Here the expectedExceptions parameter is used along with the @Test annotation. Now, let's see @Test(expectedExceptions) in action.
Create a java class to be tested, say, MessageUtil.java in /work/testng/src. Add an error condition inside the printMessage() method.
/*
* This class prints the given message on console.
*/
public class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   public MessageUtil(String message) {
      this.message = message;
   }

   // prints the message
   public void printMessage() {
      System.out.println(message);
      int a =0;
      int b = 1/a;
   }

   // add "Hi!" to the message
   public String salutationMessage() {
      message = "Hi!" + message;
      System.out.println(message);
      return message;
   }
}
Create a java test class, say, ExpectedExceptionTest.java in /work/testng/src.
Create a java test class, say, ExpectedExceptionTest.java in /work/testng/src.
Add an expected exception  ArithmeticException to the testPrintMessage() test case.
Add an expected exception  ArithmeticException to the testPrintMessage() test case.
Following are the contents of ExpectedExceptionTest.java.
import org.testng.Assert;
import org.testng.annotations.Test;

public class ExpectedExceptionTest {
   String message = "Manisha";
   MessageUtil messageUtil = new MessageUtil(message);

   @Test(expectedExceptions = ArithmeticException.class)
   public void testPrintMessage() {
      System.out.println("Inside testPrintMessage()");
      messageUtil.printMessage();
   }

   @Test
   public void testSalutationMessage() {
      System.out.println("Inside testSalutationMessage()");
      message = "Hi!" + "Manisha";
      Assert.assertEquals(message,messageUtil.salutationMessage());
   }
}
Create testng.xml in /work/testng/src to execute test case(s).
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">
   <test name = "test1">
      <classes>
         <class name = "ExpectedExceptionTest" />
      </classes>
   </test>
</suite>
Compile the MessageUtil, Test case classes using javac.
/work/testng/src$ javac MessageUtil.java TestJunit.java

Now, run the Test Runner, which will run test cases defined in the provided Test Case class.
/work/testng/src$ java org.testng.TestNG testng.xml

Verify the output. testPrintMessage() test case will be passed.
Inside testPrintMessage()
Manisha
Inside testSalutationMessage()
Hi!Manisha

===============================================
Suite1
Total tests run: 2, Failures: 0, Skips: 0
===============================================


    38 Lectures 
     4.5 hours 

 Lets Kode It

    15 Lectures 
     1.5 hours 

 Quaatso Learning

    28 Lectures 
     3 hours 

 Dezlearn Education
 Print
 Add Notes
 Bookmark this page
How to use Unicode and Special Characters in Tkinter?

Sometimes we need to add unicode and special charset in our Tkinter application. We can add unicode characters in our labels or widgets concatenating the signature as, u ‘/<Unicode of Character>’. You can find the list of all unicode characters from here
In this example, we will add a unicode character in the button widget.
# Import the required Libraries
from tkinter import *

#Create an instance of tkinter frame
win= Tk()
win.geometry("700x200")

#Create a button

Button(win, text='Click'+u'\u01CF', font=('Poppins bold',
10)).pack(pady=20)

#Keep running the window or frame
win.mainloop()
Running the above code will create a button with a unicode character (u01CF).
Java Program for Extended Euclidean algorithms

05 Dec, 2018
GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors.
// Java program to demonstrate working of extended// Euclidean Algorithm  import java.util.*;import java.lang.*;  class GFG {    // extended Euclidean Algorithm    public static int gcdExtended(int a, int b, int x, int y)    {        // Base Case        if (a == 0) {            x = 0;            y = 1;            return b;        }          int x1 = 1, y1 = 1; // To store results of recursive call        int gcd = gcdExtended(b % a, a, x1, y1);          // Update x and y using results of recursive        // call        x = y1 - (b / a) * x1;        y = x1;          return gcd;    }      // Driver Program    public static void main(String[] args)    {        int x = 1, y = 1;        int a = 35, b = 15;        int g = gcdExtended(a, b, x, y);        System.out.print("gcd(" + a + ", " + b + ") = " + g);    }}// Code Contributed by Mohit Gupta_OMG <(0-o)>
gcd(35, 15) = 5

Please refer complete article on Basic and Extended Euclidean algorithms for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
Java Program to Read a File to String
Comparing two ArrayList In Java
SHA-1 Hash
Java Program to Convert File to a Byte Array
Java Program to Find Sum of Array Elements
Java Program for compound interest

07 Feb, 2018
Compound Interest formula:
Formula to calculate compound interest annually is given by:Compound Interest = P(1 + R/100)rWhere,P is principle amountR is the rate andT is the time span
Example:
Input : Principle (amount): 1200
        Time: 2
        Rate: 5.4
Output : Compound Interest = 1333.099243

// Java program to find compound interest for// given values.import java.io.*;  class GFG{    public static void main(String args[])    {        double principle = 10000, rate = 10.25, time = 5;          /* Calculate compound interest */        double CI = principle *                    (Math.pow((1 + rate / 100), time));                  System.out.println("Compound Interest is "+ CI);    }}// This code is contributed by Anant Agarwal.
Please refer complete article on Program to find compound interest for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between BSS and ESS

10 Nov, 2020
1. Basic Service Set (BSS) :Basic Service Set (BSS), as name suggests, is a group or set of all stations that communicate with each together. Here, stations are considered as computers or components connected to wired network.
2. Extended Service Set (ESS) :Extended Service Set (ESS), as name suggests, is a group of BSSs or one or more interconnected BSS along with their wired network.
Difference between BSS and ESS :
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Python | math.tan() function

20 Mar, 2019
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.tan() function returns the tangent of value passed as argument. The value passed in this function should be in radians.
Syntax: math.tan(x)
Parameter:x : value to be passed to tan()
Returns: Returns the tangent of value passed as argument
Code #1:
# Python code to demonstrate the working of tan()     # importing "math" for mathematical operations import math     a = math.pi / 6     # returning the value of tangent of pi / 6 print ("The value of tangent of pi / 6 is : ", end ="") print (math.tan(a)) 
 Code #2:
# Python program showing # Graphical representation of # tan() function import mathimport numpy as npimport matplotlib.pyplot as plt   in_array = np.linspace(0, np.pi, 10)   out_array = []  for i in range(len(in_array)):    out_array.append(math.tan(in_array[i]))    i += 1     print("in_array : ", in_array) print("\nout_array : ", out_array)   # red for numpy.sin() plt.plot(in_array, out_array, color = 'red', marker = "o") plt.title("math.tan()") plt.xlabel("X") plt.ylabel("Y") plt.show() 
in_array : [0. 0.34906585 0.6981317 1.04719755 1.3962634 1.745329252.0943951 2.44346095 2.7925268 3.14159265]
out_array : [0.0, 0.36397023426620234, 0.8390996311772799, 1.7320508075688767, 5.671281819617707, -5.671281819617711, -1.7320508075688783, -0.8390996311772804, -0.36397023426620256, -1.2246467991473532e-16]
Python math-library-functions
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
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
T-SQL - Date Functions

Following is the list of date functions in MS SQL Server.
It will return the current date along with time.
Syntax for the above function −
GETDATE()

The following query will return the current date along with time in MS SQL Server.
Select getdate() as currentdatetime
It will return the part of date or time.
Syntax for the above function −
DATEPART(datepart, datecolumnname)

Example 1 − The following query will return the part of current date in MS SQL Server.
Select datepart(day, getdate()) as currentdate
Example 2 − The following query will return the part of current month in MS SQL Server.
Select datepart(month, getdate()) as currentmonth
It will display the date and time by add or subtract date and time interval.
Syntax for the above function −
DATEADD(datepart, number, datecolumnname)

The following query will return the after 10 days date and time from the current date and time in MS SQL Server.
Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime 
It will display the date and time between two dates.
Syntax for the above function −
DATEDIFF(datepart, startdate, enddate)

The following query will return the difference of hours between 2015-11-16 and 2015-11-11 dates in MS SQL Server.
Select datediff(hour, 2015-11-16, 2015-11-11) as 
differencehoursbetween20151116and20151111 
It will display the date and time in different formats.
Syntax for the above function −
CONVERT(datatype, expression, style)

The following queries will return the date and time in different format in MS SQL Server.
How to convert rgb() color string into an object in JavaScript ?

06 Apr, 2021
Given a color in the form of rgb( ) or rgba() and the task is to convert it into an object where the keys are the color names and values are the color values.
Input:    rgb(242, 52, 110)
Output: {
   red: 242,
   green: 52,
   blue: 110
}

Input:    rgba(255, 99, 71, 0.5)
Output: {
  red: 255,
  green: 99,
  blue: 71,
  alpha: 0.5
}
Approach: To achieve this we use the following approach.
Store the color in a variable named rgb.
Create an array named colors that contain the names of the colors red, green, blue, and alpha.
Create a variable names colorArr in which we store the color values of the input rgb. For example: [“255”, “99”, “71”, 0.5], to achieve this we slice the rgb from where the “(“ present to from where the “)” present. Now you got the string “255, 99, 71, 0.5”. Now split the array from where the “, ” present. Now you get the array [“255′′, ’99”, “71”, “0.5”].
Now create an empty object.
Apply forEach loop on the colorArr and for every iteration insert the name of color and value of the color to the object.
Now print the object.
Javascript
<script>let rgb = "rgba(255, 99, 71, 0.5)"  let colors = ["red", "green", "blue", "alpha"]  // Getting the index of "(" and ")" // by using the indexOf() methodlet colorArr = rgb.slice(    rgb.indexOf("(") + 1,     rgb.indexOf(")")).split(", ");  let obj = new Object();  // Insert the values into objcolorArr.forEach((k, i) => {    obj[colors[i]] = k})  console.log(obj)</script>
Output:
{
  alpha: "0.5",
  blue: "71",
  green: "99",
  red: "255"
}
Javascript
<script>function rgbToObj(rgb) {      let colors = ["red", "green", "blue", "alpha"]      let colorArr = rgb.slice(        rgb.indexOf("(") + 1,         rgb.indexOf(")")    ).split(", ");      let obj = new Object();      colorArr.forEach((k, i) => {        obj[colors[i]] = k    })      return obj;}    console.log(rgbToObj("rgb(255, 99, 71)"))console.log(rgbToObj("rgb(255, 99, 71, 0.5)"))</script>
Output:
{
  blue: "71",
  green: "99",
  red: "255"
}

{
  alpha: "0.5",
  blue: "71",
  green: "99",
  red: "255"
}
JavaScript-Methods
JavaScript-Properties
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Find the geometric mean of a given Pandas DataFrame

05 Sep, 2020
In this article, we will discuss how to find the geometric mean of a given DataFrame. Generally geometric mean of nth numbers is the nth root of their product.
It can found using the scipy.stats.gmean() method. This function calculates the geometric mean of the array elements along the specified axis of the array (list in python).
Syntax:
scipy.stats.gmean(array, axis=0, dtype=None)
Approach :
Import module
Create Pandas DataFrame
Create a new column for the geometric mean
Find the geometric mean with scipy.stats.gmean()
Store into a new column
Display DataFrame
Step-by-Step Implementation :
Step 1: Importing module and Making Dataframe.
Python
# importing moduleimport pandas as pdimport numpy as npfrom scipy import stats  # Create a DataFramedf = pd.DataFrame({    'Name': ['Monty', 'Anurag', 'Kavya', 'Hunny', 'Saurabh',             'Shubham', 'Ujjawal', 'Satyam', 'Prity', 'Tanya',              'Amir', 'donald'],    'Match1_score': [52, 87, 35, 14, 41, 71, 95, 83, 22, 82, 11, 97],    'match2_score': [45, 80, 62, 53, 49, 82, 36, 97, 84, 93, 39, 59]})  # Display DataFramedf
Output :
Step 2:  Create an empty DataFrame column.
Python3
# Creating empty column in DataFramedf['Geometric Mean'] = Nonedf
Output :
Step 3: Find Geometric mean with scipy.stats.gmean()  and store it into a new column.
Python3
# Computing geometric mean# Storing into a DataFrame columndf['Geometric Mean'] = stats.gmean(df.iloc[:, 1:3], axis=1)df
Output :
Python pandas-dataFrame
Python Pandas-exercise
Python scipy-stats-functions
Python-pandas
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create button to open SMS compose to a phone number using HTML ?

08 Jun, 2020
Sometimes, when you search for a number on the web, you might want to SMS to it directly from the web page instead of noting it down and then messaging to it. It becomes quite convenient for the user. Making an SMS link is very easy in HTML. Here, we will see how to make the SMS link on a webpage.
Approach: Using <a> href attribute: Enter the phone number in place of the URL and add sms: before it to make an SMS link. Add the text between the tags that will appear as the clickable link.
For Single Recipient:Syntax:
<a href="sms:(countrycode)(number)"> Text </a>
Example:
<!DOCTYPE html><html>  <head>    <title>        Create button to open SMS         compose to a phone number    </title></head>  <body>    <p>        For any queries you can text        us at the below number:     </p>          <a href="sms:+911234567890">        +91-123-4567-890    </a></body>  </html>
Output:Before clicking the link:After clicking the link:
For Multiple Recipient:Syntax:
<a href="sms:(countrycode)(number), 
    (countrycode)(number), ...."> Text </a>
Example:
<!DOCTYPE html><html>  <head>    <title>        Create button to open SMS        compose to a phone number    </title></head>  <body>    <p>        Send text to multiple         recipients:     </p>      <a href="sms:+911234567890,             +11234567890">        Send a SMS    </a></body>  </html>
Output:Before clicking the link:After clicking the link:
HTML-Misc
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to make elements float to center?

19 May, 2022
The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout. So, we can center the elements by using position property.
Example 1: This example set the position of elements exactly at the center of the screen. 
html
<!DOCTYPE html><html> <head>    <title>        Make float to center to element    </title>         <!-- Style to set element float        to center -->    <style>        .Center {            width:200px;            height:200px;            position: fixed;            background-color: blue;            top: 50%;            left: 50%;            margin-top: -100px;            margin-left: -100px;        }    </style></head> <body>    <div class="Center"></div></body> </html>                   
Output:
  
Example: This example set the position of text float elements exactly at the center of the screen. 
html
<!DOCTYPE html><html> <head>         <!-- Style to set text-element        to center -->    <style>        .center {            text-align-last: center;            border: 2px solid black;        }    </style></head> <body>    <h2 style = "text-align:center">        Text is centered:    </h2>         <div class="center">        <p>            <font color="green">                GeeksForGeeks A Computer                Science Portal for Geeks            </font>        </p>    </div></body> </html>                   
Output:
 
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
hardikkoriintern
CSS-Misc
HTML-Misc
Picked
Web-Programs
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Matplotlib.pyplot.subplot2grid() in python

19 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.pyplot.subplot2grid() function give additional flexibility in creating axes object at a specified location inside a grid. It also helps in spanning the axes object across multiple rows or columns. In simpler words, this function is used to create multiple charts within the same figure. It is a sub-figure layout manager.
Syntax : Plt.subplot2grid(shape, location, rowspan, colspan)
Parameters :
shape: As the name suggests it is used to define the shape of the grid to be plotted within the graph. It is a required argument and is generally passed in as a list or tuple of two numbers which are responsible for the layout of the grid with the first number being the number of rows and the second number as the number of columns.
location (loc): This is the second mandatory argument that this function takes. Similar to the shape argument it is also a required argument and is generally passed in as a list or tuple of two numbers. It is used for specifying the row and column number to place the sub-plot. It is also important to note that the indexes start from 0. So (0, 0) would be the cell in the first row and the first column of the grid.
rowspan: Once the grid layout is set and the starting index is decided using location(loc) one can expand the selection to take up more rows with this argument. This is an optional parameter and has a default value of 1.
colspan: Similar to rowspan it is used to expand the selection to take up more columns. It is also an optional parameter with default value of 1.
Example 1:
import matplotlib.pyplot as plt    fig = plt.figure()  axes1 = plt.subplot2grid((4, 4), (0, 0),                         colspan = 4)  axes2 = plt.subplot2grid((4, 4), (1, 0),                         colspan = 3)  axes3 = plt.subplot2grid((4, 4), (1, 2),                          rowspan = 3)  axes4 = plt.subplot2grid((4, 4), (2, 0))axes5 = plt.subplot2grid((4, 4), (2, 1))  fig.tight_layout()
Output :
Example 2:
import randomimport matplotlib.pyplot as pltfrom matplotlib import style    style.use('fivethirtyeight')  fig = plt.figure()    # helper function to plot the linesdef helper():          xs = []    ys = []      for i in range(10):        x = i        y = random.randrange(10)          xs.append(x)        ys.append(y)    return xs, ys  axes1 = plt.subplot2grid ((7, 1), (0, 0),                          rowspan = 2,                           colspan = 1)  axes2 = plt.subplot2grid ((7, 1), (2, 0),                          rowspan = 2,                          colspan = 1)  axes3 = plt.subplot2grid ((7, 1), (4, 0),                           rowspan = 2,                           colspan = 1)  x, y = helper()axes1.plot(x, y)  x, y = helper()axes2.plot(x, y)  x, y = helper()axes3.plot(x, y)
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sklearn.cross_decomposition.PLSRegression() function in Python

03 Jun, 2021
PLS regression is a Regression method that takes into account the latent structure in both datasets. Partial least squares regression performed well in MRI-based assessments for both single-label and multi-label learning reasons. PLSRegression acquires from PLS with mode=”A” and deflation_mode=”regression”. Additionally, known PLS2 or PLS in the event of a one-dimensional response.
Syntax: class sklearn.cross_decomposition.PLSRegression(n_components=2, *, scale=True, max_iter=500, tol=1e-06, copy=True) 
Parameters:
This function accepts five parameters which are mentioned above and defined below:
n_components:<int>: Its default value is 2, and it accepts the number of components that are needed to keep.
scale:<bool>: Its default value is True, and it accepts whether to scale the data or not.
max_iteran :<int>: Its default value is 500, and it accepts the maximum number of iteration of the NIPALS inner loop.
tol: <non-negative real>: Its default value is 1e-06, and it accepts tolerance used in the iterative algorithm.
copy:<bool>: Its default value is True, and it shows that deflection should be done on a copy. Don’t care about side effects when the default value is set True.
Return Value: PLSRegression is an approach for predicting response.
The below Example illustrates the use of the PLSRegression() Model.
Example:
Python3
import numpy as npimport pandas as pdfrom sklearn import datasetsimport matplotlib.pyplot as pltfrom sklearn.cross_decomposition import PLSRegressionfrom sklearn.model_selection import train_test_split  # load boston data using sklearn datasetsboston = datasets.load_boston() # separate data and target valuesx = boston.datay = boston.target # tabular data structure with labeled axes# (rows and columns) using DataFramedf_x = pd.DataFrame(x, columns=boston.feature_names)df_y = pd.DataFrame(y) # create PLSRegression modelpls2 = PLSRegression(n_components=2) # split datax_train, x_test, y_train, y_test = train_test_split(    df_x, df_y, test_size=0.30, random_state=1) # fit the modelpls2.fit(x_train, y_train) # predict the valuesY_pred = pls2.predict(x_test) # plot the predicted Valuesplt.plot(Y_pred)plt.xticks(rotation=90)plt.show() # print the predicted valueprint(Y_pred)
 
 
Output:
 
Plot the Predicted value using PLSRegression
 
 
Print the predicted value using trained model
 
 
clintra
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 PIL | UnsharpMask() method

08 Sep, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.PIL.ImageFilter.UnsharpMask() method applies the Unsahrp mask filter to the input image.
Syntax: PIl.ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)Parameters: radius: Blur Radius percent: Unsharp strength, in percent threshold: Threshold controls the minimum brightness change that will be sharpened  
See this digital unsharp masking for the explanation of the parametersImage used: 
Python3
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter      # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")      # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 3, percent = 200, threshold = 5))      im2.show()
Output: 
Python3
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter      # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")      # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 4, percent = 500, threshold = 8))      im2.show()
Output: 
Python3
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter      # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")      # applying the unsharpmask methodim2 = im1.filter(ImageFilter.UnsharpMask(radius = 5, percent = 500, threshold = 10))      im2.show()
Output: 
 
gtea
Image-Processing
Python-pil
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
numpy.fix() in Python

04 Dec, 2020
The numpy.fix() is a mathematical function that rounds elements of the array to the nearest integer towards zero. The rounded values are returned as floats.
Syntax : numpy.fix(a, b = None)Parameters :
a : [array_like] Input array to be floated.b : [ndarray, optional] Output array.
Return : The array of rounded numbers
 Code #1 : Working
# Python program explaining# fix() function  import numpy as np  in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array)  fixoff_values = np.fix(in_array)print ("\nRounded values : \n", fixoff_values)    in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array)  fixoff_values = np.fix(in_array)print ("\nRounded values : \n", fixoff_values)  in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array)  fixoff_values = np.fix(in_array)print ("\nRounded values : \n", fixoff_values)
Output :
Input array : 
 [0.5, 1.5, 2.5, 3.5, 4.5, 10.1]

Rounded values : 
 [  0.   1.   2.   3.   4.  10.]

Input array : 
 [0.53, 1.54, 0.71]

Rounded values : 
 [ 0.  1.  0.]

Input array : 
 [0.5538, 1.33354, 0.71445]

Rounded values : 
 [ 0.  1.  0.]
 
Code #2 : Working
# Python program explaining# fix() function  import numpy as np  in_array = [1, 4, 7, 9, 12]print ("Input array : \n", in_array)  fixoff_values = np.fix(in_array)print ("\nRounded values : \n", fixoff_values)    in_array = [133, 344, 437, 449, 12]print ("\nInput array : \n", in_array)  fixoff_values = np.fix(in_array)print ("\nRounded values upto 2: \n", fixoff_values)  in_array = [133, 344, 437, 449, 12]print ("\nInput array : \n", in_array)  fixoff_values = np.fix(in_array)print ("\nRounded values upto 3: \n", fixoff_values)
Output :
Input array : 
 [1, 4, 7, 9, 12]

Rounded values : 
 [  1.   4.   7.   9.  12.]

Input array : 
 [133, 344, 437, 449, 12]

Rounded values upto 2: 
 [ 133.  344.  437.  449.   12.]

Input array : 
 [133, 344, 437, 449, 12]

Rounded values upto 3: 
 [ 133.  344.  437.  449.   12.]
 References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.fix.html#numpy.fix.
Python numpy-Mathematical Function
Python-numpy
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Ints contains() function | Guava | Java

26 Jul, 2021
Guava’s Ints.contains() returns true if target is present as an element anywhere in array.Syntax:  
public static boolean 
  contains(int[] array, int target)
Parameters: This method accepts following parameters:  
array: An array of int values, possibly empty.
target: A primitive int value.
Return Value: This method returns a boolean value. It returns True if array[i] == target for some value of i.Example 1: 
Java
// Java code to show implementation of// Guava's Ints.contains() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG {     // Driver's code    public static void main(String[] args)    {         // Creating an Integer array        int[] arr = { 5, 4, 3, 2, 1 };         int target = 3;         // Using Ints.contains() method to search        // for an element in the array. The method        // returns true if element is found, else        // returns false        if (Ints.contains(arr, target))            System.out.println("Target is present"                               + " in the array");        else            System.out.println("Target is not present"                               + " in the array");    }}
Target is present in the array
 
Example 2: 
Java
// Java code to show implementation of// Guava's Ints.contains() method import com.google.common.primitives.Ints;import java.util.Arrays; class GFG {     // Driver's code    public static void main(String[] args)    {         // Creating an Integer array        int[] arr = { 2, 4, 6, 8, 10 };         int target = 7;         // Using Ints.contains() method to search        // for an element in the array. The method        // returns true if element is found, else        // returns false        if (Ints.contains(arr, target))            System.out.println("Target is present"                               + " in the array");        else            System.out.println("Target is not present"                               + " in the array");    }}
Target is not present in the array
 
Reference: https://google.github.io/guava/releases/22.0/api/docs/com/google/common/primitives/Ints.html#contains-int:A-int- 
manikarora059
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.