code-rag-bench/online-tutorials huggingface dataset:
How to find the absolute distance between columns of an R data frame?

The absolute distance can be found by calculating the difference between column values. And if we want the distance to be absolute then we would be need to use abs function. For example, suppose we have a data frame df that contain columns x and y then the absolute distance can be found by using dfAbsoluteDistance<−abs(dfy-df$x).
Consider the below data frame:
Live Demo
> set.seed(274)
> x1<-rpois(20,5)
> y1<-rpois(20,8)
> df1<-data.frame(x1,y1)
> df1
  x1 y1
1 6 11
2 1 4
3 4 2
4 7 12
5 4 5
6 6 10
7 6 14
8 6 8
9 2 11
10 3 8
11 3 8
12 2 6
13 1 6
14 2 10
15 4 4
16 6 11
17 4 10
18 9 3
19 3 1
20 9 8
Creating a new column with absolute distance:
> df1$Absolute_Distance<-abs(df1$y1-df1$x1)
> df1
  x1 y1 Absolute_Distance
1 6 11      5
2 1 4       3
3 4 2       2
4 7 12      5
5 4 5       1
6 6 10      4
7 6 14      8
8 6 8       2
9 2 11      9
10 3 8      5
11 3 8      5
12 2 6      4
13 1 6      5
14 2 10     8
15 4 4      0
16 6 11     5
17 4 10     6
18 9 3      6
19 3 1      2
20 9 8      1
Live Demo
> x2<-sample(0:9,20,replace=TRUE)
> y2<-sample(1:10,20,replace=TRUE)
> df2<-data.frame(x2,y2)
> df2
 x2 y2
1 7 5
2 9 9
3 8 8
4 1 6
5 5 1
6 9 6
7 0 6
8 5 10
9 4 5
10 4 10
11 0 3
12 5 2
13 9 7
14 0 1
15 5 7
16 2 1
17 2 1
18 6 6
19 6 2
20 4 10
Creating a new column with absolute distance:
> df2$Distance<-abs(df2$y2-df2$x2)
> df2
  x2 y2 Distance
1 7 5      2
2 9 9      0
3 8 8      0
4 1 6      5
5 5 1      4
6 9 6      3
7 0 6      6
8 5 10     5
9 4 5      1
10 4 10    6
11 0 3     3
12 5 2     3
13 9 7     2
14 0 1     1
15 5 7     2
16 2 1     1
17 2 1     1
18 6 6     0
19 6 2     4
20 4 10    6
Find the Sum of fractions - JavaScript

We have an array of arrays like this −
const arr = [[12, 56], [3, 45], [23, 2], [2, 6], [2, 8]];
Note that while the array can have any number of elements, each subarray should strictly contain two numbers.
The two numbers in each subarray represents a fraction. For example, the fraction represented by the first subarray is 12/56, by the second is 3/45 and so on.
We are required to write a JavaScript function that takes in one such array and calculates the sum of fractions represented by all the subarrays. Calculate the sum in fraction form (i.e., without converting them to decimals). Return the sum as an array of two elements representing the resulting fraction.
Following is the code −
const arr = [[12, 56], [3, 45], [23, 2], [2, 6], [2, 8]];
const gcd = (a, b) => {
   let num = 2, res = 1;
   while(num <= Math.min(a, b)){
      if(a % num === 0 && b % num === 0){
         res = num;
      };
      num++;
   };
   return res;
}
const sumFrac = (a, b) => {
   const aDenom = a[1], aNumer = a[0];
   const bDenom = b[1], bNumer = b[0];
   let resDenom = aDenom * bDenom;
   let resNumer = (aDenom*bNumer) + (bDenom*aNumer);
   const greatestDivisor = gcd(resDenom, resNumer);
   return [resNumer/greatestDivisor, resDenom/greatestDivisor];
};
const sumArrayOfFractions = arr => {
   return arr.reduce((acc, val) => sumFrac(acc, val));
};
Following is the output in the console −
[ 1731, 140 ]
CSS Float - GeeksforGeeks

05 Nov, 2021
The float CSS property is used to position the elements to the left, right, of its container along with permitting the text and inline elements to wrap around it. The float property defines the flow of content in the page. The remaining elements will be part of the flow if the element is removed from the normal flow of the content. This property is ignored by the absolutely positioned elements. It can be written in a CSS file or can be directly specified in the style of an element.
Syntax:
float: none|left|right|initial|inherit;
Property values:
none: This is the default value & the element does not float.
left: Element floats on the left side of the container.
right: Element floats on the right side of the container.
initial Element will be set to its default value.
inherit: Element inherits floating property of its parent property.
We will use the above property values & understand their usage through the example.
left: The element will be positioned to the left side of its containing block.
HTML
<!DOCTYPE html><html>  <head>    <title>Float</title></head>  <body>    <div class="GFG" style="font-size:40px; color:#006400; float:left;"> GeeksforGeeks </div></body>  </html>
Output:
right: The element will be positioned to the right side of its containing block.
HTML
<!DOCTYPE html><html>  <head>    <title>Float</title></head>  <body>    <div class="GFG" style="font-size:40px; color:#006400; float:right;"> GeeksforGeeks </div></body>  </html>
Output:
none: The element remains the same as it is declared ie it will no effect on the element & this is the default value.
HTML
<!DOCTYPE html><html>  <head>    <title>Float</title></head>  <body>    <div class="GFG" style="font-size:40px; color:#006400; float:none;"> GeeksforGeeks </div></body>  </html>
Output:
inherit: It is used to inherit a property to an element from its parent element property value.
HTML
<!DOCTYPE html><html>  <head>    <title>Float</title></head>  <body>    <div style="float:right">        <div class="GFG" style="font-size:40px;     color:#006400; float:inherit;"> GeeksforGeeks </div>    </div></body>  </html>
Output:
Supported Browsers:
Google Chrome 1.0
Microsoft Edge 12.0
Firefox 1.0
Internet Explorer 4.0
Safari 1.0
Opera 7.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
bunnyram19
bhaskargeeksforgeeks
CSS-Basics
Web technologies
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
random.vonmisesvariate() function in Python - GeeksforGeeks

26 May, 2020
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
vonmisesvariate() is an inbuilt method of the random module. It is used to return a random floating point number with von Mises distribution or circular normal distribution.
Syntax : random.vonmisesvariate(mu, kappa)
Parameters :mu : mean angle, expressed in radians between 0 and 2*pikappa : concentration parameter, greater than or equal to zero
Returns : a random von Mises distribution floating number
Example 1:
# import the random moduleimport random  # determining the values of the parametersmu = 0kappa = 4  # using the vonmisesvariate() methodprint(random.vonmisesvariate(mu, kappa))
Output :
0.9429600175580171
Example 2: We can generate the number multiple times and plot a graph to observe the von Mises distribution.
# import the required libraries import random import matplotlib.pyplot as plt     # store the random numbers in a  # list nums = [] mu = 0kappa = 4    for i in range(100):     temp = random.vonmisesvariate(mu, kappa)    nums.append(temp)         # plotting a graph plt.plot(nums) plt.show()
Output :
Example 3: We can create a histogram to observe the density of the von Mises distribution.
# import the required libraries import random import matplotlib.pyplot as plt     # store the random numbers in a list nums = [] mu = 0kappa = 4    for i in range(10000):     temp = random.vonmisesvariate(mu, kappa)     nums.append(temp)         # plotting a graph plt.hist(nums, bins = 200) plt.show()
Output :
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
declare - Unix, Linux Command

declare - Declare variables and give them attributes.
declare [-afFrxi] [-p] [name[=value]]
If no names are given, then 'declare' will display the values of variables instead. Using + instead of - turns off the attribute instead. When used in a function, declare makes each name local, as with the local command. The typeset command is supplied for compatibility with the Korn shell; however, it has been deprecated in favor of the declare builtin command. The return status is zero unless an invalid option is encountered, an attempt is made to define a function using '-f foo=bar', an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax, one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-existent function with '-f'. 
$ declare | grep HOME
HOME=/home/bozo

$ zzy=68
$ declare | grep zzy
zzy=68

$ Colors=([0]="purple" [1]="reddish-orange" [2]="light green")
$ echo ${Colors[@]}
purple reddish-orange light green

bash$ declare | grep Colors
Colors=([0]="purple" [1]="reddish-orange" [2]="light green")


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
ArrayDeque toArray() Method in Java - GeeksforGeeks

10 Dec, 2018
The java.util.ArrayDeque.toArray() method is used to form an array of the same elements as that of the Deque. Basically, the method copies all the element from this deque to a new array.
Syntax:
Object[] arr = Array_Deque.toArray()
Parameters: The method does not take any parameters.
Return Value: The method returns an array containing the elements present in the ArrayDeque.
Below programs illustrate the java.util.ArrayDeque.toArray() method.Program 1:
// Java code to illustrate toArray()import java.util.*;  public class ArrayDequeDemo {    public static void main(String args[])    {        // Creating an empty ArrayDeque        Deque<String> de_que = new ArrayDeque<String>();          // Use add() method to add elements into the Deque        de_que.add("Welcome");        de_que.add("To");        de_que.add("Geeks");        de_que.add("For");        de_que.add("Geeks");          // Displaying the ArrayDeque        System.out.println("The ArrayDeque: " + de_que);          // Creating the array and using toArray()        Object[] arr = de_que.toArray();          System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The ArrayDeque: [Welcome, To, Geeks, For, Geeks]
The array is:
Welcome
To
Geeks
For
Geeks

Program 2:
// Java code to illustrate toArray()import java.util.*;  public class ArrayDequeDemo {    public static void main(String args[])    {        // Creating an empty ArrayDeque        Deque<Integer> de_que = new ArrayDeque<Integer>();          // Use add() method to add elements into the Deque        de_que.add(10);        de_que.add(15);        de_que.add(30);        de_que.add(20);        de_que.add(5);        de_que.add(25);          // Displaying the ArrayDeque        System.out.println("The ArrayDeque: " + de_que);          // Creating the array and using toArray()        Object[] arr = de_que.toArray();          System.out.println("The array is:");        for (int j = 0; j < arr.length; j++)            System.out.println(arr[j]);    }}
The ArrayDeque: [10, 15, 30, 20, 5, 25]
The array is:
10
15
30
20
5
25

Java - util package
Java-ArrayDeque
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to find the coordinates of the cursor with JavaScript?

To find the coordinates of the cursor in JavaScript, use event.clientX and event.clientY. You can try to run the following code to get cursor coordinates in JavaScript.
<!DOCTYPE html>
<html>
   <head>
      <script>
         function coordinatesFunc(event) {
            document.write("Coordinate(X) = " + event.clientX + "<br>Coordinate(Y) = " + event.clientY);
         }
      </script>
   </head>

   <body>
      <div onmousedown="coordinatesFunc(event)">Click me to get coordinates of cursor</p>
   </body>
</html>
Bootstrap class center-block

Use class center-block to set an element to center.
You can try to run the following code to implement the center-block class
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "pull-right" style = "width:100px; background-color:gray; color: white;">
         Float to right
      </div>
      <div class = "row">
         <div class = "center-block" style = "width:200px; background-color:#ccc; color: white;">
            Example for center-block
         </div>
      </div>
   </body>
</html>
HTML datetime Attribute

15 Jul, 2021
The <time> datetime Attribute in HTML is used to defines the machine-readable date/time of the <time> element. The date-time is inserted in the format YYYY-MM-DDThh:mm:ssTZD. Syntax:  
<time datetime="YYYY-MM-DDThh:mm:ssTZD"> 
Attribute Values: This attribute contains single value YYYY-MM-DDThh:mm:ssTZD which is used to specify the date and time when the text was deleted. The explanation of datetime components are listed below:  
YYYY: It sets the year of datetime object (e.g. 2009).
MM: It sets the month of datetime object (e.g. 05 for March).
DD: It sets the day of the month of datetime object (e.g. 04).
T: It is a required separator.
hh: It sets the hour of datetime object (e.g. 18 for 06.00pm).
mm: It sets the minutes of datetime object (e.g. 34).
ss: It sets the seconds of datetime object (e.g. 40).
TZD: Time Zone Designator (Z denotes Zulu, also known as Greenwich Mean Time)
Example:  
html
<!DOCTYPE html><html>  <head>    <title>        HTML Time dateTime Attribute    </title></head>  <body style="text-align:center;">         <h1>GeeksforGeeks</h1>      <h2>        HTML <Time>dateTime Attribute    </h2>          <p>Jawahar lal Nehru birthday is celebrated on         <time datetime="2018--11-14 12:00">            children's day.        </time>    </p>  </body>  </html>
Output :  
Supported Browsers: The browser supported by HTML <time> datetime Attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
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
SimpleDateFormat parse() Method in Java with Examples

12 Oct, 2021
The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.Syntax:  
public Date parse(String the_text, ParsePosition position)
Parameters: The method takes two parameters:  
the_text: This is of the String type and refers to the string which is to be parsed to produce the date.
position: This is of ParsePosition object type and refers to the information of the starting index of the parse.
Return Value: The method either returns the Date parsed from the string or Null in case of an error.Below programs illustrate the working of parse() Method of SimpleDateFormat: Example 1:  
Java
// Java Code to illustrate parse() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo {    public static void main(String[] args)        throws InterruptedException    {        SimpleDateFormat SDFormat            = new SimpleDateFormat("MM/ dd/ yy");         try {            Calendar cal = Calendar.getInstance();             // Use of .parse() method to parse            // Date From String            String dt = "10/ 27/ 16";            System.out.println("The unparsed"                               + " string is: " + dt);             cal.setTime(SDFormat.parse(dt));            System.out.println("Time parsed: "                               + cal.getTime());        }        catch (ParseException except) {            except.printStackTrace();        }    }}
The unparsed string is: 10/ 27/ 16
Time parsed: Thu Oct 27 00:00:00 UTC 2016
 
Example 2:  
Java
// Java Code to illustrate parse() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo {    public static void main(String[] args)        throws InterruptedException    {        SimpleDateFormat SDFormat            = new SimpleDateFormat("MM/ dd/ yy");         try {            Calendar cal = Calendar.getInstance();             // Use of .parse() method to parse            // Date From String            String dt = "01/ 29/ 19";            System.out.println("The unparsed"                               + " string is: " + dt);             cal.setTime(SDFormat.parse(dt));            System.out.println("Time parsed: "                               + cal.getTime());        }        catch (ParseException except) {            except.printStackTrace();        }    }}
The unparsed string is: 01/ 29/ 19
Time parsed: Tue Jan 29 00:00:00 UTC 2019
 
gulshankumarar231
Java-Functions
Java-SimpleDateFormat
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Map size() method with example

13 Aug, 2019
The size() is utilized to find the number of key-value pairs in the stated map.
Method Definition: def size: Int
Return Type: It returns the number of elements in the map.
Example #1:
// Scala program of size()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs")                  // Applying size method        val result = m1.size                  // Displays output        println(result)          }}
3

Example #2:
// Scala program of size()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = Map(3 -> "geeks", 1 -> "for", 1 -> "cs")                  // Applying size method        val result = m1.size                  // Displays output        println(result)              }}
2

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Scala | Arrays
Operators in Scala
Scala Constructors
Enumeration in Scala
Lambda Expression in Scala
How to Install Scala with VSCode?
Scala String replace() method with example
How to get the first element of List in Scala
Python – Replace all numbers by K in given String

05 Sep, 2020
Given a string containing numbers, replace each number by K.
Input : test_str = ‘G4G is 4 all No. 1 Geeks’, K = ‘#’Output : G#G is # all No. # GeeksExplanation : All numbers replaced by K.
Input : test_str = ‘G4G is 4 all No. Geeks’, K = ‘#’Output : G#G is # all No. GeeksExplanation : All numbers replaced by K.
Method #1 : Using replace() + isdigit()
In this, we check for numerics using isdigit() and replace() is used to perform the task of replacing the numbers by K.
Python3
# Python3 code to demonstrate working of # Replace numbers by K in String# Using replace() + isdigit()  # initializing stringtest_str = 'G4G is 4 all No. 1 Geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing K K = '@'  # loop for all charactersfor ele in test_str:    if ele.isdigit():        test_str = test_str.replace(ele, K)          # printing result print("The resultant string : " + str(test_str)) 
The original string is : G4G is 4 all No. 1 Geeks
The resultant string : G@G is @ all No. @ Geeks

Method #2 : Using regex() + sub()
In this, appropriate regex is used to identify digits and sub() is used to perform replace.
Python3
# Python3 code to demonstrate working of # Replace numbers by K in String# Using regex() + sub()import re  # initializing stringtest_str = 'G4G is 4 all No. 1 Geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing K K = '@'  # using regex expression to solve problem res = re.sub(r'\d', K, test_str)          # printing result print("The resultant string : " + str(res)) 
The original string is : G4G is 4 all No. 1 Geeks
The resultant string : G@G is @ all No. @ Geeks

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

09 Sep, 2020
The _.has() method is used to check whether the path is a direct property of object or not. It returns true if path exists, else it returns false.
Syntax:
_.has(object, path)

Parameters: This method accepts two parameters as mentioned above and described below:
object: This parameter holds the object to query.
path: This parameter holds the path to check. The path will be array or string.
Return Value: This method returns true if path exists, else false
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Given objectvar object = { 'a': { 'b': 2 } };  // Use of _.has method console.log(_.has(object, 'a')); console.log(_.has(object, ['a'])); console.log(_.has(object, ['b'])); 
Output:
true
true
false

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Given objectvar object = { 'a': { 'b': 2 } };  // Use of _.has method console.log(_.has(object, 'a.b')); console.log(_.has(object, ['a','b'])); console.log(_.has(object, ['a','b','c'])); 
Output:
true
true
false

JavaScript-Lodash
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 ?
Create Line Curves for Specified Equations in R Programming – curve() Function

10 Jun, 2020
curve() function in R Language is used to draw a curve for the equation specified in the argument.
Syntax: curve(expression, to, from, col)
Parameters:expression: To be curvedto, from: range of curve plottingcol: color of curve
Example 1:
# R program to create a curve  # Creating curve using curve() functioncurve(x ^ 2 + x + 5, -4, 4, col ="green", ylab ="y")
Output:
Example 2:
# R program to create a curve  # Creating curve using functionfun <- function(x) {x ^ 3 + 4}curve(fun, -4, 4, col ="red", ylab ="y")
Output:
R Math-Function
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Display Upper Triangular Matrix

20 Jul, 2021
Upper Triangular Matrix is a matrix in which all the elements below the principal matrix are 0. A necessary condition is that matrix must be Square matrix in nature. If the matrix is not a square matrix, it can never be called the upper triangular matrix.
Input 1: mat[][] = { {2, 1, 4},
                     {1, 2, 3},  
                     {3, 6, 2} }
                     
Output :  mat[][]= { {2, 1, 4},
                     {0, 2, 3},  
                     {0, 0, 2} }
                     
Explaination: All the element below the principal diagonal needs to be 0.

Input 2 :   mat[][]=  { {4,7},
                        {2,8} }
                  
Output :   mat[][]=   { {4,7},
                        {0,8} }

Input 3 :  mat[][]=  { {2,1,4,6},
                       {1,2,3,7},  
                       {3,6,2,8} }  
Output :   Matrix should be a Square Matrix
 Approach:
If the matrix has equal rows and columns, continue the program else exit the program.
Run the loop over the whole matrix, and for the rows whose row number is greater than column number, make the element at that position equal to 0.
Below is the implementation of the above approach:
Java
// Java Program to print the upper triangular matriximport java.io.*; class GFG {       // Print matrix using iterative approach    public static void printMatrix(int[][] a)    {        for (int i = 0; i < a.length; i++) {            for (int j = 0; j < a[0].length; j++)                System.out.print(a[i][j] + " ");            System.out.println();        }    }    public static void upperTriangularMatrix(int matrix[][])    {        int row = matrix.length;        int col = matrix[0].length;               // if number of rows and        // columns are not equal,then        // return back        if (row != col) {            System.out.println(                "Matrix should be a Square Matrix");            return;        }        else {                       // looping over the whole matrix            for (int i = 0; i < row; i++) {                for (int j = 0; j < col; j++) {                                       // for the rows ,whose row number is                    // greater then column number,mark the                    // element as 0                    if (i > j) {                        matrix[i][j] = 0;                    }                }            }             System.out.println(                "Upper Triangular Matrix is given by :-");                       // printing the upper triangular matrix            printMatrix(matrix);        }    }    public static void main(String[] args)    {        int mat[][] = { { 2, 1, 4 }, { 1, 2, 3 }, { 3, 6, 2 } };               // calling the function        upperTriangularMatrix(mat);    }}
Upper Triangular Matrix is given by :-
2 1 4 
0 2 3 
0 0 2 
  Space Complexity: 0(N^2)
Time Complexity: 0(N^2)
 
simranarora5sos
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Check for spaces in string

04 Jul, 2019
Sometimes, we might have a problem in which we need to check if the string has any of blank spaces. This kind of problem can be in Machine Learning domain to get specific type of data set. Let’s discuss certain ways in which this kind of problem can be solved.
Method #1 : Using regexThis kind of problem can be solved using the regex utility offered by python. By feeding the appropriate regex string in search(), we can check presence of space in a string.
# Python3 code to demonstrate working of# Check for spaces in string# Using regeximport re  # initializing string test_str = "Geeks  forGeeks"  # printing original string print("The original string is : " + test_str)  # Using regex# Check for spaces res = bool(re.search(r"\s", test_str))  # printing result print("Does string contain spaces ? " + str(res))
The original string is : Geeks  forGeeks
Does string contain spaces ? True

Method #2 : Using in operatorThis task can also be performed using in operator. Just required to check for a space in the string. The verdict returned is true even if a single space is found and false otherwise.
# Python3 code to demonstrate working of# Check for spaces in string# Using in operator  # initializing string test_str = "Geeks  forGeeks"  # printing original string print("The original string is : " + test_str)  # Using in operator# Check for spaces res = " " in test_str  # printing result print("Does string contain spaces ? " + str(res))
The original string is : Geeks  forGeeks
Does string contain spaces ? True

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get all the aliases in PowerShell?

In PowerShell, you will get all the alias and their commands using Alias: drive as shown below.
Dir Alias:
Here, Alias: is the drive but surprisingly you will not find it in your operating system. This is the
virtual drive and there are other virtual drives as well. You can list all the virtual drives using the
below command.
Get-Alias will provide the same result.
The above output provides the individual alias and their commands for it. But to group them based
on their cmdlets, you need to use Group-Object command.
Dir Alias: | Group-Object Definition
You will see in the output that aliases are listed against their cmdlet and their counts as well.
Scala List max() method with example

26 Jul, 2019
The max() method is utilized to find the largest element of all the elements in the stated list.
Method Definition: def max[B >: A](implicit ord: math.Ordering[B]): A
Return Type: It returns the largest of all the elements in the stated list.
Example #1:
// Scala program of max()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 2, 3)                  // Applying max method        val result = m1.max                  // Displays output        println(result)          }}
3

Example #2:
// Scala program of max()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(5, 12, 3, 13)                  // Applying max method        val result = m1.max                  // Displays output        println(result)          }}
13

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
How to Install Scala with VSCode?
SciPy – Integration of a Differential Equation for Curve Fit

23 Jan, 2022
In Machine Learning, often what we do is gather data, visualize it, then fit a curve in the graph and then predict certain parameters based on the curve fit. If we have some theoretical data we can use curve fitting from the verified dataset to extract the equation and verify it. So to find the equation of a curve of any order be it linear, quadratic or polynomial, we use Differential Equations and then integrating that equation we can get the curve fit.In Python SciPy, this process can be done easily for solving the differential equation by mathematically integrating it using odeint(). The odeint(model, y0, t) can be used to solve any order differential equation by taking three or more parameters.  
Parameters : model– the differential equation  y0– Initial value of Y t– the time space for which we want the curve(basically the range of x) 
Let’s illustrate this with an example:  
Code: To solve the equation to get y = x – 1 + 2 (e^-x) as the solution  
python3
import numpy as npfrom scipy.integrate import odeintimport matplotlib.pyplot as plt from scipy.integrate import odeint # Define a function which calculates the derivative by making dy/dx as# the subject of formula in the given above equationdef dy_dx(y, x):    return x - y #Here we define the graph limits for xxs = np.linspace(-5,5,100) #Initially y=1 giveny0 = 1.0 # This scipy.integrate.odeint() integrates the given equation by taking# 3 parameters odeint(model,y0,t)# model- the differential equation function# y0-the initial value of y# t- the timepoints for which we need to plot the curveys = odeint(dy_dx, y0, xs)ys = np.array(ys).flatten() # By using the matplotlib.pyplot library we plot the curve after integrationplt.rcParams.update({'font.size': 14})  # increase the font sizeplt.xlabel("x-values")plt.ylabel("Y- values")plt.title('Curve of -> y=x-1+2*(e^-x)')plt.plot(xs, ys,color='green')
Output: This is the graph generated by using the scipy.integrate.odeint( ) which can be seen below and further be used for curve fitting – for analyzing the data in Machine learning.  
The Graph generated after integrating the differential equation
 
ruhelaa48
adnanirshad158
Maths
Python-scipy
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Python | Convert nested sublist into tuples - GeeksforGeeks

18 Oct, 2019
Sometimes, while working with huge amount of data, we might have in which each point of data constitutes of several elements and needs to be processed as single unit. For this, we might sometimes, just receive a matrix and it’s constituent data points are also lists, which don’t make much sense and whole and might be required to be converted to tuples. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple() + list comprehensionThis is the one-liner approach to solve this problem. In this we just iterate through the innermost sublist and convert each of lists to tuple using tuple().
# Python3 code to demonstrate working of# Convert nested sublist into tuples# Using tuple() + list comprehension  # Initializing listtest_list = [[[1, 2, 3], [4, 6, 7]], [[6, 9, 8], [10, 11, 12]]]  # printing original listprint("The original list is : " + str(test_list))  # Convert nested sublist into tuples# Using tuple() + list comprehensionres = [[tuple(ele) for ele in sub] for sub in test_list]  # printing resultprint("The data after conversion to tuple is : " + str(res))
The original list is : [[[1, 2, 3], [4, 6, 7]], [[6, 9, 8], [10, 11, 12]]]
The data after conversion to tuple is : [[(1, 2, 3), (4, 6, 7)], [(6, 9, 8), (10, 11, 12)]]

 
Method #2 : Using map() + list comprehension + tupleThis is another way in which this task can be performed. In this, we reduce one inner loop and extend the functionality of tuple conversion to each element using map().
# Python3 code to demonstrate working of# Convert nested sublist into tuples# Using map() + list comprehension + tuple  # Initializing listtest_list = [[[1, 2, 3], [4, 6, 7]], [[6, 9, 8], [10, 11, 12]]]  # printing original listprint("The original list is : " + str(test_list))  # Convert nested sublist into tuples# Using map() + list comprehension + tupleres = [list(map(tuple, sub)) for sub in test_list]  # printing resultprint("The data after conversion to tuple is : " + str(res))
The original list is : [[[1, 2, 3], [4, 6, 7]], [[6, 9, 8], [10, 11, 12]]]
The data after conversion to tuple is : [[(1, 2, 3), (4, 6, 7)], [(6, 9, 8), (10, 11, 12)]]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
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
How to copy the content of one HTML5 Canvas to another Canvas locally?

The drawImage() method is used to draw image, canvas and videos on canvas. It can also draw part of image and increase or decrease the image size.
Let us see an example −
//context grabbed from your destination canvas
ctx = destinationCanvas.getContext('2d');

//drawImage() called passing the source canvas directly
dCtx.drawImage(sourceCanvas, 0, 0);
In this code, firstly the image is copied from the source canvas. The sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. A canvas drawing context cannot be used as a source. If a canvas drawing context is your source canvas then there is a reference to the original canvas element on the context under context.canvas
The latter code uses drawImage() method to copy context from source canvas to the desired canvas.
How to get distinct rows in dataframe using PySpark? - GeeksforGeeks

30 May, 2021
In this article we are going to get the distinct data from pyspark dataframe in Python, So we are going to create the dataframe using a nested list and get the distinct data.
We are going to create a dataframe from pyspark list bypassing the list to the createDataFrame() method from pyspark, then by using distinct() function we will get the distinct rows from the dataframe.
Syntax: dataframe.distinct()
Where dataframe is the dataframe name created from the nested lists using pyspark
Example 1: Python code to get the distinct data from college data in a data frame created by list of lists.
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of college datadata = [["1", "bobby", "vvit"],         ["2", "sravan", "jntuk"],        ["3", "rohith", "AU"],        ["4", "sridevi", "GVRS"],         ["1", "bobby", "vvit"]]  # specify column namescolumns = ['ID', 'NAME', 'COLLEGE']  # creating a dataframe from the # lists of datadataframe = spark.createDataFrame(data, columns)  print('Actual data in dataframe')dataframe.show()
Output:
Now Get the distinct rows in dataframe:
Python3
print('distinct data')  # display distinct datadataframe.distinct().show()
Output:
Example 2: Python program to find distinct values from 1 row
Python3
# importing moduleimport pyspark  # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of college datadata = [["1", "bobby", "vvit"]]  # specify column namescolumns = ['ID', 'NAME', 'COLLEGE']  # creating a dataframe from the # list of datadataframe = spark.createDataFrame(data, columns)  print('Actual data in dataframe')dataframe.show()
Output:
Now Get the distinct rows in dataframe:
Python3
print('distinct data')  # display distinct data from# the dataframedataframe.distinct().show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
GATE | GATE-CS-2003 | Question 88 - GeeksforGeeks

22 Sep, 2021
In the following C program fragment, j, k n and TwoLog_n are integer variables, and A is an array of integers. The variable n is initialized to an integer ≥ 3, and TwoLog_n is initialized to the value of 2*⌈log2(n)⌉
for (k = 3; k < = n; k++)    A[k] = 0;for (k = 2; k < = TwoLog_n; k++)    for (j = k + 1; j < = n; j++)        A[j] = A[j] || (j % k);for (j = 3; j < = n; j++)    if (!A[j]) printf("%d", j);
The set of numbers printed by this program fragment is(A) {m | m ≤ n, (∃ i) [m = i!]} Here i! mean factorial of i(B) {m | m ≤ n, (∃ i) [m = i2]}(C) {m | m ≤ n, m is prime}(D) {}Answer: (D)Explanation: Option (D) is correct because if take n=4 then TwoLog_n value 4.first loop initially A[3]=A[4]=0;then two loop k = 2 to 4 and j = 3 to 4
if k=2 
         j=3  A[3] = A[3] || (3%2) 
                          = 0 || 1
                  A[3] = 1 
       j=4  A[4] = A[4] || (4%2)
                         = 0 || 0
                A[4] = 0
K=3
         j=4  A[4] = A[4] || (4%3)

                        = 0 || 1
               A[4] = 1
K=4
     J=5 condition false means terminate
 A[3] = A[4] = 1

Means last print loop never execute.Quiz of this Question
vinit faldu
arorakashish0911
GATE-CS-2003
GATE-GATE-CS-2003
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 83
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1997 | Question 25
How to retrieve particular columns of a table using JDBC program?

A ResultSet interface in JDBC represents the tabular data generated by SQL queries. It has a cursor which points to the current row. Initially this cursor is positioned before first row.
You can move the cursor using the next() method and, you can retrieve the column values of a row using the getter methods of the ResultSet interface (getInt(), getString(), getDate() etc..).
To retrieve required data from a table:
Connect to the database.
Connect to the database.
Create a Statement object.
Create a Statement object.
Execute the Statement using the executeQuery() method. To this method, pass the select query in the String format. To retrieve all the values, we use the following query:
Execute the Statement using the executeQuery() method. To this method, pass the select query in the String format. To retrieve all the values, we use the following query:
Select * from TableName;
To retrieve particular columns, specify the required column names instead of * as:
To retrieve particular columns, specify the required column names instead of * as:
select Name, DOB from Emp
Assume we have a table named Emp in the database with the following description:
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| Name     | varchar(255) | YES  |     | NULL    |       |
| DOB      | date         | YES  |     | NULL    |       | 
| Location | varchar(255) | YES  |     | NULL    |       |
+----------+--------------+------+-----+---------+-------+
Following JDBC example retrieves Name and DOB values of the employees from the Emp table.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingParticularColumn {
      public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");

      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select Name, DOB from Emp");

      System.out.println("Contents of the table");
      while(rs.next()) {
         System.out.print("Name of the Employee: "+rs.getString("Name")+", ");
         System.out.print("Date of Birth: "+rs.getDate("DOB"));
         System.out.println("");
      }
   }
}
Connection established......
Contents of the table
Name of the Employee: Amit, Date of Birth: 1970-01-08
Name of the Employee: Sumith, Date of Birth: 1970-01-08
Name of the Employee: Sudha, Date of Birth: 1970-01-05
Python | Pandas Series.dt.weekday - GeeksforGeeks

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.weekday attribute return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6.
Syntax: Series.dt.weekday
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.weekday attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',               '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.weekday attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# return the day of weekresult = sr.dt.weekday  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.weekday attribute has successfully accessed and returned the day of week in the underlying data of the given series object. Example #2 : Use Series.dt.weekday attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'M'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.weekday attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# return the day of weekresult = sr.dt.weekday  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.weekday attribute has successfully accessed and returned the day of week in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Iterate over a list in Python
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib