code-rag-bench/online-tutorials huggingface dataset:
Comparator naturalOrder() method in Java with examples - GeeksforGeeks

29 Apr, 2019
The naturalOrder() method of Comparator Interface in Java returns a comparator that use to compare Comparable objects in natural order. The returned comparator by this method is serializable and throws NullPointerException when comparing null.
Syntax:
static <T extends Comparable<T>> 
    Comparator<T> naturalOrder()

Parameters: This method accepts nothing.
Return value: This method returns a comparator that imposes the natural ordering on Comparable objects.
Below programs illustrate naturalOrder() method:Program 1:
// Java program to demonstrate// Comparator.naturalOrder()  method  import java.util.Arrays;import java.util.Comparator;import java.util.List;  public class GFG {    public static void main(String... args)    {          List<Integer> values            = Arrays.asList(212, 324,                            435, 566,                            133, 100, 121);          // naturalOrder is a static method        values.sort(Comparator.naturalOrder());          // print sorted number based on natural order        System.out.println(values);    }}
The output printed on console of IDE is shown below.Output:
Program 2:
// Java program to demonstrate// Comparator.naturalOrder()  method  import java.util.Arrays;import java.util.Comparator;import java.util.List;  public class GFG {    public static void main(String... args)    {          List<String> stringList            = Arrays.asList("Aman", "Kajal",                            "Joyita", "Das");          System.out.println("Before sorting:");        stringList.forEach(System.out::println);          stringList.sort(Comparator.naturalOrder());        System.out.println("\nAfter sorting:");        stringList.forEach(System.out::println);    }}
The output printed on console is shown below.Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#naturalOrder()
Java - util package
Java-Comparator
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Strings in Java
StringBuilder Class in Java with Examples
Python | Convert column to separate elements in list of lists - GeeksforGeeks

11 Jun, 2021
There are instances in which we might require to extract a particular column of a Matrix and assign its each value as separate entity in list and this generally has a utility in Machine Learning domain. Let’s discuss certain ways in which this action can be performed.Method #1 : Using list slicing and list comprehension The functionality of list slicing and comprehension can be clubbed to perform the particular task of extracting a column from a list and then it can be added as new element using list comprehension. 
Python3
# Python3 code to demonstrate # column to separate elements in list of lists# using list slicing and list comprehension # initializing list of listtest_list = [[1, 3, 4],             [6, 2, 8],             [9, 10, 5]] # printing original listprint ("The original list is : " + str(test_list)) # using list slicing and list comprehension# column to separate elements in list of listsres = [i for nest_list in [[j[1 : ], [j[0]]]         for j in test_list] for i in nest_list] # printing resultprint ("The list after column shift is : " + str(res))
The original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]
The list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]

 Method #2 : Using itertools.chain() + list comprehension + list slicing The above method can be improved by inducing the concept of element chaining and reduce the overhead of the list comprehension and reducing the time taken to execute this particular task. 
Python3
# Python3 code to demonstrate # column to separate elements in list of lists# using itertools.chain()+ list comprehension + list slicingfrom itertools import chain # initializing list of listtest_list = [[1, 3, 4],             [6, 2, 8],             [9, 10, 5]] # printing original listprint ("The original list is : " + str(test_list)) # using itertools.chain() + list comprehension + list slicing# column to separate elements in list of listsres = list(chain(*[list((sub[1: ], [sub[0]]))                      for sub in test_list])) # printing resultprint ("The list after column shift is : " + str(res))
The original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]
The list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]

arorakashish0911
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python | Scipy stats.hypsecant.ppf() method - GeeksforGeeks

10 Feb, 2020
With the help of stats.hypsecant.ppf() method, we can get the value of percentage point function which is inverse( cdf ) by using stats.hypsecant.ppf() method.
Syntax : stats.hypsecant.ppf(x, beta)Return : Return the value of percentage point function.
Example #1 :In this example we can see that by using stats.hypsecant.ppf() method, we are able to get the value of percentage point function by using this method.
# import hypsecantfrom scipy.stats import hypsecantbeta = 1  # Using stats.hypsecant.ppf() methodgfg = hypsecant.ppf(0.3, beta)  print(gfg)
Output :
0.3257245223731834
Example #2 :
# import hypsecantfrom scipy.stats import hypsecantbeta = 4  # Using stats.hypsecant.ppf() methodgfg = hypsecant.ppf(0.9, beta)  print(gfg)
Output :
5.842730034701113
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Change Background color of a web page using onmouseover property

The onmouseover property allows you set a script when the mouse pointer is moved onto an element. To change the background color, use the HTML DOM backgroundColor property.
Let us see an example to implement the onmouseover property and change the background color −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Heading Two</h2>
   <a onmouseover="document.body.style.backgroundColor ='orange'">Hover over me to change the background color.</a><br>
</body>
</html>
Now hover over the text to change the background color of the web page −
Example program on Dynamic memory allocation function in C language

How to display and calculate the sum of n numbers by using dynamic memory allocation function in C language?
Following is the C program to display the elements and calculate the sum of n numbers by the user by using dynamic memory allocation functions. Here, we also try to reduce the wastage of memory.
 Live Demo
#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointers,sum//
   int numofe,i,sum=0;
   int *p;
   //Reading number of elements from user//
   printf("Enter the number of elements : ");
   scanf("%d",&numofe);
   //Calling malloc() function//
   p=(int *)malloc(numofe*sizeof(int));
   /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Printing elements//
   printf("Enter the elements : \n");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("\nThe sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("\nDisplaying the cleared out memory location : \n");
   for(i=0;i<numofe;i++){
      printf("%d\n",p[i]);//Garbage values will be displayed//
   }
}
When the above program is executed, it produces the following result −
Enter the number of elements: 4
Enter the elements:
23
45
67
89
The sum of elements is 224
Displaying the cleared out memory location:
7410816
0
7405904
0
\leftrightharpoons - Tex Command

\leftrightharpoons - Used to draw leftrightharpoons symbol.
{ \leftrightharpoons }
\leftrightharpoons command is used to draw leftrightharpoons symbol.

\leftrightharpoons

⇋



\leftrightharpoons

⇋


\leftrightharpoons

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Count Primes in Python

Suppose we have a limit n. We have to count the number of primes present in the range 2 to n. So if n = 10, the result will be 4. As there are four primes before 10, they are 2, 3, 5, 7.
To solve this, we will follow this approach −
count = 0
take one array prime = of size n + 1, and fill it with False
for i = 0 to n, doif prime[i] = false, thenincrease count by 1set j = 2while j * i <n, thenprime[i * j] = Truej = j + 1
if prime[i] = false, thenincrease count by 1set j = 2while j * i <n, thenprime[i * j] = Truej = j + 1
increase count by 1
set j = 2
while j * i <n, thenprime[i * j] = Truej = j + 1
prime[i * j] = True
j = j + 1
return count
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def countPrimes(self, n):
      """
      :type n: int
      :rtype: int
      """
      count = 0
      primes = [False for i in range(n+1)]
      for i in range(2,n):
         if primes[i] == False:
            count+=1
            j = 2
            while j*i<n:
               primes[j*i] = True
               j+=1
      return count
ob1 = Solution()
print(ob1.countPrimes(50))
print(ob1.countPrimes(10))
n = 50
n = 10
15
4
How to use UICollectionView in Swift?

To use collection view in swift, first, we need to create a collection View. We can either drag and drop it to the storyboard, or we can make it programmatically. After that, we need to confirm our class to UICollectionViewDataSource and UICollectionViewDelegate. Also if we need custom cell size and layouts, we need to confirm it to UICollectionViewDelegateFlowLayout.
Let’s see the step required to create a collection View programmatically.
func initCollection() {
   let layout = UICollectionViewFlowLayout()
   layout.itemSize = CGSize(width: 50, height: 50)
   let collection = UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)
   collection.dataSource = self
   collection.delegate = self
   collection.backgroundColor = colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
   collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
   self.view.addSubview(collection)
}
We need to call the above function in our ViewDidLoad() method. Whether we create a collection programmatically, or with a storyboard, we need to allocate data source, and delegate to give data to table, and observe its actions respectively.
Now, we need to tell the collection, how many sections it should have −
func numberOfSections(in collectionView: UICollectionView) -> Int {
   return 1
}
After that, we need to tell how many items it will have, and what data should be present in the cells.
func collectionView(_ collection: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   return 7
}
func collectionView(_ collection: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
   cell.layer.backgroundColor = colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1)
   return cell
}
Optionally we can give it different size according to requirement.
func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
   let size = CGSize(width: 200, height: 50)
   return size
}
When we run the above code on a device, this is the result that’s produced.
How to Alter a Column from Null to Not Null in SQL Server? - GeeksforGeeks

23 Sep, 2021
With this article, we will learn how to alter a column from accepting Null values to Not Null in SQL Server. The prerequisites of this article are you should be having a MSSQL server on your computer.
A query is a statement or a group of statements written to perform a specific task, like retrieve data, save data into a database.
So, we will create a database first:
CREATE DATABASE GFG
USE GFG
CREATE TABLE gfgTutorial(
id integer,
Name varchar(20)
)
sp_help 'dbo.gfgTutorial'
ALTER TABLE gfgTutorial ALTER COLUMN id VARCHAR (50) NOT NULL;
So now our table id column is changed to not null
Changed null id to not null
So we have successfully changed the id column to not null in the gfgTutorial table.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Convert VARCHAR to INT
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
DateTime.AddHours() Method in C#

The DateTime.AddHours() method in C# is used to add the specified number of hours to the value of this instance. This method returns a new DateTime.
Following is the syntax −
public DateTime AddHours (double hrs);
Above, hrs are the number of hours to be added. The value can be negative to subtract the hours.
Let us now see an example to implement the DateTime.AddHours() method
using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 11, 2, 9, 0, 10);
      DateTime d2 = d1.AddHours(2);
      System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:t} ", d1);
      System.Console.WriteLine("\nNew DateTime (After adding hours) = {0:dd} {0:y}, {0:t} ", d2);
   }
}
This will produce the following output −
Initial DateTime = 02 November 2019, 9:00 AM
New DateTime (After adding hours) = 02 November 2019, 11:00 AM
Let us now see another example to implement the DateTime.AddHours() method −
using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 10, 5, 9, 0, 10);
      DateTime d2 = d1.AddHours(-5);
      System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:t} ", d1);
      System.Console.WriteLine("\nNew DateTime (After subtracting hours) = {0:dd} {0:y}, {0:t} ", d2);
   }
}
This will produce the following output −
Initial DateTime = 05 October 2019, 9:00 AM
New DateTime (After subtracting hours) = 05 October 2019, 4:00 AM
Tryit Editor v3.7

Tryit: Several !important rules
Why singleton class is always sealed in C#?

The sealed keyword means that the class cannot be inherited from. Declaring constructors private means that instances of the class cannot be created.
You can have a base class with a private constructor, but still inherit from that base class, define some public constructors, and effectively instantiate that base class.
Constructors are not inherited (so the derived class won't have all private constructors just because the base class does), and that derived classes always call the base class constructors first.
Marking the class sealed prevents someone from trivially working around your carefully-constructed singleton class because it keeps someone from inheriting from the class.
static class Program {
   static void Main(string[] args){
      Singleton fromStudent = Singleton.GetInstance;
      fromStudent.PrintDetails("From Student");

      Singleton fromEmployee = Singleton.GetInstance;
      fromEmployee.PrintDetails("From Employee");

      Console.WriteLine("-------------------------------------");

      Singleton.DerivedSingleton derivedObj = new Singleton.DerivedSingleton();
      derivedObj.PrintDetails("From Derived");
      Console.ReadLine();
   }
}
public class Singleton {
   private static int counter = 0;
   private static object obj = new object();

   private Singleton() {
      counter++;
      Console.WriteLine("Counter Value " + counter.ToString());
   }
   private static Singleton instance = null;

   public static Singleton GetInstance{
      get {
         if (instance == null)
            instance = new Singleton();
         return instance;
      }
   }

   public void PrintDetails(string message){
      Console.WriteLine(message);
   }

   public class DerivedSingleton : Singleton {
   }
}
Average of Squares of Natural Numbers?

The average of the square of Natural Number is calculated by adding all the squares up to n natural numbers and then dividing it by the number.
Average of square of first 2 natural numbers is 2.5 ,
12 + 22 = 5 => 5/2 = 2.5.
There are two methods for calculating this is programming −
Using Loops
Using Formula
Calculating average of square of natural numbers using loops
This logic works by finding the squares of all natural numbers. By loop from 1 to n finding square of each and adding to the sum variable. Then dividing this sum by n.
Program to find the sum of squares of natural numbers −
 Live Demo
#include <stdio.h>
int main() {
   int n = 2;
   float sum = 0;
   for (int i = 1; i <= n; i++) {
      sum = sum + (i * i);
   }
   float average = sum/n;
   printf("The average of the square of %d natural numbers is %f", n,average);
   return 0;
}
The average of the square of 2 natural numbers is 2.500000
Calculating average of square of natural numbers using formula. 
There are mathematical formulas to make calculations easy. For calculating the sum of squares of natural numbers the formula is ‘ n*(n+1)*((2*n)+1)/6’ diving this by the number n gives the formula : ‘ (n+1)*((2*n)+1)/6’.
Program to find the sum of squares of natural numbers −
 Live Demo
#include <stdio.h>
int main() {
   int n = 2;
   float average = ((n+1)*((2*n)+1)/6);
   printf("The average of the square of %d natural numbers is %f", n,average);
   return 0;
}
The average of the square of 2 natural numbers is 2.500000
Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?

We have to write a function that takes in an array and returns an object with two properties
namely positive and negative. They both should be an array containing all positive and negative
items respectively from the array.
This one is quite straightforward, we will use the Array.prototype.reduce() method to pick
desired elements and put them into an object of two arrays.
const arr = [
   [12, -45, 65, 76, -76, 87, -98],
   [54, -65, -98, -23, 78, -9, 1, 3],
   [87, -98, 3, -2, 123, -877, 22, -5, 23, -67]
];
const splitArray = (arr) => {
   return arr.reduce((acc, val) => {
      if(val < 0){
         acc['negative'].push(val);
      } else {
         acc['positive'].push(val);
      }
      return acc;
   }, {
         positive: [],
         negative: []
      })
   };
   for(let i = 0; i < arr.length; i++){
   console.log(splitArray(arr[i]));
}
The output in the console will be −
{ positive: [ 12, 65, 76, 87 ], negative: [ -45, -76, -98 ] }
{ positive: [ 54, 78, 1, 3 ], negative: [ -65, -98, -23, -9 ] }
{
   positive: [ 87, 3, 123, 22, 23 ],
   negative: [ -98, -2, -877, -5, -67 ]
}
What are variable arguments in java?

While defining a method, In general, we will specify the arguments it accepts along with the type as −
myMethod(int a, String b){
}
Suppose if you need to accept more than one variable of the same type you need to specify the variables one after the other as −
myMethod(int a, int b, int c){
}
You can also pass a variable number of arguments of a particular type, to a method. These are known as variable arguments or, varargs. They are represented by three dots (...)
public myMethod(int ... a) {
   // method body
}
Once you use variable arguments as a parameter method while calling you can pass as many numbers of arguments to this method (variable number of arguments) or, you can simply call this method without passing any arguments.
 Live Demo
public class Sample{
   void demomethod(String... args) {
      for (String arg : args) {
         System.out.println(arg);
      }
   }
   public static void main(String args[] ){
      new Sample().demomethod("Ram", "Rahim", "Robert");
      new Sample().demomethod("Krishna", "Kasyap");
      new Sample().demomethod();
   }
}
Ram
Rahim
Robert
Krishna
Kasyap
 Live Demo
public class VarargsExample{
   void demoMethod(String name, int age, int... marks) {
      System.out.println();
      System.out.println("Name: "+name);
      System.out.println("Age: "+age);
      System.out.print("Marks: ");
      for (int m: marks) {
         System.out.print(m+" ");
      }
   }
   public static void main(String args[] ){
      VarargsExample obj = new VarargsExample();
      obj.demoMethod("Krishna", 23, 90, 95, 80, 69 );
      obj.demoMethod("Vishnu", 22, 91, 75, 94 );
      obj.demoMethod("Kasyap", 25, 85, 82);
      obj.demoMethod("Vani", 25, 93);
   }
}
Name: Krishna
Age: 23
Marks: 90 95 80 69
Name: Vishnu
Age: 22
Marks: 91 75 94
Name: Kasyap
Age: 25
Marks: 85 82
Name: Vani
Age: 25
Marks: 93
Rules to follow while using varargs in Java −
We can have only one variable argument per method. If you try to use more than one variable arguments a compile-time error is generated.
We can have only one variable argument per method. If you try to use more than one variable arguments a compile-time error is generated.
In the list of arguments of a method, varargs must be the last one. Else a compile-time error will be generated.
In the list of arguments of a method, varargs must be the last one. Else a compile-time error will be generated.
How to increase the width of the median line in boxplot using ggplot2 in R?

The default width of the median line is wider than the rest of the lines that represent minimum, first quartile, third quartile or maximum but we can make it a little wider to make it more appealing. This can be done with the help of fatten argument inside geom_boxplot function, the default value of fatten is 2.
 Live Demo
Consider the below data frame −
x<−sample(c("A","B","C"),20,replace=TRUE)
y<−rnorm(20,5,1.24)
df<−data.frame(x,y)
df
   x    y
1 A 4.740834
2 C 5.365280
3 B 5.250932
4 B 5.764159
5 B 4.053119
6 B 4.241961
7 B 6.285087
8 C 5.513231
9 B 5.888086
10 B 4.479830
11 C 4.217874
12 A 6.366376
13 C 6.278470
14 C 4.721193
15 B 5.387542
16 B 6.683681
17 B 6.153023
18 A 4.695209
19 C 5.715360
20 A 5.948239
Loading ggplot2 package and creating the boxplots −
library(ggplot2)
ggplot(df,aes(x,y))+geom_boxplot()
Creating the boxplots with wider median lines −
ggplot(df,aes(x,y))+geom_boxplot(fatten=3)s
ggplot(df,aes(x,y))+geom_boxplot(fatten=6)
What is the use of the Configure() method of startup class in C# Asp.net Core?

The configure method is present inside startup class of ASP.NET Core application
The Configure method is a place where you can configure application request pipeline
for your application using IApplicationBuilder instance that is provided by the built-in
IoC container
The Configure method by default has these three parameters IApplicationBuilder,
IWebHostEnvironment and ILoggerFactory .
At run time, the ConfigureServices method is called before the Configure method.
This is to register custom service with the IoC container which can be used in
Configure method.
IWebHostEnvironment :Provides information about the web hosting environment an
application is running in.
IApplicationBuilder:Defines a class that provides the mechanisms to configure an
application's request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
   if (env.IsDevelopment()){
      app.UseDeveloperExceptionPage();
   } else {
      app.UseExceptionHandler("/Error");
      app.UseHsts();
   }
   app.UseHttpsRedirection();
   app.UseStaticFiles();
   app.UseRouting();
   app.UseAuthorization();
   app.UseEndpoints(endpoints =>{
      endpoints.MapRazorPages();
   });
}
How to find row minimum for an R data frame?

Data analysis is a difficult task because it has so much variation in terms of the smaller objectives of a big project. One of the smallest tasks could be finding the minimum value in each row contained in a data frame. For this purpose, we cam use apply function and pass the FUN argument as min so that we can get minimum values.
Consider the below data frame −
 Live Demo
set.seed(101)
x1<-rpois(20,1)
x2<-rpois(20,2)
x3<-rpois(20,5)
df1<-data.frame(x1,x2,x3)
df1
  x1 x2 x3
1 1 3 4
2 0 5 5
3 1 1 6
4 1 2 4
5 0 4 4
6 0 3 3
7 1 0 2
8 0 1 8
9 1 2 7
10 1 2 2
11 2 2 2
12 1 1 4
13 1 1 6
14 3 1 6
15 1 2 5
16 1 4 7
17 2 1 6
18 0 3 5
19 1 0 6
20 0 4 5
Creating a new column Min for minimum of each row −
df1$Min<-apply(df1,1,FUN=min)
df1
x1 x2 x3 Min
1 1 3 4 1
2 0 5 5 0
3 1 1 6 1
4 1 2 4 1
5 0 4 4 0
6 0 3 3 0
7 1 0 2 0
8 0 1 8 0
9 1 2 7 1
10 1 2 2 1
11 2 2 2 2
12 1 1 4 1
13 1 1 6 1
14 3 1 6 1
15 1 2 5 1
16 1 4 7 1
17 2 1 6 1
18 0 3 5 0
19 1 0 6 0
20 0 4 5 0
Let’s have a look at another example −
 Live Demo
y1<-sample(0:9,20,replace=TRUE)
y2<-sample(0:9,20,replace=TRUE)
y3<-sample(0:9,20,replace=TRUE)
y4<-sample(0:9,20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4)
df2
  y1 y2 y3 y4
1  7  2 6 1
2  9  5 4 6
3  9  7 5 0
4  6  5 0 8
5  2  4 7 1
6  1  7 9 1
7  3  2 0 4
8  3  3 3 6
9  5  9 3 7
10 4  3 1 2
11 7  1 7 8
12 5  8 2 5
13 1  0 4 2
14 5 0 7 8
15 0 2 6 5
16 7 4 4 5
17 3 5 7 9
18 5 8 1 4
19 5 0 9 1
20 3 1 3 1
Creating a new column Minimum for minimum of each row −
df2$Minimum<-apply(df2,1,FUN=min)
df2
  y1 y2 y3 y4 Minimum
1  8  9  9  3 3
2  4  4  6  5 4
3  0  1  8  2 0
4  2  8  8  4 2
5  9  1  8  6 1
6  8  4  4  1 1
7  2  2  1  3 1
8  9  8  6  3 3
9  3  9  8  8 3
10 1  6  9  8 1
11 0  3  4  2 0
12 5  0 7 6 0
13 8  7  4 7 4
14 1  3  5 2 1
15 1  7  8 1 1
16 0  9  5 5 0
17 5  9  8 0 0
18 5  3  2 3 2
19 1  3  9 7 1
20 8  2  6 2 2
strtof function in C

22 Jul, 2019
Parses the C-string str(assumed) interpreting its content as a floating-point number (according to the current locale ) and returns its value as a float. If endptr(end pointer) is not a null pointer, the function also sets the value of endptr to point to the first character after the number.
Syntax:
strtof(const char* str, char **endptr)
Parameters:
str : String object with the representation of floating point number
endptr : Reference to an already allocated object of type char*, 
whose value is set by the function to the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.
Return Value : On success, the function returns the
 converted floating-point number as a value of type float.
// C code to convert string having// floating point as its content// using strtof function  #include <stdio.h>#include <stdlib.h> // Header file containing strtof function  int main(){    // Character array to be parsed    char array[] = "365.25 7.0";      // Character end pointer    char* pend;      // f1 variable to store float value    float f1 = strtof(array, &pend);      // f2 variable to store float value    float f2 = strtof(pend, NULL);      // Printing parsed float values of f1 and f2    printf("%.2f\n%.2f\n", f1, f2);      // Performing operation on the values returned    printf(" One year has %.2f weeks \n", f1 / f2);      return 0;}
Output:
365.25
7.0
One year has 52.18 weeks
This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nidhi_biet
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs
Mahotas – Haar Transform

10 Jun, 2021
In this article we will see how we can do image haar transform in mahotas. The haar wavelet is a sequence of rescaled “square-shaped” functions which together form a wavelet family or basis. Wavelet analysis is similar to Fourier analysis in that it allows a target function over an interval to be represented in terms of an orthonormal basis. The Haar sequence is now recognised as the first known wavelet basis and extensively used as a teaching example. In this tutorial we will use “luispedro” image, below is the command to load it.  
mahotas.demos.load('luispedro')
Below is the luispedro image  
In order to do this we will use mahotas.haar method  
Syntax : mahotas.haar(img)Argument : It takes image object as argumentReturn : It returns image object  
Note : Input image should be filtered or should be loaded as greyIn order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this 
image = image[:, :, 0]
Example 1:  
Python3
# importing various librariesimport numpy as npimport mahotasimport mahotas.demosfrom mahotas.thresholding import soft_thresholdfrom pylab import imshow, showfrom os import path # loading imagef = mahotas.demos.load('luispedro', as_grey = True)  # showing imageprint("Image") imshow(f)show() # haar transformh = mahotas.haar(f) # showing imageprint("Image with haar transform")imshow(h)show()
Output :  
Example 2:  
Python3
# importing required librariesimport mahotasimport numpy as npfrom pylab import imshow, showimport os  # loading imageimg = mahotas.imread('dog_image.png') # filtering imageimg = img[:, :, 0]  # showing imageprint("Image") imshow(img)show() # haar transformh = mahotas.haar(img) # showing imageprint("Image with haar transform")imshow(h)show()
Output :  
 
arorakashish0911
Python-Mahotas
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 – Print dictionary of list values

28 Nov, 2021
In this article, we will print a dictionary of list values. Dictionary of list values means a dictionary  contains values as a list of dictionaries
Example:
{‘key1’: [{‘key1′: value,......,’key n’: value}........{‘key1′: value,......,’key n’: value}}],
————————
————————
‘keyn’: [{‘key1′: value,......,’key n’: value}........{‘key1′: value,......,’key n’: value}}]}
So we have to get the dictionaries present in the list according to the key. We can get this by using dict.items().
Syntax:
d.items()
we can iterate over the dictionary using for loop
for key,values in data.items():
     for i in values:
          print(key," : ",i)
Example 1: Python code to create a dictionary with student names as key and values as subject details
Python3
# create a dictionary# with student names as key# values as subject detailsdata = {'manoja': [{'subject1': "java", 'marks': 98},                    {'subject2': "PHP", 'marks': 89}],        'manoj': [{'subject1': "java", 'marks': 78},                   {'subject2': "PHP", 'marks': 79}]}  # get the list of data# using items() methodfor key, values in data.items():    for i in values:        print(key, " : ", i)
Output:
manoja  :  {'subject1': 'java', 'marks': 98}
manoja  :  {'subject2': 'PHP', 'marks': 89}
manoj  :  {'subject1': 'java', 'marks': 78}
manoj  :  {'subject2': 'PHP', 'marks': 79}
Example 2:
Python3
# create a dictionary# with student names as key# values as subject detailsdata = {'manoja': [{'subject1': "java", 'marks': 98},                    {'subject2': "PHP", 'marks': 89}],        'manoj': [{'subject1': "java", 'marks': 78},                  {'subject2': "PHP", 'marks': 79}],        'ramya': [{'subject1': "html", 'marks': 78}]}  # get the list of data# using items() methodfor key, values in data.items():    for i in values:        print(key, " : ", i)
Output:
manoja  :  {'subject1': 'java', 'marks': 98}
manoja  :  {'subject2': 'PHP', 'marks': 89}
manoj  :  {'subject1': 'java', 'marks': 78}
manoj  :  {'subject2': 'PHP', 'marks': 79}
ramya  :  {'subject1': 'html', 'marks': 78}
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
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
Python | os.path.join() method
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
Tryit Editor v3.7

Tryit: Styling textarea
How to get services on remote computers with PowerShell?

To get service on the remote computer(s), simply you need to add parameter – ComputerName and provide remote servers computer name or IP address.
In the below example, we are getting services information on remote computer Win7 which has Automatic start-type.
Get-Service -ComputerName Win7 | Where{$_.StartType -eq "Automatic"}
Similarly, you can connect multiple computers separated by comma (,) in – ComputerName parameter.
Get-Service -ComputerName Win7, TestPC | Where{$_.StartType -eq "Automatic"}
If you need to identify on which particular computer(s), services exist, you can use the machinename property. In the above example, we are adding a machine name property in Pipeline.
Get-Service -ComputerName Win7, TestPC | Where{$_.StartType -eq "Automatic"} |
Select MachineName, Name, Status
How to update a timestamp field of a MySQL table?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> PunchOut timestamp,
   -> PunchStatus tinyint(1)
   -> );
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-01-31 6:30:10',1);
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values('2019-02-06 4:10:13',0);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('2018-12-16 03:00:30',0);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('2016-11-25 02:10:00',1);
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statemen −
mysql> select *from DemoTable;
+---------------------+-------------+
| PunchOut            | PunchStatus |
+---------------------+-------------+
| 2019-01-31 06:30:10 |           1 |
| 2019-02-06 04:10:13 |           0 |
| 2018-12-16 03:00:30 |           0 |
| 2016-11-25 02:10:00 |           1 |
+---------------------+-------------+
4 rows in set (0.00 sec)
Here is the query to update the timestamp field of a MySQL table. We have set current date to the fields with PunchStatus 0 −
Note − Current date and time is 2019-06-30 13:43:45
mysql> update DemoTable set PunchOut=now() where PunchStatus=0;
Query OK, 2 rows affected (0.19 sec)
Rows matched: 2  Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
+---------------------+-------------+
| PunchOut            | PunchStatus |
+---------------------+-------------+
| 2019-01-31 06:30:10 |           1 |
| 2019-06-30 13:43:45 |           0 |
| 2019-06-30 13:43:45 |           0 |
| 2016-11-25 02:10:00 |           1 |
+---------------------+-------------+
4 rows in set (0.00 sec)
Python - Bernoulli Distribution

The Bernoulli distribution is a special case of the Binomial distribution where a single experiment is conducted so that the number of observation is 1. So, the Bernoulli distribution therefore describes events having exactly two outcomes.

We use various functions in numpy library to mathematically calculate the values for a bernoulli distribution. Histograms are created over which we plot the probability distribution curve. 
from scipy.stats import bernoulli
import seaborn as sb

data_bern = bernoulli.rvs(size=1000,p=0.6)
ax = sb.distplot(data_bern,
                  kde=True,
                  color='crimson',
                  hist_kws={"linewidth": 25,'alpha':1})
ax.set(xlabel='Bernouli', ylabel='Frequency')
Its output is as follows −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Explain cherry picking in Git

Cherry picking is a way to choose specific commits from one branch and apply them to another branch. This is useful when you want to select specific changes from a pull request.
git cherry-pick {commit_hash}
The above command will cherry pick the commit associated with the specified commit hash to the current branch.
From the above commits shown in the diagram, we need to apply only commit F1 from the feature branch to the master branch.
In this case, the master branch after cherry picking will look as below.
$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo
$ git init
Initialized empty Git repository in E:/tut_repo/.git/

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ echo hello>hello.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git add .

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git commit -m 'hello'
[master (root-commit) cac1d77] hello
1 file changed, 1 insertion(+)
create mode 100644 hello.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ echo hello 2 >> hello.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git commit -am 'c2'
[master 4f10a5d] c2
1 file changed, 1 insertion(+)

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git branch feature

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git switch feature
Switched to branch 'feature'

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ echo world>world.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git add .

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git commit -m 'F1'
[feature 9b5ddf0] F1
1 file changed, 1 insertion(+)
create mode 100644 world.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ echo world again>>world.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git commit -am 'F2'
[feature 629c15d] F2
1 file changed, 1 insertion(+)

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (feature)
$ git checkout master
Switched to branch 'master'

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* 629c15d (feature) F2
* 9b5ddf0 F1
* 4f10a5d (HEAD -> master) c2
* cac1d77 hello

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ echo hello3>>hello.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git commit -am 'C3'
[master 81cdced] C3
1 file changed, 1 insertion(+)

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* 81cdced (HEAD -> master) C3
| * 629c15d (feature) F2
| * 9b5ddf0 F1
|/
* 4f10a5d c2
* cac1d77 hello

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git cherry-pick 9b5ddf0
[master 693bff8] F1
Date: Tue Mar 30 13:43:50 2021 +0530
1 file changed, 1 insertion(+)
create mode 100644 world.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ git log --oneline --all --graph
* 693bff8 (HEAD -> master) F1
* 81cdced C3
| * 629c15d (feature) F2
| * 9b5ddf0 F1
|/
* 4f10a5d c2
* cac1d77 hello

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ ls
hello.txt world.txt

$ dell@DESKTOP-N961NR5 MINGW64 /e/tut_repo (master)
$ cat world.txt
world
How I can dynamically import Python module?

To dynamically import Python modules, you can use the importlib package's import_module(moduleName) function. You need to have moduleName as a string. For example,
>>> from importlib import import_module
>>> moduleName = "os"
>>> globals()[moduleName] = import_module(moduleName)
If you want to dynamically import a list of modules, you can even call this from a for loop. For example,
>>> import importlib
>>> modnames = ["os", "sys", "math"]
>>> for lib in modnames:
...     globals()[lib] = importlib.import_module(lib)
The globals() call returns a dict. We can set the lib key for each library as the object returned to us on import of a module.
D3.js timer() function - GeeksforGeeks

29 Jul, 2020
The D3.timer() function is used to run a timer function after a particular interval of time. The timer will run after a specified delay. The delay given is in milliseconds.
Syntax:
d3.timer(callback, delay);
Parameters: It takes the following two parameters.
callback: It is a function.
delay: It is the delay after which the function is executed.
Returns: It returns the Time of datatype Number.
Below given are a few examples of the above function.
Example 1:
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"        content="width=device-width,                 initial-scale=1.0">  <title>Document</title></head><style></style><body>  <!-- Fetching from CDN of D3.js -->  <script type = "text/javascript"          src = "https://d3js.org/d3.v4.min.js">  </script>  <script>  let func=function(elapsed) {      console.log(elapsed);      if (elapsed > 500){        console.log("Timer stopped")        timer.stop();      }    }   var timer = d3.timer(func);  </script></body></html>
Output:
Example 2:
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport"        content="width=device-width,                 initial-scale=1.0">  <title>Document</title></head><style>  .originalColor{    height: 100px;    width: 100px;  }  .darkerColor{    height: 100px;    width: 100px;  }</style><body>  <!-- Fetching from CDN of D3.js -->  <script type = "text/javascript"           src = "https://d3js.org/d3.v4.min.js">  </script>  <script>  let func=function(e) {      console.log(e);      if (e>300){        console.log("Timer stopped")        timer.stop();      }    }    // Delay of 2000ms   var timer = d3.timer(func, 2000);  </script></body></html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
numpy.loadtxt() in Python - GeeksforGeeks

11 Dec, 2018
numpy.load() in Python is used load data from a text file, with aim to be a fast reader for simple text files.
Note that each row in the text file must have the same number of values.
Syntax: numpy.loadtxt(fname, dtype=’float’, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
Parameters:fname : File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators should return byte strings for Python 3k.dtype : Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array.delimiter : The string used to separate values. By default, this is any whitespace.converters : A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: converters = {0: datestr2num}. Default: None.skiprows : Skip the first skiprows lines; default: 0.
Returns: ndarray
Code #1:
# Python program explaining # loadtxt() functionimport numpy as geek  # StringIO behaves like a file objectfrom io import StringIO     c = StringIO("0 1 2 \n3 4 5")d = geek.loadtxt(c)  print(d)
Output :
[[ 0.  1.  2.]
 [ 3.  4.  5.]]
 Code #2:
# Python program explaining # loadtxt() functionimport numpy as geek  # StringIO behaves like a file objectfrom io import StringIO     c = StringIO("1, 2, 3\n4, 5, 6")x, y, z = geek.loadtxt(c, delimiter =', ', usecols =(0, 1, 2),                                                 unpack = True)  print("x is: ", x)print("y is: ", y)print("z is: ", z)
Output :
x is:  [ 1.  4.]
y is:  [ 2.  5.]
z is:  [ 3.  6.]
 Code #3:
# Python program explaining # loadtxt() functionimport numpy as geek  # StringIO behaves like a file objectfrom io import StringIO     d = StringIO("M 21 72\nF 35 58")e = geek.loadtxt(d, dtype ={'names': ('gender', 'age', 'weight'),                                  'formats': ('S1', 'i4', 'f4')})  print(e)
Output :
[(b'M', 21,  72.) (b'F', 35,  58.)]

Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python