code-rag-bench/online-tutorials huggingface dataset:
HTML | Window scrollBy() method - GeeksforGeeks

30 Jul, 2019
The window.scrollBy() method is used to scroll the document by given number of pixels.
Syntax:
window.scrollBy( xcoordinate, ycoordinate );
or
window.scrollBy(options);
Parameters: This method accepts two parameters as mentioned above and described below:
x-coordinate: It is the horizontal pixel value which indicates how much you want to scroll the document (in terms of px).
y-coordinate: It is the vertical pixel value which indicates how much you want to scroll the document (in terms of px).
Note: You can find these options in options in ScrollToOptions dictionary.
Example 1: Scroll horizontally
<!DOCTYPE html><html>      <head>    <title>        HTML | DOM window scrollby() method    </title>          <style>        body {            width: 5000px;        }        a:focus {            background-color: magenta;        }        button {            position: fixed;        }    </style></head>  <body>    <h1 style="color:green;">         GeeksforGeeks     </h1>      <h2>HTML DOM Window.scrollBy() method</h2>      <button onclick="scrollby()">        Scroll horizontally!    </button>          <br><br>      <script>        function scrollby() {            window.scrollBy(100, 0);        }    </script></body>  </html>
Output:
Example 2: Using options
<!DOCTYPE html><html>  <head>    <title>        HTML | DOM Window scrollBy() method    </title>          <style>        body {            width: 5000px;            height:5000px;        }        a:focus {            background-color: magenta;        }        button {            position: fixed;        }    </style></head>  <body>    <h1 style="color:green;">         GeeksForGeeks     </h1>      <h2>HTML DOM Window.scrollBy() method</h2>      <div>        <button onclick="scrollWin(0, 50)">            Scroll down        </button>                  <br><br>                  <button onclick="scrollWin(0, -50)">            Scroll up        </button>                  <br><br>                  <button onclick="scrollWin(50, 0)">            Scroll right        </button>                  <br><br>                  <button onclick="scrollWin(-50, 0)">            Scroll left        </button>    </div>      <script>        function scrollWin(x, y) {            window.scrollBy(x, y);        }    </script></body>  </html>                    
Output:
Supported Browsers: The browser supported by HTML DOM Window scrollBy() method are listed below:
Google Chrome 45
Firefox
Opera 32
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
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 ?
Difference between var, let and const keywords in JavaScript
Convert PDF to Image using Python - GeeksforGeeks

21 Jan, 2021
Many tools are available on the internet for converting a PDF to an image. In this article, we are going to write code for converting pdf to image and make a handy application in python. Before writing the code we need to install the required module pdf2image and poppler.
pdf2image 1.14.0: This module converts a PDF to a PIL object. To install this module type the below command in the terminal.
pip install pdf2image
poppler: This module allows to read, render, or modify PDF documents. Windows users will have to build or download poppler for Windows. click here to download
 You will then have to add the bin/ folder to PATH or use
 poppler_path = r”C:\path\to\poppler-xx\bin” as an argument in convert_from_path.
Approach:
Import the pdf2image module
Store a PFD with convert_from_path()
Save image with save()
Below is the Implementation.
PDF File used:
Python
# import modulefrom pdf2image import convert_from_path  # Store Pdf with convert_from_path functionimages = convert_from_path('example.pdf') for i in range(len(images)):         # Save pages as images in the pdf    images[i].save('page'+ str(i) +'.jpg', 'JPEG')
  
Output:
 
 
Let’s write code for Application Using Tkinter: This Script implements the above Implementation into a GUI.
 
Below is the Implementation.
 
Python3
from pdf2image import convert_from_pathfrom tkinter import *from tkinter import messagebox  def pdf2img():    try:        images = convert_from_path(str(e1.get()))        for img in images:            img.save('new_folder\output.jpg', 'JPEG')     except  :        Result = "NO pdf found"        messagebox.showinfo("Result", Result)     else:        Result = "success"        messagebox.showinfo("Result", Result)   master = Tk()Label(master, text="File Location").grid(row=0, sticky=W) e1 = Entry(master)e1.grid(row=0, column=1) b = Button(master, text="Convert", command=pdf2img)b.grid(row=0, column=2,columnspan=2, rowspan=2,padx=5, pady=5)  mainloop()
  
Output:
 
 
If there is no PDF file at your given location.
 
 
ashwinbeec16
python-utility
Python
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
p5.js | minute() function - GeeksforGeeks

08 Apr, 2019
The minute() function in p5.js is used to return the current minute in the system clock. The value of minute() function lies between 0 to 59.
Syntax:
minute()
Parameters: The function does not accept any parameter.
Return Value: This function returns an integer value which represents the minute time.
Below program illustrates the minute() function in p5.js:
Example: This example uses minute() function to return the current minute in the system clock.
function setup() {      // Create Canvas of size 270*80    createCanvas(270, 80);}  function draw() {          // Set the background color    background(220);          // Initialize the parameter with     // current minute    let m = minute();      // Set the text font size    textSize(16);          // Set the text color    fill(color('red'));      // Display the result    text("Current minute is : "+m, 50, 30);}
Output:
Reference: https://p5js.org/reference/#/p5/minute
JavaScript-p5.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 ?
How to insert spaces/tabs in text using HTML/CSS?
Python | Pandas Timestamp.to_pydatetime - GeeksforGeeks

27 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.to_pydatetime() function convert a Timestamp object to a native Python datetime object.
Syntax :Timestamp.to_pydatetime()
Parameters :
warn : boolean
Return : datetime object
Example #1: Use Timestamp.to_pydatetime() function to convert the given Timestamp to a native python datetime object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                   hour = 10, second = 49, tz = 'US/Central')   # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_pydatetime() function to convert the given Timestamp to python’s datetime object.
# convert to datetimets.to_pydatetime()
Output :
As we can see in the output, the Timestamp.to_pydatetime() function has returned a native python datetime object constructed from the given Timestamp object.
Example #2: Use Timestamp.to_pydatetime() function to convert the given Timestamp to a native python datetime object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                   hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_pydatetime() function to convert the given Timestamp to python’s datetime object.
# convert to datetimets.to_pydatetime()
Output :
As we can see in the output, the Timestamp.to_pydatetime() function has returned a native python datetime object constructed from the given Timestamp object.
Python Pandas-Timestamp
Python-pandas
Python
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()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
Python - Distance between collections of inputs - GeeksforGeeks

10 Jan, 2020
scipy.stats.cdist(array, axis=0) function calculates the distance between each pair of the two collections of inputs.
Parameters :array: Input array or object having the elements to calculate the distance between each pair of the two collections of inputs.axis: Axis along which to be computed. By default axis = 0
Returns : distance between each pair of the two collections of inputs.
Code #1 : 2D Array
from scipy.spatial.distance import cdista = [[1, 3, 27], [3, 6, 8]]arr1 = cdist(a, a)   print("Value of cdist is :", arr1) 
Output:
Value of cdist is : [[ 0.         19.33907961]
 [19.33907961  0.        ]]

Code #2 : 3D Array
from scipy.spatial.distance import cdist   arr1 = [[1, 3, 27],          [3, 4, 6],          [7, 6, 3],          [3, 6, 8]]       print("Value of cdist is :", cdist(arr1, arr1))  
Output:
Value of cdist is : [[ 0.         21.11871208 24.91987159 19.33907961]
 [21.11871208  0.          5.38516481  2.82842712]
 [24.91987159  5.38516481  0.          6.40312424]
 [19.33907961  2.82842712  6.40312424  0.        ]]

Python scipy-stats-functions
Python-scipy
Python
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Storage of integer and character values in C

We have used the integer and character variables many times in our program. Here we will see how they are stored in the memory.
In C the character values are also stored as integers. In the following code, we shall put 270 into a character type data. So the binary equivalent of 270 is 100001110, but takes only first 8-bits from right. So the result will be (00001110), that is 14. Then stores the value into variable a. It also gives warning for overflow.
In the next variable y, we are trying to store negative number say -130. The negative number will be stored as 2’s complemented method. So the binary of 130 is (10000010). The 2’s complemented value is 01111101 + 1 = 01111110. Here also the right most 8-bits are taken. So the result will be (01111110) = 126
#include <stdio.h>
int main() {
   char x = 270;
   char y = -130;
   printf("The value of x is: %d\n", x);
   printf("The value of y is: %d", y);
}
The value of x is: 14
The value of y is: 126
How to apply NOW() to timestamps field in MySQL Workbench?

Let us first create a table −
create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ShippingDate timestamp
);
Insert some records in the table using insert command. Here, we have included the current date with NOW() −
INSERT INTO DemoTable(ShippingDate) VALUES(now());
Display all records from the table using select statement −
SELECT *FROM DemoTable;
Following is the screenshot of query in MySQL workbench to set NOW() to timestamp field “ShippingDate”. The query also displays the output below −
How to iterate over an Array using for loop in Golang? - GeeksforGeeks

05 May, 2020
An array is a data structure of the collection of items of the similar type stored in contiguous locations. For performing operations on arrays, the need arises to iterate through it. A for loop is used to iterate over data structures in programming languages. It can be used here in the following ways:
Example 1:
// Golang program to iterate over// an Array using for looppackage main  import "fmt"  func main() {      // taking an array    arr := [5]int{1, 2, 3, 4, 5}    fmt.Println("The elements of the array are: ")      // using for loop    for i := 0; i < len(arr); i++ {        fmt.Println(arr[i])    }}
Output:
The elements of the array are:
1
2
3
4
5

Explanation: The variable i is initialized as 0 and is defined to increase at every iteration until it reaches the value of the length of the array. Then the print command is given to print the elements at each index of the array one by one.
Example 2: The for loopcan use another keyword return to perform iterations.
// Golang program to iterate over// an Array using for looppackage main  import "fmt"  func main() {      // taking an array    arr := [5]string{"Ronaldo", "Messi", "Kaka", "James", "Casillas"}    fmt.Println("The elements of the array are:")      // using for loop    for index, element := range arr {        fmt.Println("At index", index, "value is", element)    }}
Output:
The elements of the array are:
At index 0 value is Ronaldo
At index 1 value is Messi
At index 2 value is Kaka
At index 3 value is James
At index 4 value is Casillas

Explanation: Keyword range sets the scope of iteration upto the length of arr. The variables index and element store then indexes and values of the array respectively.
Example 3: When we don’t need the index, we can ignore it with the blank identifier _.
// Golang program to iterate over// an Array using for looppackage main  import "fmt"  func main() {      // taking an array    arr := []int{1, 2, 3, 4, 5}    fmt.Println("The elements of the array are:")      // using for loop    for _, value := range arr {        fmt.Println(value)    }}
Output:
The elements of the array are:
1
2
3
4
5

Golang-Arrays
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
strings.Replace() Function in Golang With Examples
Time Formatting in Golang
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Golang Maps
How to convert a string in lower case in Golang?
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
How to compare times in Golang?
Interfaces in Golang
Bar Chart with negative values

Following is an example of a Bar Chart with negative values.
We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. Now, let us see an example of a basic bar chart with negative values. 
app.component.ts
import { Component } from '@angular/core';
import * as Highcharts from 'highcharts';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   highcharts = Highcharts;
   chartOptions = {   
      chart: {
         type: 'bar'
      },
      title: {
         text: 'Bar chart with negative values'
      },
      xAxis:{
         categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']        
      },     
      series: [
         {
            name: 'John',
            data: [5, 3, 4, 7, 2]
         }, 
         {
            name: 'Jane',
            data: [2, -2, -3, 2, 1]
         }, 
         {
            name: 'Joe',
            data: [3, 4, 4, -2, 5]
         }
      ]
   };
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Integer hashCode() Method in Java

05 Dec, 2018
The java.lang.Integer.hashCode() method of Integer class in Java is used to return the hash code for a particular Integer .
Syntax:
public int hashCode()
Parameters : The method does not take any parameters.
Return Value: The method returns a hash code integer value for this object, which is equal to the uncomplicated primitive integer value, represented by this Integer object.
Below programs illustrate the use of hashCode() of Integer class:Program 1: When integer data type is passed.
// Java program to demonstrate working// of Java.lang.Integer.hashCode() Methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {        // Object s_int created        Integer s_int = new Integer("223");          // Returning a hash code value for this object         int hashcodevalue = s_int.hashCode();        System.out.println("Hash code Value for object = " + hashcodevalue);    }}
Hash code Value for object = 223

Program 2: When String data type is passed.Note: This causes RuntimeErrors like NumberFormatException
// Java program to demonstrate working// of Java.lang.Integer.hashCode() Methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {        // object s_int created        Integer s_int = new Integer("gfg");          // Returning a hash code value for this object.        int hashcodevalue = s_int.hashCode();        System.out.println("Hash code Value for object = " + hashcodevalue);    }}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "gfg"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.(Integer.java:867)
    at Geeks.main(Geeks.java:9)

Java-Functions
Java-Integer
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Frequencies of Values in a Dictionary

01 Oct, 2020
Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_dict = {‘ide’ : 3, ‘Gfg’ : 3, ‘code’ : 2}Output : {3: 2, 2: 1}
Input : test_dict = {10 : 1, 20 : 2, 30 : 1, 40 : 2 }Output : {1 : 2, 2 : 2}
Method #1 : Using defaultdict() + loopThe combination of above functions can be used to solve this problem. In this, we use defaultdict() to initialize the counter dictionary with integers and increment counter in brute force manner using loop.
# Python3 code to demonstrate working of # Dictionary Values Frequency# Using defaultdict() + loopfrom collections import defaultdict  # initializing dictionarytest_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Dictionary Values Frequency# Using defaultdict() + loopres = defaultdict(int)for key, val in test_dict.items():    res[val] += 1      # printing result print("The frequency dictionary : " + str(dict(res))) 
The original dictionary : {'Gfg': 3, 'code': 2, 'ide': 3}
The frequency dictionary : {2: 1, 3: 2}

Method #2 : Using Counter() + values()The combination of above functions can be used to solve this problem. In this, we perform the task of extraction of values using values() and frequency counter using Counter().
# Python3 code to demonstrate working of # Dictionary Values Frequency# Using Counter() + values()from collections import Counter  # initializing dictionarytest_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Dictionary Values Frequency# Using defaultdict() + loopres = Counter(test_dict.values())      # printing result print("The frequency dictionary : " + str(dict(res))) 
The original dictionary : {'code': 2, 'Gfg': 3, 'ide': 3}
The frequency dictionary : {2: 1, 3: 2}

Python dictionary-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
How to run MongoDB shell using mongos command?


In order to launch the MongoDB shell, you need to use mongo command. Following is the syntax −
>mongo
First reach the MongoDB bin directory from command prompt as in the below screenshot −
Here is the command to launch the mongo shell as in the below screenshot −
This will produce the following output −
Python | Pandas Series.nonzero() to get Index of all non zero values in a series

30 Sep, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Series.nonzero() is an argument less method. Just like it name says, rather returning non zero values from a series, it returns index of all non zero values. The returned series of indices can be passed to iloc method and return all non zero values.
Syntax: Series.nonzero()Return type: Array of indices
Example:In this example, a Series is created from a Python List using Pandas Series() method. The series also contains some zero values. After that nonzero() method is called on series and the result is stored in result variable. The result series is then passed to iloc() method to return all non zero values at that indices.
# importing pandas module import pandas as pd     # importing numpy module import numpy as np     # creating listlist =[1, 0, 12, 1, 0, 4, 22, 0, 3, 9]  # creating seriesseries = pd.Series(list)  # calling .nonzero() methodresult = series.nonzero()  # displayprint(result)  # retrieving values using iloc methodvalues = series.iloc[result]  # displayvalues
Output:
(array([0, 2, 3, 5, 6, 8, 9]), )
0     1
2    12
3     1
5     4
6    22
8     3
9     9
dtype: int64

As shown in output, the index position of every non zero elements was returned and the values at that position were returned using iloc method.
Akanksha_Rai
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
What are chrome extensions?

31 Oct, 2019
It is a small program to modify the experience or add functionality to the chrome browser. They are created using web technology like HTML, CSS, JavaScript, etc.The main aim of an extension is to serve a single purpose around which the whole program is built, although it can have multiple components but they should help in accomplishing the main purpose of the program.An extension should have the minimal interface or it can extend to a web page also but main focus is to provide good functionality with less overhead.Extension are zipped into a in .crx package, the user needs to download the package and install it. Chrome extension is published in the Chrome web store.
Some example of chrome extension is:
Password manager
Ads blocker
Adding to-do lists or notes to Chrome
Making it easier to copy text from a site
Let’s create a simple extension just to demonstrate the working procedure:
Every extension require a manifest fileFirst, create a manifest.json file {
    "name": "Hello Extensions",
    "description" : "Base Level Extension",
    "version": "1.0",
    "manifest_version": 2
  }
 {
    "name": "Hello Extensions",
    "description" : "Base Level Extension",
    "version": "1.0",
    "manifest_version": 2
  }
Then, for demonstration we will add an icon to the extension which will on being clicked open a web page created by us.Add this inside the file"browser_action": {
      "default_popup": "hello.html",
      "default_icon": "icon.png"
    }   

"browser_action": {
      "default_popup": "hello.html",
      "default_icon": "icon.png"
    }   

Then add this to include a shortcut to display the HTML page"commands": {
      "_execute_browser_action": {
        "suggested_key": {
          "default": "Ctrl+Shift+F"
        },
        "description": "Opens hello.html"
      }
    }

"commands": {
      "_execute_browser_action": {
        "suggested_key": {
          "default": "Ctrl+Shift+F"
        },
        "description": "Opens hello.html"
      }
    }

Picked
GBlog
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
How to Learn Data Science in 10 weeks?
What is Data Structure: Types, Classifications and Applications
What is Hashing | A Complete Tutorial
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Python – Removing Constant Features From the Dataset

02 Sep, 2020
Those features which contain constant values (i.e. only one value for all the outputs or target values) in the dataset are known as Constant Features. These features don’t provide any information to the target feature. These are redundant data available in the dataset. Presence of this feature has no effect on the target, so it is good to remove these features from the dataset. This process of removing redundant features and keeping only the necessary features in the dataset comes under the filter method of Feature Selection Methods.
Now Let’s see how we can remove constant features in Python.
Consider the self created dataset for the article:
Code: Create DataFrame of the above data
# Import pandas to create DataFrameimport pandas as pd  # Make DataFrame of the given datadata = pd.DataFrame({"Portal":['GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks',                                'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks', 'GeeksforGeeks'],                    "Article's_category":['Python', 'Data Science', 'Data Science', 'Data Science', 'Mathematics',                                           'Python', 'Data Science', 'Mathematics', 'Mathematics'],                    "Views":[545, 1505, 1157, 2541, 5726, 3125, 3131, 6525, 15000]})
Code: Convert the categorical data to numerical data
# import ordinal encoder from sklearnfrom sklearn.preprocessing import OrdinalEncoderord_enc = OrdinalEncoder()  # Transform the datadata[["Portal","Article's_category"]] = ord_enc.fit_transform(data[["Portal","Article's_category"]])
Code: Fit the data to VarianceThreshold.
# import VarianceThresholdfrom sklearn.feature_selection import VarianceThresholdvar_threshold = VarianceThreshold(threshold=0)   # threshold = 0 for constant  # fit the datavar_threshold.fit(data)  # We can check the variance of different features asprint(var_threshold.variances_)
Output: Variance of different features:
[0.00000000e+00 6.17283951e-01 1.76746269e+07]
Code: Transform the data
print(var_threshold.transform(data))print('*' * 10,"Separator",'*' * 10)  # shapes of data before transformed and after transformedprint("Earlier shape of data: ", data.shape)print("Shape after transformation: ", var_threshold.transform(data).shape)
Output:
[[2.000e+00 5.450e+02]
 [0.000e+00 1.505e+03]
 [0.000e+00 1.157e+03]
 [0.000e+00 2.541e+03]
 [1.000e+00 5.726e+03]
 [2.000e+00 3.125e+03]
 [0.000e+00 3.131e+03]
 [1.000e+00 6.525e+03]
 [1.000e+00 1.500e+04]]
********** Separator **********
Earlier shape of data:  (9, 3)
Shape after transformation:  (9, 2)

As you can observe earlier we had 9 observations with 3 features.After transformation we have 9 observations with 2 features. We can clearly observe that the removed feature is ‘Portal’.
data-science
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to upload files using HTML to website ?

31 Oct, 2021
Every file that needs to be uploaded to the website, required the basic form which facilitates uploading. This feature is essential when we are filling the form on a specific website. This file upload may support a variety of file formats along with various types of files. The file uploading feature is one of the essential parts of the form in the website. In this article, we will learn to build the file upload feature in the website using HTML. We will use the concept of HTML <input> tag that will allow the user to upload files to a website.
<input> tag: It is used to specify an input field where the user can enter the required data. The input tag is used within the <form> element to declare input controls that allow users to input data. An input field can be of various types depending upon the attribute type. The Input tag is an empty element that only contains attributes. Here, we have defined a type attribute whose value is set as “file”
Syntax:
<input type = "file"... />
This syntax specifies the file-select field that enables the feature to choose one or more files from their device storage then upload it to a server using the form submission button.
Example: This example illustrates the use of the <input> tag by specifying the type attribute as a file.
HTML
<!DOCTYPE html><html><head>    <title>How to upload files using HTML to website?</title></head>  <body>    <center>        <h1>Welcome to GFG</h1>        <h2>How to upload files using HTML to website?</h2>        <input type="file"                id="file1"                name="upload">    </center></body></html>
Output: In the output, you can see that when the file is chosen and then uploaded, its name is also showing right beside the button.
HTML-Basics
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hierarchically-clustered Heatmap in Python with Seaborn Clustermap

02 Dec, 2020
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas. 
Clustering is basically grouping data based on relationships among the variables in the data.  Clustering algorithms help in getting structured data in unsupervised learning. The most common types of clustering are shown below.
Clustering_types
Here we are going to see hierarchical clustering especially Agglomerative(bottom-up) hierarchical clustering. In Agglomerative clustering, we start with considering each data point as a cluster and then repeatedly combine two nearest clusters into larger clusters until we are left with a single cluster. The graph we plot after performing agglomerative clustering on data is called Dendrogram.
Coming to the heat map, it is a graphical representation of data where values are represented using colors. Variation in the intensity of color depicts how data is clustered or varies over space.
The clustermap() function of seaborn plots a hierarchically-clustered heat map of the given matrix dataset. It returns a clustered grid index. 
Below are some examples which depict the hierarchically-clustered heat map from a dataset:
In the Flights dataset the data(Number of passengers) is clustered based on month and year:
Example 1: 
Python3
# Importing the libraryimport seaborn as snsfrom sunbird.categorical_encoding import frequency_encoding  # Load datasetdata = sns.load_dataset('flights')  # Categorical encodingfrequency_encoding(data, 'month')  # Clustering data row-wise and# changing color of the map.sns.clustermap(data, figsize=(7, 7))
Output :
The legend to the left of the cluster map indicates information about the cluster map e.g bright color indicates more passengers and dark color indicates fewer passengers.     
Example 2:
Python3
# Importing the libraryimport seaborn as snsfrom sunbird.categorical_encoding import frequency_encoding  # Load datasetdata = sns.load_dataset('flights')  # Categorical encodingfrequency_encoding(data, 'month')  # Clustering data row-wise and# changing color of the map.sns.clustermap(data, cmap='coolwarm', figsize=(7, 7))
Output:
Here we have changed the colors of the cluster map.
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
sizeof() Operator in C#

28 May, 2020
The sizeof() operator is used to obtain the size of a data type in bytes in bytes. It will not return the size of the variables or instances. Its return type is always int.
Syntax:
int sizeof(type);
Examples:
Input : sizeof(byte);
Output : 1

Input : sizeof(int);
Output : 4

// C# program to illustrate the // sizeof() operatorusing System;using System.IO;using System.Text;   namespace IncludeHelp{    class Test    {        // Main Method         static void Main(string[] args)        {            Console.WriteLine("sizeof(char)     : {0}", sizeof(char));            Console.WriteLine("sizeof(byte)     : {0}", sizeof(byte));            Console.WriteLine("sizeof(sbyte)    : {0}", sizeof(sbyte));            Console.WriteLine("sizeof(float)    : {0}", sizeof(float));            Console.WriteLine("sizeof(ushort)   : {0}", sizeof(ushort));            Console.WriteLine("sizeof(double)   : {0}", sizeof(double));            Console.WriteLine("sizeof(int)      : {0}", sizeof(int));            Console.WriteLine("sizeof(bool)     : {0}", sizeof(bool));            Console.WriteLine("sizeof(short)    : {0}", sizeof(short));                       }    }}
Output:
sizeof(char)     : 2
sizeof(byte)     : 1
sizeof(sbyte)    : 1
sizeof(float)    : 4
sizeof(ushort)   : 2
sizeof(double)   : 8
sizeof(int)      : 4
sizeof(bool)     : 1
sizeof(short)    : 2

CSharp Operators
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
How can we disable the maximize button of a JFrame in Java?

A JFrame is a class from javax. swing package and it can extend java.awt.frame class. It is a top-level window with a border and a title bar. A JFrame class has many methods that can be used to customize it.
After setting the size of a JFrame we can still change the size by putting the cursor at the corners and dragging it or if we press resize option next to close at the top right corner, it will maximize to the size of a full screen. This happens because resize is set to true by default for JFrame class. We can make it as false as setResizable(false), now it can appear according to the dimensions we have given in the code and it cannot be resizable.
import java.awt.*;
import javax.swing.*;
public class JFrameDemo extends JFrame {
   String title;
   public JFrameDemo(String title) {
      super(title);
      add(new JLabel("JFrame with maximize button disabled"), BorderLayout.CENTER);
      setSize(350, 275);
      setLocationRelativeTo(null);
      setResizable(false); // maximize button disable
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JFrameDemo("JFrame Demo");
   }
}
PugJS Basics and Installation

25 May, 2021
Pug.js is a template engine for Node.js and browsers to render dynamic reusable content. At compile time, the template engine compiles our Pug template code to HTML. We can use variables in pug just like in JavaScript. At runtime, the template engine injects or replaces variables in a template file with actual values, and transforms the template into an HTML file which is then rendered on client side.
Pug has many powerful features like conditions, loops, includes, mixins using which we can render HTML code based on user input or reference data. Pug also support JavaScript natively, hence using JavaScript expressions, we can format HTML code. This approach allows us to reuse static web pages having dynamic data. Pug was formerly called Jade until it’s version 2.0 was released in 2015.
Let’s make a basic pug template using express.js:
Prerequisite: Basic working knowledge of express is required.
Step 1: Make an empty project folder. In command prompt / terminal, run npm init to initialize package.json file:
npm init -y
-y flag is for default settings in package.json.
Step 2: Install express and pug. We will directly install ‘express’ package rather than generating our express app with ‘express-generator’ for simplicity reasons. You can optionally install nodemon for hot reloading.
npm install express pug
Step 3: Make an empty index.js file. Make a views folder and an empty index.pug file inside it. Optionally, you can also make a public folder for static assets like media files and client side javascript.
Our final directory structure will look like this:
Final Directory Structure
Step 4: Setting up a basic express app. In Index.js:
Javascript
// Importing node modulesconst express = require("express");const pug = require("pug");const path = require("path"); // Initializing express appconst app = express(); // Setting our view engine to pugapp.set("view engine", "pug"); // Setting our default viewsapp.set("views", __dirname + "/views"); // Serving public assetsapp.use(express.static(    path.join(__dirname + "/public"))); // Home page will render "index.pug"// file. ".pug" extension is not// required. Express takes care of// it behind the scenesapp.get("/", (req, res) => {    res.render("index");}); // Listening our app on port 3000app.listen(3000);
Step 5: In index.pug file:
Javascript
doctype htmlhtml    head        title GeeksForGeeks    body        h1 Welcome to GeeksForGeeks        p We successfully made a Sample Pug Template!
You can read basics of pug syntax here.
Step 6: In terminal start the application. Run nodemon command if we have installed it previously, or just simply use node.
node index.js or nodemon index.js
In browser on localhost 3000 port, we get the below rendered template:
Akanksha_Rai
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Axis Ranges in Matplotlib?

28 Nov, 2021
Matplotlib sets the default range of the axis by finding extreme values (i.e. minimum and maximum) on that axis.  However, to get a better view of data sometimes pyplot module is used to set axis ranges of the graphs according to the requirements in Matplotlib. Following is the method used to set axis range in Matplotlib:
Syntax:
For setting range of x-axis:
 matplotlib.pyplot.xlim(limit_range)
For setting range of y-axis: 
 matplotlib.pyplot.ylim(limit_range)
Example 1:
Let us plot the sine wave function without setting the axis range:
Python
# import packagesimport matplotlib.pyplot as pltimport numpy as np  # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1)  # generate value of sine function for # given x valuesy = np.sin(x)  # plot graph of sine functionplt.plot(y, color='blue')  # display plotplt.show()
Output: 
Now, we will set the x-axis range of the plot as [0, 60]. Following is the code for restricting the range of the x-axis:
Example 2:
Python
# import packagesimport matplotlib.pyplot as pltimport numpy as np  # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1)  # generate value of sine function for # given x valuesy = np.sin(x)  # plot graph of sine functionplt.plot(y, color='blue')  # Set the range of x-axisplt.xlim(0, 60)  # display plotplt.show()
Output:
Now, we will set the y axis range of plot as [0, 1]. Following is the code for restricting the range of y-axis:
Example 3:
Python
# import packagesimport matplotlib.pyplot as pltimport numpy as np  # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1)  # generate value of sine function for # given x valuesy = np.sin(x)  # plot graph of sine functionplt.plot(y, color='blue')  # Set the range of y-axisplt.ylim(0, 1)  # display plotplt.show()
Output:
We can also set the range for both the axis of the plot at the same time. Now, we will set the x-axis range as [0, 32] and y axis range as [0, 1]. Following is the code for restricting the range of x-axis and y-axis:
Example 4:
Python
# import packagesimport matplotlib.pyplot as pltimport numpy as np  # return values between 0 and 10 with # even space of 0.1x = np.arange(0, 10, 0.1)  # generate value of sine function for# given x valuesy = np.sin(x)  # plot graph of sine functionplt.plot(y, color='blue')  # Set the range of x-axisplt.xlim(0, 32)# Set the range of y-axisplt.ylim(0, 1)  # display plotplt.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
What is strlen function in C language?

The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character.
An array of characters is called a string.
Given below is the declaration of an array −
char stringname [size];
For example − char a[50]; string of length 50 characters
Using single character constant −
char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants −
char a[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’
This function gives the length of the string, i.e., the number of characters in a string.
The syntax of strlen() function is as follows −
int strlen (string name)
The following program shows the usage of strlen() function.
 Live Demo
#include <string.h>
main ( ){
   char a[30] = "Hello";
   int l;
   l = strlen (a);
   printf ("length of the string = %d", l);
   getch ( );
}
When the above program is executed, it produces the following result −
length of the string = 5
Note : "\0" not counted as a character.
Consider another example.
Following is the C program to find the length of a string −
 Live Demo
#include<stdio.h>
#include<string.h>
int main(){
   int str1, str2;
   //initializing the strings
   char string1[] = "Welcome To";
   char string2[] = {'T','U','T','O','R','I','A','L','\0'};
   //calculating the length of the two strings
   str1 = strlen(string1);
   str2 = strlen(string2);
   printf("string1 length is: %d \n", str1);
   printf("string2 length is: %d \n", str2);
}
When the above program is executed, it produces the following result −
string1 length is: 10
string2 length is: 8
Program to Find Out the Occurrence of a Digit from a Given Range in Python

Suppose we have been provided with two positive integers n and d where d is a digit within 0 to 9. We have to determine how many times the digit d appears within the integer numbers between 1 and n.
So, if the input is like n = 45, d = 5, then the output will be 5.
These numbers have the digit 5: [5, 15, 25, 35, 45].
To solve this, we will follow these steps −
Define a function solve(). This will take n and d as inputs.
Define a function solve(). This will take n and d as inputs.
if n < 0, thenreturn 0
if n < 0, then
return 0
return 0
k := floor of (n /10) − 1
k := floor of (n /10) − 1
ans := solve(k, d) * 10 + k + 1
ans := solve(k, d) * 10 + k + 1
if d is same as 0, thenans := ans − 1
if d is same as 0, then
ans := ans − 1
ans := ans − 1
m := floor of (n / 10) * 10
m := floor of (n / 10) * 10
while m <= n, doans := ans + count of occurrences of string representation of d in string
representation of m.m := m + 1
while m <= n, do
ans := ans + count of occurrences of string representation of d in string
representation of m.
ans := ans + count of occurrences of string representation of d in string
representation of m.
m := m + 1
m := m + 1
return ans
return ans
From the main function, now call the function −
From the main function, now call the function −
value := solve(n,d)
value := solve(n,d)
print(value)
print(value)
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, n, d):
      if n < 0:
         return 0
      k = n // 10 − 1
      ans = self.solve(k, d) * 10 + k + 1
      if d == 0:
         ans −= 1
      m = n // 10 * 10
      while m <= n:
         ans += str(m).count(str(d))
         m += 1
      return ans
ob = Solution()
print(ob.solve(45,5))
45, 5
5
Retrieve the last element from a LinkedList in Java

The last element of a Linked List can be retrieved using the method java.util.LinkedList.getLast() respectively. This method does not require any parameters and it returns the last element of the LinkedList.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Andy");
      l.add("Sara");
      l.add("James");
      l.add("Betty");
      l.add("Bruce");
      System.out.println("The last element of the Linked List is : " + l.getLast());
   }
}
The last element of the Linked List is : Bruce
Now let us understand the above program.
The LinkedList l is created. LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.getLast() is used to retrieve the last element of the linked list. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>();
l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");
System.out.println("The last element of the Linked List is : " + l.getLast());