code-rag-bench/online-tutorials huggingface dataset:
How to Install Scikit-Learn in Windows? - GeeksforGeeks

21 Sep, 2021
Scikit Learn is an open-source Python library that implements a range of machine learning, preprocessing, cross-validation, and visualization algorithms using a unified interface.
In this article, we will look into how to install the Scikit-Learn library in Windows.
The only thing that you need for installing the Twisted framework on Windows are:
Python
PIP or conda (Depending upon user preference)
If you want the installation to be done through conda,  open up the Anaconda Powershell Prompt and use the below command:
conda install -c conda-forge scikit-learn 
Type y for yes when prompted.
You will get a similar message once the installation is complete:
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
Users who prefer to use pip can use the below command to install the Scikit-Learn library on Windows:
pip install scikit-learn
You will get a similar message once the installation is complete:
To verify if Scikit learn library has been successfully installed in your system run the below command:
python -m pip show scikit-learn
If the installation is successful, you’ll get the following message:
Blogathon-2021
how-to-install
Picked
Python scikit-module
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
SQL Query to Create Table With a Primary Key
SQL Query to Convert Datetime to Date
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
C library function - log()

The C library function double log(double x) returns the natural logarithm (base-e logarithm) of x.
Following is the declaration for log() function.
double log(double x)
x − This is the floating point value.
x − This is the floating point value.
This function returns natural logarithm of x.
The following example shows the usage of log() function.
#include <stdio.h>
#include <math.h>

int main () {
   double x, ret;
   x = 2.7;

   /* finding log(2.7) */
   ret = log(x);
   printf("log(%lf) = %lf", x, ret);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
log(2.700000) = 0.993252


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
C Program for Iterative Merge Sort - GeeksforGeeks

06 Dec, 2018
Following is a typical recursive implementation of Merge Sort that uses last element as pivot.
/* Recursive C program for merge sort */#include <stdio.h>#include <stdlib.h>  /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r);  /* l is for left index and r is right index of the sub-array  of arr to be sorted */void mergeSort(int arr[], int l, int r){    if (l < r) {        int m = l + (r - l) / 2; // Same as (l+r)/2 but avoids overflow for large l & h        mergeSort(arr, l, m);        mergeSort(arr, m + 1, r);        merge(arr, l, m, r);    }}  /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */void merge(int arr[], int l, int m, int r){    int i, j, k;    int n1 = m - l + 1;    int n2 = r - m;      /* create temp arrays */    int L[n1], R[n2];      /* Copy data to temp arrays L[] and R[] */    for (i = 0; i < n1; i++)        L[i] = arr[l + i];    for (j = 0; j < n2; j++)        R[j] = arr[m + 1 + j];      /* Merge the temp arrays back into arr[l..r]*/    i = 0;    j = 0;    k = l;    while (i < n1 && j < n2) {        if (L[i] <= R[j]) {            arr[k] = L[i];            i++;        }        else {            arr[k] = R[j];            j++;        }        k++;    }      /* Copy the remaining elements of L[], if there are any */    while (i < n1) {        arr[k] = L[i];        i++;        k++;    }      /* Copy the remaining elements of R[], if there are any */    while (j < n2) {        arr[k] = R[j];        j++;        k++;    }}  /* Function to print an array */void printArray(int A[], int size){    int i;    for (i = 0; i < size; i++)        printf("%d ", A[i]);    printf("\n");}  /* Driver program to test above functions */int main(){    int arr[] = { 12, 11, 13, 5, 6, 7 };    int arr_size = sizeof(arr) / sizeof(arr[0]);      printf("Given array is \n");    printArray(arr, arr_size);      mergeSort(arr, 0, arr_size - 1);      printf("\nSorted array is \n");    printArray(arr, arr_size);    return 0;}
Given array is 
12 11 13 5 6 7 

Sorted array is 
5 6 7 11 12 13

Please refer complete article on Iterative Merge Sort for more details!
Merge Sort
C Programs
Sorting
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
D3.js timer.restart() Function - GeeksforGeeks

29 Jul, 2020
The timer.restart() function in D3.js is used to restart a timer with the given function and delay. The timer.restart() function is used when one wants to reset the timer and start again.
Syntax:
timer.restart(callback, delay);

Parameters: It takes two parameters as mentioned above and described below:
callback: It is the function to be stopped or start after a particular delay.
delay: It is the time after which the function will be executed or stop
Example 1: When no delay is given.
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0"></head>  <body>    <!-- Fetching from CDN of D3.js -->    <script type="text/javascript"         src="https://d3js.org/d3.v4.min.js">    </script>          <script>        count = 0;        let func = function (e) {            console.log(e)            if (e > 40) {                console.log("Timer stopped after 40ms")                if (e > 40) {                    count++;                      // Restarting the timer again                    console.log("Timer restarts")                    timer.restart(func)                }                if (count > 2) {                    timer.stop();                    console.log(                        "count > 2 so timer is stopped")                }            }        }        var timer = d3.timer(func);    </script></body>  </html>
Output:
Example 2: When a delay is given.
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0"></head>  <body>    <!-- Fetching from CDN of D3.js -->    <script type="text/javascript"         src="https://d3js.org/d3.v4.min.js">    </script>          <script>        count = 0;        let func = function (e) {            console.log(e)            if (e > 10) {                console.log("Timer stopped after 10ms")                if (e > 10) {                    count++;                      // Restarting the timer again                    console.log("Timer restarts")                    timer.restart(func)                }                if (count > 4) {                    timer.stop();                    console.log(                    "count > 4 so timer is stopped")                }            }        }        // A 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.
Comments
Old Comments
Convert a string to an integer in JavaScript
Set the value of an input field in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Form validation using HTML and JavaScript
Express.js express.Router() Function
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
Tryit Editor v3.7

Tryit: Video autoplay and muted
Lazy loading of images in table view using Swift

To load an image in table view cell we’ll go through a series of steps.
Create a table view, table view cell and add an Image view to it.
Assign a custom class to the cell we created.
In the cell for row at method write the following lines of code.
let cell = tblView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
return cell
To download the image we’ll create a function and embed that into an extension.
func setImageFromUrl(ImageURL :String) {
   URLSession.shared.dataTask( with: NSURL(string:ImageURL)! as URL, completionHandler: {
      (data, response, error) -> Void in
      DispatchQueue.main.async {
         if let data = data {
            self.image = UIImage(data: data) 
         }
      }
   }).resume()
}
Now embed the same function into an extension of UIImageView to use with any image.
In Cell for row at method the following function, where img is the outlet in custom Class.
cell.img.setImageFromUrl(ImageURL: url)
In this example I’ve used an image from open source "https://homepages.cae.wisc.edu/~ece533/images/boat.png”
When we run the same code on an iPhone 7+ simulator, below is the result −
C++ Relational and Equality Operators

In C Programming, the values hold on in 2 variables will be compared exploitation following operators and relation between them will be determined. These operators are called relational operators. Various C++ relational operators available are-
You can use these operators for checking the relationship between the operands. These operators are mostly used in conditional statements and loops to find a relation between 2 operands and act accordingly. For example,
#include<iostream>
using namespace std;

int main() {
   int a = 3, b = 2;

   if(a < b) {
      cout<< a << " is less than " << b;
   }
   else if(a > b) {
      cout<< a << " is greater than " << b;
   }
   return 0;
}
This will give the output −
3 is greater than 2
The equality operators in C++ are is equal to(==) and is not equal to(!=). They do the task as they are named. The binary equality operators compare their operands for strict equality or inequality. The equality operators, equal to (==) and not equal to (!=), have lower precedence than the relational operators, but they behave similarly. The result type for these operators is bool.The equal-to operator (==) returns true (1) if both operands have the same value; otherwise, it returns false (0). The not-equal-to operator (!=) returns true if the operands do not have the same value; otherwise, it returns false.
#include <iostream>  
using namespace std;  

int main() {  
   cout  << boolalpha  // For printing true and false as true and false in case of a bool result
   << "The true expression 3 != 2 yields: "  
   << (3 != 2) << endl  
   << "The false expression 20 == 10 yields: "  
   << (20 == 10) << endl;  
}
This gives the output −
The true expression 3 != 2 yields: true
The false expression 20 == 10 yields: false
Python Pandas - Get the week of the year on the given Period

To get the week of the year on the given Period, use the period.weekofyear property. At first, import the required libraries −
import pandas as pd
The pandas.Period represents a period of time. Creating two Period objects
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35)
Display the Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)
Get the week of the year from two Period objects
res1 = period1.weekofyear
res2 = period2.weekofyear
Following is the code
import pandas as pd

# The pandas.Period represents a period of time
# creating two Period objects
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35)

# display the Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)

# get the week of the year from two Period objects
res1 = period1.weekofyear
res2 = period2.weekofyear

# Return the week of the year from the two Period objects
print("\nWeek of the year from the 1st Period object ...\n", res1)
print("\nWeek of the year from the 2nd Period object...\n", res2)
This will produce the following code
Period1...
2020-09-23
Period2...
2021-04-16

Week of the year from the 1st Period object ...
39

Week of the year from the 2nd Period object...
15
Determining the position and length of the match Java regex

The start() method of the java.util.regex.Matcher class returns the starting position of the match (if a match occurred).
Similarly, the end() method of the Matcher class returns the ending position of the match.
Therefore, return value of the start() method will be the starting position of the match and the difference between the return values of the end() and start() methods will be the length of the match.
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
   public static void main(String[] args) {
      int start = 0, len = -1;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\\d+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
         start = matcher.start();
         len = matcher.end()-start;
      }
      System.out.println("Position of the match : "+start);
      System.out.println("Length of the match : "+len);
   }
}
Enter input text:
sample data with digits 12345
Position of the match : 24
Length of the match : 5
Passing a vector to constructor in C++

This is a simple C++ program to pass a vector to a constructor.
Begin
   Declare a class named as vector.
      Declare vec of vector type.
      Declare a constructor of vector class.
         Pass a vector object v as a parameter to the constructor.
         Initialize vec = v.
         Declare a function show() to display the values of vector.
            for (int i = 0; i < vec.size(); i++)
               print the all values of variable i.
   Declare v of vector type.
      Initialize some values into v in array pattern.
   Declare ob as an object against the vector class.
      Pass values of v vector via ob vector object to class vector.
   Call show() function using vector object to show the all values of
   vector v.
End.
 Live Demo
#include <iostream>
#include <vector>
using namespace std;
class Vector {
   vector<int> vec;
   public:
      Vector(vector<int> v) {
         vec = v;
}
void show() {
   for (int i = 0; i < vec.size(); i++)
      cout << vec[i] << " ";
   }
};
int main() {
   vector<int> v = {7,6,5,4};
   Vector ob(v);
   ob.show();
   return 0;
}
7 6 5 4
Can we have a try block without a catch block in Java?


Yes, It is possible to have a try block without a catch block by using a final block.
As we know, a final block will always execute even there is an exception occurred in a try block, except System.exit() it will execute always.
public class TryBlockWithoutCatch {
   public static void main(String[] args) {
      try {
         System.out.println("Try Block");
      } finally {
         System.out.println("Finally Block");
      }
   }
}
Try Block
Finally Block
A final block will always execute even though the method has a return type and try block returns some value.
public class TryWithFinally {
   public static int method() {
      try {
         System.out.println("Try Block with return type");
         return 10;
      } finally {
         System.out.println("Finally Block always execute");
      }
   }
   public static void main(String[] args) {
      System.out.println(method());
   }
}
Try Block with return type
Finally Block always execute
10
jsoup - Parsing String

Following example will showcase parsing an HTML String into a Document object.
Document document = Jsoup.parse(html);

Where
document − document object represents the HTML DOM.
document − document object represents the HTML DOM.
Jsoup − main class to parse the given HTML String.
Jsoup − main class to parse the given HTML String.
html − HTML String.
html − HTML String.
The parse(String html) method parses the input HTML into a new Document. This document object can be used to traverse and get details of the html dom.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupTester {
   public static void main(String[] args) {
   
      String html = "<html><head><title>Sample Title</title></head>"
         + "<body><p>Sample Content</p></body></html>";
      Document document = Jsoup.parse(html);
      System.out.println(document.title());
      Elements paragraphs = document.getElementsByTag("p");
      for (Element paragraph : paragraphs) {
            System.out.println(paragraph.text());
      }
   }
}
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester

See the result.
Sample Title
Sample Content

 Print
 Add Notes
 Bookmark this page
Mahotas - Hit & Miss transform - GeeksforGeeks

10 Jul, 2020
In this article we will see how we can perform hit and miss transform in mahotas. In mathematical morphology, hit-or-miss transform is an operation that detects a given configuration in a binary image, using the morphological erosion operator and a pair of disjoint structuring elements.
In order to do this we will use mahotas.hitmiss method
Syntax : mahotas.hitmiss(img, template)
Argument : It takes two numpy ndarray as argument
Return : It returns ndarray
Below is the implementation
# importing required librariesimport mahotas as mhimport numpy as npfrom pylab import imshow, show    # creating region# numpy.ndarrayregions = np.zeros((10, 10), bool)    # setting 1 value to the regionregions[1, :2] = 1regions[5:8, 6: 8] = 1regions[8, 0] = 1      # showing the image with interpolation = 'nearest'print("Image")imshow(regions, interpolation ='nearest')show()   # template for hit misstemplate = np.array([            [0, 1, 1],            [0, 1, 1],            [0, 1, 1]])   # hit miss transformimg = mahotas.hitmiss(regions, template)  # showing imageprint("Image after hit miss transform")imshow(img)show()
Output :
Image
Image after hit miss transform
Another example
# importing required librariesimport mahotas as mhimport numpy as npfrom pylab import imshow, show    # creating region# numpy.ndarrayregions = np.zeros((10, 10), bool)    # setting 1 value to the regionregions[2:3, :3] = 1regions[7:, 7:] = 1      # showing the image with interpolation = 'nearest'print("Image")imshow(regions, interpolation ='nearest')show()   # template for hit misstemplate = np.array([            [0, 1, 1],            [0, 1, 1],            [0, 1, 1]])   # hit miss transformimg = mahotas.hitmiss(regions, template)  # showing imageprint("Image after hit miss transform")imshow(img)show()
Output :
Image
Image after hit miss transform
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
VBA - IsArray Function

The IsArray Function returns a boolean value that indicates whether or NOT the specified input variable is an array variable.
IsArray(variablename)

Add a button and add the following function.
Private Sub Constant_demo_Click()
   Dim a,b as Variant
   a = array("Red","Blue","Yellow")
   b = "12345"
  
   msgbox("The IsArray result 1 : " & IsArray(a))
   msgbox("The IsArray result 2 : " & IsArray(b))
End Sub
When you execute the above function, it produces the following output.
The IsArray result 1 : True
The IsArray result 2 : False


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Difference between Scanner and BufferReader Class in Java

Scanner and BufferReader both classes are used to read input from external system. Scanner is normally used when we know input is of type string or of primitive types and BufferReader is used to read text from character streams while buffering the characters for efficient reading of characters. Following are the important differences between Scanner class and a BufferReader class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class JavaTester {
   public static void main(String args[]) throws NumberFormatException, IOException {
      BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter an number:");
      int a = Integer.parseInt(bufferReader.readLine());
      System.out.printf("You entered: " + a);
      Scanner scanner = new Scanner(System.in);
      System.out.println("\nEnter an number:");
      a = scanner.nextInt();
      System.out.printf("You entered: " + a);
   }
}
Enter an number:
1
You entered: 1
Enter an number:
2
You entered: 2
Find the count of unique group combinations in an R data frame.

To find the count of unique group combinations in an R data frame, we can use count
function of dplyr package along with ungroup function.
For Example, if we have a data frame called df that contains three grouping columns say
G1, G2, and G3 then we can count the unique group combinations in df by using the
below given command −
count(df,G1,G2,G3)%%ungroup()
Following snippet creates a sample data frame −
Grp1<-sample(1:2,20,replace=TRUE)
Grp2<-sample(1:2,20,replace=TRUE)
Grp3<-sample(1:2,20,replace=TRUE)
df1<-data.frame(Grp1,Grp2,Grp3)
df1
The following dataframe is created
 Grp1 Grp2 Grp3
 1 2   1   1
 2 1   2   1
 3 2   1   2
 4 2   2   1
 5 1   1   1
 6 1   1   2
 7 2   1   1
 8 2   1   2
 9 2   1   2
10 1   1   1
11 2   1   1
12 2   1   1
13 2   2   2
14 2   1   2
15 1   2   2
16 2   2   1
17 2   1   2
18 2   2   1
19 1   1   2
20 2   2   2
To load dplyr package and count the unique group combinations in df1 on the above
created data frame, add the following code to the above snippet −
Grp1<-sample(1:2,20,replace=TRUE)
Grp2<-sample(1:2,20,replace=TRUE)
Grp3<-sample(1:2,20,replace=TRUE)
df1<-data.frame(Grp1,Grp2,Grp3)
library(dplyr)
count(df1,Grp1,Grp2,Grp3)%%ungroup()
If you execute all the above given snippets as a single program, it generates the
following Output −
Grp1 Grp2 Grp3 n
1 1    1   1   2
2 1    1   2   2
3 1    2   1   1
4 1    2   2   1
5 2    1   1   4
6 2    1   2   5
7 2    2   1   3
8 2    2   2   2
Following snippet creates a sample data frame −
Class1<-sample(c("First","Second","Third"),20,replace=TRUE)
Class2<-sample(c("First","Second","Third"),20,replace=TRUE)
Class3<-sample(c("First","Second","Third"),20,replace=TRUE)
df2<-data.frame(Class1,Class2,Class3)
df2
The following dataframe is created
  Class1  Class2 Class3
 1 First  Second Second
 2 Second Third  Second
 3 Third  Second Third
 4 First  Third  Second
 5 Second Third  First
 6 Second Third  First
 7 First  Second Second
 8 Third  First  Third
 9 Third  Third  Third
10 Second First  Third
11 Third  Second Second
12 Second Second Second
13 Third  Second Second
14 Third  First  Third
15 First  First  First
16 Third  Third  Third
17 Third  Third  Third
18 First  Third  Third
19 Third  Second First
20 Second Second Second
To count the unique group combinations in df2 on the above created data frame, add the
following code to the above snippet −
Class1<-sample(c("First","Second","Third"),20,replace=TRUE)
Class2<-sample(c("First","Second","Third"),20,replace=TRUE)
Class3<-sample(c("First","Second","Third"),20,replace=TRUE)
df2<-data.frame(Class1,Class2,Class3)
count(df2,Class1,Class2,Class3)%%ungroup()
If you execute all the above given snippets as a single program, it generates the
following Output −
  Class1  Class2 Class3 n
 1 First  First  First 1
 2 First  Second Second 2
 3 First  Third  Second 1
 4 First  Third  Third 1
 5 Second First  Third 1
 6 Second Second Second 2
 7 Second Third  First 2
 8 Second Third  Second 1
 9 Third  First  Third 2
10 Third  Second First 1
11 Third  Second Second 2
12 Third  Second Third 1
13 Third  Third  Third 3
Error 1046 No database Selected, how to resolve?

The 1046 error occurs if you forget to select any database before creating a table.
Let us see how and why this error occurs. We will try to create a table without selecting a
database −
mysql> CREATE table MyTable1
   -> (
   -> id int
   -> );
ERROR 1046 (3D000): No database selected
Or
mysql> INSERT into sample values(1);
ERROR 1046 (3D000): No database selected

Look at the output above, we are getting the same 1046 error: “No database selected”
Now, we can resolve this error after selecting any database with the help of USE command −
mysql> USE business;
Database changed

Above, I have included the database with the name ‘business’. After that, we can create the
same table (which we tried creating above) under the database, “business” −
mysql> CREATE table MyTable1
   -> (
   -> id int
   -> );
Query OK, 0 rows affected (0.49 sec)

We can check whether the table is present or not in the “business” database. The query is as
follows −
mysql> SHOW tables like '%MyTable1%';

The following is the output
+---------------------------------+
| Tables_in_business (%MyTable1%) |
+---------------------------------+
| mytable1                        |
+---------------------------------+
1 row in set (0.05 sec)
How to display a value when select a JList item in Java?

A JList is a subclass of JComponent class that allows the user to choose either a single or multiple selections of items. A JList can generate a ListSelectiionListener interface and it includes one abstract method valueChanged(). We can display a value when an item is selected from a JList by implementing MouseListener interface or extending MouseAdapter class and call the getClickCount() method with single-click event (getClickCount() == 1) of MouseEvent class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class JListItemSeletionTest extends JFrame {
   private JList list;
   private JScrollPane jsp;
   private Vector data;
   public JListItemSeletionTest() {
      setTitle("JListItemSeletion Test");
      list = new JList();
      data = new Vector();
      data.addElement("India");
      data.addElement("Australia");
      data.addElement("England");
      data.addElement("England");
      data.addElement("New Zealand");
      data.addElement("South Africa");
      list.setListData(data);
      list.setSelectedIndex(0);
      list.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if (me.getClickCount() == 1) {
               JList target = (JList)me.getSource();
               int index = target.locationToIndex(me.getPoint());
               if (index >= 0) {
                  Object item = target.getModel().getElementAt(index);
                  JOptionPane.showMessageDialog(null, item.toString());
               }
            }
         }
      });
      jsp = new JScrollPane(list);
      add(jsp, BorderLayout.NORTH);
      setSize(400, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JListItemSeletionTest();
   }
}
A Quick, Easy Way to Unpivot Data in Python | by Nik Piepenbreier | Towards Data Science

In a previous post, we took a look at doing three common Excel tasks in Python. Today we’ll take a look a function that, while possible in Excel, is pretty well hidden and kind of clunky. I’m talking about “un-pivoting” data in Excel.
Python and Excel make it incredibly easy to analyze data and to present that analysis in a cross-tab style format. But what if you receive data only in that format? To take on meaningful analysis beyond that, it’s often necessary to spend a good chunk of time to reformat the data. We’ll call that process “un-pivoting”.
Let’s load our dataset into a Pandas dataframe by running:
import pandas as pddf = pd.read_excel('https://github.com/datagy/mediumdata/raw/master/pythonexcel.xlsx')
If you want to explore the data in Excel, you can download the file here.
We can print out the column names by writing the following:
print(df.columns)
This will return:
['Product', 'Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4']
Essentially, we want to turn all the Quarters into a single column (called Quarter), and have the Sales as a separate column. The Pandas Melt function makes this quite easy. We can simply write:
df = df.melt(id_vars = 'Product', var_name = 'Quarter', value_name = 'Sales')
Let’s break this down a little bit:
id_vars: identifies the column to be used as identifier variables
value_vars: the columns to unpivot. Which, if empty, (as is the case here), uses all columns except those identified in id_vars
var_name: assigns a name to the columns that were unpivoted
value_name: assigns a name to to the value column
When we now print out df, we see it returned in a way that looks like this:
Now, say we wanted to do this in good, old Excel. How would we go about this? Up until Excel 2016, this required downloading the Power Query add-on. Beginning with that version, features of the add-on were built into the main version. Let’s begin by opening the dataset. From there:
Select the Data TabWhile having the table selected, select From Table/Range in Get & Transform DataSwitch to the Transform MenuSelect the columns to unpivotClick Unpivot ColumnsSelect Close and Load on the Home TabEnjoy your unpivoted data!
Select the Data Tab
While having the table selected, select From Table/Range in Get & Transform Data
Switch to the Transform Menu
Select the columns to unpivot
Click Unpivot Columns
Select Close and Load on the Home Tab
Enjoy your unpivoted data!
Thanks for reading this article! Be sure to check out my other posts, including Learn How to (easily!!) do 3 Advanced Excel Tasks in Python.
How to create an increment of 10 value once you click a button in JavaScript?

For this, use click() along with parseInt().
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div id="add">10</div>
<div id="sequenceValue"></div>
<button id="addSequenceOf10">addValue10EachTimePressMe</button>
<script>
   addValue = 0;
   $("#addSequenceOf10").click(function() {
      var actualValue = parseInt($("#add").html());
      addValue =addValue+ actualValue;
      $("#sequenceValue").html(addValue);
   });
</script>
</body>
</html>
To run the above program, just save the file name anyName.html(index.html) and right click on
the file and select the option open with live server in VS Code editor.
This will produce the following output −
Now, press the button you will get 10 then 20 30 40.......N; as in the below output −
After clicking one more time, the snapshot is as follows.
This will produce the following output −
How to Install Golang in VScode? - GeeksforGeeks

30 Sep, 2021
GO is a compiled programming language developed by  Robert Griesemer, Rob Pike, and Ken Thompson at Google. It was introduced in 2009 and is also known as golang. In this article, we are going to see how you can set up Visual Code Studio for Go language Development. We are going to install the necessary tools for it.
GO language in Windows
Visual Studio Code
GO Extension for Visual Studio Code
 
First Navigate to this link, it will redirect you to the official download page of GO Language.
Click the Download button to download the installer for Windows.
 
After downloading the installer, start the installation. It will install GO language in your Windows system easily. You can check the version of the language by typing the following command in the terminal.
go version
GOPATH is an Environment variable and it specifies the root of your Go Workspace. By default, the workspace is located at %USERPROFILE%/go for Windows.
Configure GOPATH:
Create a folder called “C:\Projects\Go” in your C drive.
Press win(Windows) + r to open the run dialog.
Press win + r for run dialog
Type sysdm.cpl ,3 in the dialog box and click Ok.
It will open the following Window of system properties. Click the Environment Variables button at the bottom.
Now, in the System Variables section, click on the New button
Set the variable name as GOPATH and its value as C:\Projects\Go and then hit OK.
Now you have successfully configured GOPATH for your Windows system. If you want to check, just open the run dialog by pressing win + r and type %GOPATH%, if it takes you to the root directory that we have set(C:\Projects\Go) then the configuration was successful.
 
Visual Studio Code is a lightweight but Powerful IDE & Code editor for Windows, macOS, and Linux. Follow these steps to install Visual Studio Code;
First, Navigate to this URL.
Click Download VS Code for Your Operating system. You can easily install it on Windows, Mac or Linux.
 
After installation, open VS code and click on the Extension manager button in the left side panel, you can also do it by pressing Ctrl + Shift + x.
In the Search panel simply type Go or golang.
Now in the search results, you will see the GO extension by the GO team at Google, open it and hit the install button. Let the installation process finish.
GO Extension
After this, press Ctrl + Shift + p to open the command palette and run the following command –
Go: Install/Update Tools
You will see the list of tools to install, select everything, and hit Install
Now you can start developing in Golang.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Simple Substitution Cipher

Simple substitution cipher is the most commonly used cipher and includes an algorithm of substituting every plain text character for every cipher text character. In this process, alphabets are jumbled in comparison with Caesar cipher algorithm.
Keys for a simple substitution cipher usually consists of 26 letters. An example key is −
plain alphabet : abcdefghijklmnopqrstuvwxyz
cipher alphabet: phqgiumeaylnofdxjkrcvstzwb

An example encryption using the above key is−
plaintext : defend the east wall of the castle
ciphertext: giuifg cei iprc tpnn du cei qprcni

The following code shows a program to implement simple substitution cipher −
import random, sys

LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
   message = ''
   if len(sys.argv) > 1:
      with open(sys.argv[1], 'r') as f:
         message = f.read()
   else:
      message = raw_input("Enter your message: ")
   mode = raw_input("E for Encrypt, D for Decrypt: ")
   key = ''
   
   while checkKey(key) is False:
      key = raw_input("Enter 26 ALPHA key (leave blank for random key): ")
      if key == '':
         key = getRandomKey()
      if checkKey(key) is False:
		print('There is an error in the key or symbol set.')
   translated = translateMessage(message, key, mode)
   print('Using key: %s' % (key))
   
   if len(sys.argv) > 1:
      fileOut = 'enc.' + sys.argv[1]
      with open(fileOut, 'w') as f:
         f.write(translated)
      print('Success! File written to: %s' % (fileOut))
   else: print('Result: ' + translated)

# Store the key into list, sort it, convert back, compare to alphabet.
def checkKey(key):
   keyString = ''.join(sorted(list(key)))
   return keyString == LETTERS
def translateMessage(message, key, mode):
   translated = ''
   charsA = LETTERS
   charsB = key
   
   # If decrypt mode is detected, swap A and B
   if mode == 'D':
      charsA, charsB = charsB, charsA
   for symbol in message:
      if symbol.upper() in charsA:
         symIndex = charsA.find(symbol.upper())
         if symbol.isupper():
            translated += charsB[symIndex].upper()
         else:
            translated += charsB[symIndex].lower()
				else:
               translated += symbol
         return translated
def getRandomKey():
   randomList = list(LETTERS)
   random.shuffle(randomList)
   return ''.join(randomList)
if __name__ == '__main__':
   main()
You can observe the following output when you implement the code given above −

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python – Ascending Order Sort grouped Pandas dataframe by group size?

To group Pandas dataframe, we use groupby(). To sort grouped dataframe in ascending order, use sort_values(). The size() method is used to get the dataframe size.
For ascending order sort, use the following in sort_values() −
ascending=True
At first, create a pandas dataframe −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],

      "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
   }
)
Next, group according to Reg_Price column and sort in ascending order −
dataFrame.groupby('Reg_Price').size().sort_values(ascending=True)
Following is the code −
import pandas as pd

# dataframe with one of the columns as Reg_Price
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],

      "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
   }
)

print"DataFrame...\n",dataFrame

# group according to Reg_Price column and sort in ascending order
print"\nSorted in Ascending order...";
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=True))
This will produce the following output−
DataFrame...
        Car Reg_Price
0       BMW      1000
1     Lexus      1400
2      Audi      1000
3  Mercedes       900
4    Jaguar      1700
5   Bentley       900

Sorted in Ascending order...
Reg_Price
1400    1
1700    1
900     2
1000    2
dtype: int64
How to find time difference using Python?

It is very easy to do date and time maths in Python using time delta objects. Whenever you want to add or subtract to a date/time, use a DateTime.datetime(), then add or subtract date time.time delta() instances. A time delta object represents a duration, the difference between two dates or times. The time delta constructor has the following function signature
DateTime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])¶
Note: All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here https://docs.python.org/2/library/datetime.html#timedelta-objects
An example of using the time delta objects and dates
import datetime
old_time = datetime.datetime.now()
print(old_time)
new_time = old_time - datetime.timedelta(hours=2, minutes=10)
print(new_time)
This will give the output
2018-01-04 11:09:00.694602
2018-01-04 08:59:00.694602
time delta() arithmetic is not supported for date time.time() objects; if you need to use offsets from an existing date time.time() object, just use date time.datetime.combine() to form a date time.date time() instance, do your calculations, and 'extract' the time again with the .time() method.
Subtracting 2 date time objects gives a time delta object. This time delta object can be used to find the exact difference between the 2 date times. 
t1 = datetime.datetime.now()
t2 = datetime.datetime.now()
print(t1 - t2)
print(type(t1 - t2))
This will give the output
-1 day, 23:59:56.653627
<class 'datetime.timedelta'>
Get the item that appears the most times in an array JavaScript

Let’s say, we are required to write a function that takes in an array of string / number literals and
returns the index of the item that appears for the most number of times. We will iterate over the
array and prepare a frequencyMap and from that map we will return the index that makes most
appearances.
The code for doing so will be −
const arr1 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34, 65, 34, 22, 67, 34];
const arr2 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34];
const mostAppearances = (arr) => {
   const frequencyMap = {};
   arr.forEach(el => {
      if(frequencyMap[el]){
         frequencyMap[el]++;
      }else{
         frequencyMap[el] = 1;
      };
   });
   let highest, frequency = 0;
   Object.keys(frequencyMap).forEach(key => {
      if(frequencyMap[key] > frequency){
         highest = parseInt(key, 10);
         frequency = frequencyMap[key];
      };
   });
   return arr.indexOf(highest);
};
console.log(mostAppearances(arr1));
console.log(mostAppearances(arr2));
The output in the console will be −
6
1
How to create a histogram using weights in R?

A histogram using weights represent the weighted distribution of the values. In R, we can use weighted.hist function of plotrix package to create this type of histogram and we just need the values and weights corresponding to each value. Since plotrix is not frequently used, we must make sure that we install this package using install.packages("plotrix") then load it in R environment.
Loading plotrix package −
library("plotrix")
Consider the below vector and the weight associated with that vector −
x<-sort(rpois(5000,5))
weight<-seq(1,5000)
Creating weighted histogram for x −
Let’s have a look at another example −
y<-sort(sample(0:100,2000,replace=TRUE)) 
weight<-seq(1,2000) \
weighted.hist(y,weight)
How to Extend an Array After Initialisation in Java? - GeeksforGeeks

05 Aug, 2021
In java, the arrays are immutable i.e if the array is once assigned or instantiated the memory allocated for the array can’t be decreased or increased. But there is one form of a solution in which we can extend the array.
Extending an array after initialization: As we can’t modify the array size after the declaration of the array, we can only extend it by initializing a new array and copying the values of the old array to the new array, and then we can assign new values to the array according to the size of the array declared.
Below are the examples to show extending the array after initialization.
Example 1:
Java
// java program to demonstrate// extending an arrayimport java.lang.*; class ExtendingArray {       public static void main(String[] args)    {         // initializing string array        String[] words = new String[] { "G", "E", "E" };         // allocating space for 5 strings        // in the extended array        String[] extendWords = new String[5];         // adding new string        // at index 3 and 4        extendWords[3] = "K";        extendWords[4] = "S";         // copying the array elements        // to new extended array        System.arraycopy(words, 0, extendWords, 0,                         words.length);         // printing the extended array        // elements        for (String str : extendWords) {            System.out.print(str);        }    }}
GEEKS
Example 2: 
Java
// Java program to demonstrate// extending an array import java.lang.*; class ExtendingArray {       public static void extendedArray()    {         // initializing integers to array int        int[] num = new int[] { 1, 2, 3, 4, 5, 6 };         // allocating space for 10 integers        int[] extendnum = new int[10];         // adding new integers        // at index 6,7,8,9        extendnum[6] = 7;        extendnum[7] = 8;        extendnum[8] = 9;        extendnum[9] = 10;         // copying old array to new array        System.arraycopy(num, 0, extendnum, 0, num.length);         // print the elements of        // extended array using for-each        for (int str : extendnum)            System.out.println(str);    }    public static void main(String[] args)    {         // create an instance        ExtendingArray exarr = new ExtendingArray();         // extend an array and print them        exarr.extendedArray();    }}
1
2
3
4
5
6
7
8
9
10
 
surinderdawra388
as5853535
Java-Array-Programs
Java-Arrays
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
GATE | GATE CS 2012 | Question 51 - GeeksforGeeks

28 Jun, 2021
Table A
Id   Name    Age
----------------
12   Arun    60
15   Shreya  24
99   Rohit   11


Table B
Id   Name   Age
----------------
15   Shreya  24
25   Hari    40
98   Rohit   20
99   Rohit   11


Table C
Id   Phone  Area
-----------------
10   2200   02  
99   2100   01
Consider the above tables A, B and C. How many tuples does the result of the following SQL query contains?
SELECT A.id 
FROM   A 
WHERE  A.age > ALL (SELECT B.age 
                    FROM   B 
                    WHERE  B. name = "arun") 

(A) 4(B) 3(C) 0(D) 1Answer: (B)Explanation: The meaning of “ALL” is the A.Age should be greater than all the values returned by the subquery. There is no entry with name “arun” in table B. So the subquery will return NULL. If a subquery returns NULL, then the condition becomes true for all rows of A (See this for details). So all rows of table A are selected.
Source: https://www.geeksforgeeks.org/database-management-system-set-3/Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2004 | Question 3
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2006 | Question 49
GATE | GATE CS 2019 | Question 27