code-rag-bench/online-tutorials huggingface dataset:
Beautiful Soup - Souping the Page

In the previous code example, we parse the document through beautiful constructor using a string method. Another way is to pass the document through open filehandle.
from bs4 import BeautifulSoup
with open("example.html") as fp:
   soup = BeautifulSoup(fp)
soup = BeautifulSoup("<html>data</html>")
First the document is converted to Unicode, and HTML entities are converted to Unicode characters:</p>

import bs4
html = '''<b>tutorialspoint</b>, <i>&web scraping &data science;</i>'''
soup = bs4.BeautifulSoup(html, 'lxml')
print(soup)
<html><body><b>tutorialspoint</b>, <i>&web scraping &data science;</i></body></html>

BeautifulSoup then parses the data using HTML parser or you explicitly tell it to parse using an XML parser.
Before we look into different components of a HTML page, let us first understand the HTML tree structure.
The root element in the document tree is the html, which can have parents, children and siblings and this determines by its position in the tree structure. To move among HTML elements, attributes and text, you have to move among nodes in your tree structure.
Let us suppose the webpage is as shown below −
Which translates to an html document as follows −
<html><head><title>TutorialsPoint</title></head><h1>Tutorialspoint Online Library</h1><p<<b>It's all Free</b></p></body></html>
Which simply means, for above html document, we have a html tree structure as follows −

    38 Lectures 
     3.5 hours 

 Chandramouli Jayendran

    22 Lectures 
     1 hours 

 TELCOMA Global

    6 Lectures 
     1 hours 

 AlexanderSchlee

    6 Lectures 
     1 hours 

 AlexanderSchlee

    6 Lectures 
     1 hours 

 AlexanderSchlee

    22 Lectures 
     4 hours 

 AlexanderSchlee
 Print
 Add Notes
 Bookmark this page
What happens if try to access an element with an index greater than the size of the array in Java?

An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.
The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.
Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets.
For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as −
System.out.println(myArray[3]);
//25
In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −
int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
Or, you can directly assign values with in flower braces separating them with commas (,) as −
int myArray = { 1254, 1458, 5687, 1457, 4554, 5445, 7524};
Though, you can refer the elements of an array by using the name and index as −
myArray[5];
You cannot access the elements that are greater to the size of the array. i.e. If you create an array with 7 elements, as you observe in the diagram you can access up to myArray[6].
If you try to access the array position (index) greater than its size, the program gets compiled successfully but, at the time of execution it generates an ArrayIndexOutOfBoundsException exception.
public class AccessingElements {
   public static void main(String[] args) {
      //Creating an integer array with size 5
      int inpuArray[] = new int[5];
      //Populating the array
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //Accessing index greater than the size of the array
      System.out.println( inpuArray[6]);
   }
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
   at myPackage.AccessingElements.main(AccessingElements.java:17)
LISP - If Construct

The if macro is followed by a test clause that evaluates to t or nil. If the test clause is evaluated to the t, then the action following the test clause is executed. If it is nil, then the next clause is evaluated.
Syntax for if −
(if (test-clause) (action1) (action2))

Create a new source code file named main.lisp and type the following code in it.
(setq a 10)
(if (> a 20)
   (format t "~% a is less than 20"))
(format t "~% value of a is ~d " a)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
value of a is 10

The if clause can be followed by an optional then clause.
Create a new source code file named main.lisp and type the following code in it.
(setq a 10)
(if (> a 20)
   then (format t "~% a is less than 20"))
(format t "~% value of a is ~d " a)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
a is less than 20
value of a is 10 

You can also create an if-then-else type statement using the if clause.
Create a new source code file named main.lisp and type the following code in it.
(setq a 100)
(if (> a 20)
   (format t "~% a is greater than 20") 
   (format t "~% a is less than 20"))
(format t "~% value of a is ~d " a)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
a is greater than 20
value of a is 100  


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
PHP File Handling

File handling is an important part of any web application. You 
often need to open and process a file for different tasks.
PHP has several functions for creating, reading, uploading, and editing files.


Be careful when manipulating files!
You can do a 
lot of damage if you do something wrong. Common errors are: editing the wrong 
file, filling a hard-drive with garbage data, and deleting the content of a file 
by accident.
The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "webdictionary.txt", stored on the 
server, that looks like this:
The PHP code to read the file and write it to the output buffer is as follows 
(the readfile() function returns the number of bytes read on success):
The readfile() function is useful if all you want to do is open up a file and read its contents.
The next chapters will teach you more about file handling.
Assume we have a file named "webdict.txt", write the correct syntax to open and read the file content.
echo ;

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
JavaScript String - substring() Method

This method returns a subset of a String object.
The syntax to use substr() is as follows −
string.substring(indexA, [indexB])

indexA − An integer between 0 and one less than the length of the string.
indexA − An integer between 0 and one less than the length of the string.
indexB − (optional) An integer between 0 and the length of the string.
indexB − (optional) An integer between 0 and the length of the string.
The substring method returns the new sub-string based on given parameters.
Try the following example.
<html>
   <head>
      <title>JavaScript String substring() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = "Apples are round, and apples are juicy.";         
         document.write("(1,2): "    + str.substring(1,2));
         document.write("<br />(0,10): "   + str.substring(0, 10));
         document.write("<br />(5): "      + str.substring(5));
      </script>      
   </body>
</html>
(1,2): p
(0,10): Apples are
(5): s are round, and apples are juicy. 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to sort an ArrayList in Ascending Order in Java

To sort an ArrayList in ascending order, the easiest way is to the Collections.sort() method. With this method, you just need to set the ArrayList as the parameter as shown below −
Collections.sort(ArrayList)
Let us now see an example to sort an ArrayList un ascending order. Here, we are sorting ArrayList with integer elements −
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
   public static void main(String args[]) {
      ArrayList<Integer> myList = new ArrayList<Integer>();
      myList.add(50);
      myList.add(29);
      myList.add(35);
      myList.add(11);
      myList.add(78);
      myList.add(64);
      myList.add(89);
      myList.add(67);
      System.out.println("Points\n"+ myList);
      Collections.sort(myList);
      System.out.println("Points (ascending order)\n"+ myList);
   }
}
Points
[50, 29, 35, 11, 78, 64, 89, 67]
Points (ascending)
[11, 29, 35, 50, 64, 67, 78, 89]
Following is another code to sort an ArrayList in ascending order in Java. Here, we are sorting ArrayList with string values −
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
public class Demo {
   public static void main(String args[]) {
      ArrayList<String> myList = new ArrayList<String>();
      myList.add("Tim");
      myList.add("John");
      myList.add("Steve");
      myList.add("Andy");
      myList.add("Devillers");
      myList.add("Jacob");
      myList.add("Franco");
      myList.add("Amy");
      System.out.println("Student Names\n"+ myList);
      Collections.sort(myList);
      System.out.println("Student Names (ascending)\n"+ myList);
   }
}
Student Names
[Tim, John, Steve, Andy, Devillers, Jacob, Franco, Amy]
Student Names (ascending)
[Amy, Andy, Devillers, Franco, Jacob, John, Steve, Tim]
Exception propagation in Java

Exception propagation in Java occurs when an exception thrown from the top of the stack. When it is not caught, the exception drops down the call stack of the preceding method. If it is not caught there, it further drops down to the previous method. This continues until the method reaches the bottom of the call stack or is caught somewhere in between.
Let us see an example which illustrates exception propagation in Java −
 Live Demo
public class Example {
   void method1() // generates an exception {
      int arr[] = {10,20,30};
      System.out.println(arr[7]);
   }
   void method2() // doesn't catch the exception {
      method1();
   }
   // method1 drops down the call stack
   void method3() // method3 catches the exception {
      try {
         method2();
      } catch(ArrayIndexOutOfBoundsException ae) {
         System.out.println("Exception is caught");
      }
   }
   public static void main(String args[]) {
      Example obj = new Example();
      obj.method3();
   }
}
The output is as follows −
Exception is caught
C Program to insert an array element using pointers.

Write a C program to insert the elements into an array at runtime by the user and the result to be displayed on the screen after insertion. If the inserted element is greater than the size of an array, then, we need to display Invalid Input.
An array is used to hold the group of common elements under one name.
The array operations are as follows −
Insert
Delete
Search
Refer an algorithm to insert the elements into an array with the help of pointers.
Step 1: Declare and read the number of elements.
Step 2: Declare and read the array size at runtime.
Step 3: Input the array elements.
Step 4: Declare a pointer variable.
Step 5: Allocate the memory dynamically at runtime.
Step 6: Input the position, where an element should be inserted.
Step 7: Insert the new element at that position and of the elements to right are to be shifted by one position.
Size of array is: 5
Array elements are as follows −
1 2 3 4 5
Insert new element: 9
At position: 4
The output is as follows −
After insertion the array elements are:
1 2 3 9 4 5
Following is the C program to insert the elements into an array with the help of pointers −
 Live Demo
#include<stdio.h>
#include<stdlib.h>
void insert(int n1, int *a, int len, int ele){
   int i;
   printf("Array elements after insertion is:\n");
   for(i=0;i<len-1;i++){
      printf("%d\n",*(a+i));
   }
   printf("%d\n",ele);
   for(i=len-1;i<n1;i++){
      printf("%d\n",*(a+i));
   }
}
int main(){
   int *a,n1,i,len,ele;
   printf("enter size of array elements:");
   scanf("%d",&n1);
   a=(int*)malloc(n1*sizeof(int));
   printf("enter the elements:\n");
   for(i=0;i<n1;i++){
      scanf("%d",a+i);
   }
   printf("enter the position where the element need to be insert:\n");
   scanf("%d",&len);
   if(len<=n1){
      printf("enter the new element that to be inserted:");
      scanf("%d",&ele);
      insert(n1,a,len,ele);
   } else {
      printf("Invalid Input");
   }
   return 0;
}
When the above program is executed, it produces the following output −
enter size of array elements:5
enter the elements:
1
3
5
7
2
enter the position where the element need to be insert:
5
enter the new element that to be inserted:9
Array elements after insertion are:
1
3
5
7
9
2
Create and display a one-dimensional array-like object using Pandas in Python - GeeksforGeeks

18 Aug, 2020
Series() is a function present in the Pandas library that creates a one-dimensional array and can hold any type of objects or data in it. In this article, let us learn the syntax, create and display one-dimensional array-like object containing an array of data using Pandas library.
Syntax : pandas.Series(parameters)Parameters :
data : Contains data stored in Series.
index : Values must be hashable and have the same length as data.
dtype : Data type for the output Series.
name : The name to give to the Series.
copy : Copy input data.
Returns : An object of class Series
Example 1 : Creating Series from a list
# import the libraryimport pandas as pd  # create the one-dimensional arraydata = [1, 2, 3, 4, 5]  # create the Seriesex1 = pd.Series(data)  # displaying the Seriesprint(ex1)
Output :
Example 2 :Creating a Series from a NumPy array.
# import the pandas and numpy libraryimport pandas as pdimport numpy as np  # create numpy arraydata = np.array(['a', 'b', 'c', 'd'])  # create one-dimensional datas = pd.Series(data)  # display the Seriesprint(s)
Output :
Example 3: Creating a Series from a dictionary.
# import the pandas libraryimport pandas as pd  # create dictionarydict = {'a' : 0.1, 'b' : 0.2, 'c' : 0.3}  # create one-dimensional datas = pd.Series(dict)  # display the Seriesprint(s)
Output :
Example 4 :Creating a Series from list of lists.
# importing the moduleimport pandas as pd  # creating the datadata = [['g', 'e', 'e', 'k', 's'],        ['f', 'o', 'r'],        ['g', 'e', 'e', 'k', 's']]  # creating a Pandas series of listss = pd.Series(data)  # displaying the Seriesprint(s)
Output :
Python Pandas-exercise
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
How to create transparent Status Bar and Navigation Bar in iOS?

You might have come across many application where the screen extends to complete screen i.e transparent Status Bar and transparent navigation bar.
Here we will be seeing how to create an application where the you’ll be having transparent status and navigation bar.
So let’s get started
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “TransparentViews”
Step 2 − Embed the View Controller in Navigation Controller. Add Image View and shown and add image.
Step 3 − Run the application without adding any piece of code for making status and navigation bar transparent.
The screen looks like below
Step 4 − Now Open ViewController.swift and add following code in viewDidLoad method.
override func viewDidLoad(){
   super.viewDidLoad()
   self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default)
   self.navigationController!.navigationBar.shadowImage = UIImage()
   self.navigationController!.navigationBar.isTranslucent = true
}
Step 5 − Run the application
Perl | keys() Function - GeeksforGeeks

25 Jun, 2019
keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function.
Syntax: keys(HASH)
Parameter:HASH: Hash whose keys are to be printed
Return: For scalar context, it returns the number of keys in the hash whereas for List context it returns a list of keys.
Example 1:
#!/usr/bin/perl  %hash = ('Ten' => 10,         'Eleven' => 11,         'Twelve' => 12,         'Thirteen' => 13);  @values = values( %hash );print("Values are  ", join("-", @values), "\n");  @keys = keys( %hash );print("Keys are ", join("-", @keys), "\n");
Output:
Values are  11-12-13-10
Keys are Eleven-Twelve-Thirteen-Ten
Example 2:
#!/usr/bin/perl  %hash = ('Geek' => 1,         'For' => 2,         'Geeks' => 3);  @values = values( %hash );print("Values are  ", join("-", @values), "\n");  @keys = keys( %hash );print("Keys are ", join("-", @keys), "\n");
Output:
Values are  3-2-1
Keys are Geeks-For-Geek

Perl-function
Perl-Hash-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl Tutorial - Learn Perl With Examples
Perl | Hashes
Perl | Basic Syntax of a Perl Program
Perl | Opening and Reading a File
Perl | Multidimensional Hashes
How to Install Perl on Windows?
Perl | CGI Programming
Perl | Sorting of Arrays
Perl | Data Types
Perl | Operators | Set - 1
How to center canvas in HTML5?

To center canvas in HTML 5, include the canvas tag in div tag. Then we can center align the div tag. By doing so, the canvas is also center aligned.
<!DOCTYPE html>.
<html>
   <body>
      <div style = "text-align:center;">
         <canvas style = "background-color:GREEN;">This is my canvas</canvas>
      </div>
   </body>
</html>
PDFBox - Adding Pages

In the previous chapter, we have seen how to create a PDF document. After creating a PDF document, you need to add pages to it. Let us now understand how to add pages in a PDF document.
You can create an empty page by instantiating the PDPage class and add it to the PDF document using the addPage() method of the PDDocument class.
Following are the steps to create an empty document and add pages to it.
Create an empty PDF document by instantiating the PDDocument class as shown below.
PDDocument document = new PDDocument();

The PDPage class represents a page in the PDF document therefore, you can create an empty page by instantiating this class as shown in the following code block.
PDPage my_page = new PDPage();

You can add a page to the PDF document using the addPage() method of the PDDocument class. To this method you need to pass the PDPage object as a parameter.
Therefore, add the blank page created in the previous step to the PDDocument object as shown in the following code block.
document.addPage(my_page);

In this way you can add as many pages as you want to a PDF document.
After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
document.save("Path");

Finally close the document using the close() method of the PDDocument class as shown below.
document.close();

This example demonstrates how to create a PDF Document and add pages to it. Here we will create a PDF Document named my_doc.pdf and further add 10 blank pages to it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Adding_pages.java.
package document;
 
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class Adding_Pages {

   public static void main(String args[]) throws IOException {
       
      //Creating PDF document object 
      PDDocument document = new PDDocument();

      for (int i=0; i<10; i++) {
         //Creating a blank page 
         PDPage blankPage = new PDPage();

         //Adding the blank page to the document
         document.addPage( blankPage );
      } 
     
      //Saving the document
      document.save("C:/PdfBox_Examples/my_doc.pdf");
      System.out.println("PDF created");
      
      //Closing the document
      document.close();

   }  
} 
Compile and execute the saved Java file from the command prompt using the following commands −
javac Adding_pages.java 
java Adding_pages 

Upon execution, the above program creates a PDF document with blank pages displaying the following message −
PDF created 

If you verify the specified path, you can find the created PDF document as shown in the following screenshot.
 Print
 Add Notes
 Bookmark this page
C++ String Library - begin

It returns an iterator pointing to the first character of the string.
Following is the declaration for std::string::begin.
   iterator begin();
const_iterator begin() const;
   iterator begin() noexcept;
const_iterator begin() const noexcept;
none
It returns an iterator to the beginning of the string.
Never throw any exceptions.
In below example for std::string::begin.
#include <iostream>
#include <string>

int main () {
   std::string str ("Tutorials point");
   for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
      std::cout << *it;
   std::cout << '\n';

   return 0;
}
The sample output should be like this −
Tutorials point  

 Print
 Add Notes
 Bookmark this page
CSS overflow: auto

The CSS overflow: auto, adds a scrollbar only when it's needed, unlike overflow:scroll. You can try to run the following code to implement CSS overflow: auto property:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            background-color: orange;
            width: 250px;
            height: 45px;
            border: 2px solid blue;
            overflow: auto;
         }
      </style>
   </head>
   <body>
      <h1>Heading</h1>
      <div>Overflow property used here. This is a demo text to show the working of CSS overflow: auto. This won't hide the content. A scrollbar would be visible, only if needed.</div>
   </body>
</html>
Tryit Editor v3.7

Tryit: HTML RGB color values
unsigned char in C with Examples

06 Aug, 2020
char is the most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.
Now character datatype can be divided into 2 types:
signed charunsigned char
signed char
unsigned char
unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.
Syntax:
unsigned char [variable_name] = [value]

Example:
unsigned char ch = 'a';

Initializing an unsigned char: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value 97 will be converted to a character value, i.e. ‘a’ and it will be inserted in unsigned char.// C program to show unsigned char  #include <stdio.h>  int main(){      int chr = 97;    unsigned char i = chr;    printf("unsigned char: %c\n", i);      return 0;}Output:unsigned char: a
Initializing an unsigned char with signed value: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value -1 will be first converted to a range 0-255 by rounding. So it will be 255. Now, this value will be converted to a character value, i.e. ‘ÿ’ and it will be inserted in unsigned char.// C program to show unsigned char  #include <stdio.h>  int main(){      int chr = -1;    unsigned char i = chr;    printf("unsigned char: %c\n", i);      return 0;}Output:unsigned char: ÿ

// C program to show unsigned char  #include <stdio.h>  int main(){      int chr = 97;    unsigned char i = chr;    printf("unsigned char: %c\n", i);      return 0;}
unsigned char: a

Initializing an unsigned char with signed value: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value -1 will be first converted to a range 0-255 by rounding. So it will be 255. Now, this value will be converted to a character value, i.e. ‘ÿ’ and it will be inserted in unsigned char.
// C program to show unsigned char  #include <stdio.h>  int main(){      int chr = -1;    unsigned char i = chr;    printf("unsigned char: %c\n", i);      return 0;}
unsigned char: ÿ

Zero97M
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
C Program to Swap two Numbers
Program to find Prime Numbers Between given Interval
Set, Clear and Toggle a given bit of a number in C
C program to sort an array in ascending order
time() function in C
read command in Linux with Examples

24 May, 2019
read command in Linux system is used to read from a file descriptor. Basically, this command read up the total number of bytes from the specified file descriptor into the buffer. If the number or count is zero then this command may detect the errors. But on success, it returns the number of bytes read. Zero indicates the end of the file. If some errors found then it returns -1.
Syntax:
read 

Examples:
read command without any option: The read command asks for the user’s input and exit once the user provides some input.
In the following example we are acquiring the user’s name and then showing the user’s name with a greeting.echo "what is your name..?";read name;echo "hello $name"
echo "what is your name..?";read name;echo "hello $name"
linux-command
Linux-Shell-Commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to Sort a List of Strings by the Number of Unique Characters

01 Oct, 2020
Given a list of strings. The task is to sort the list of strings by the number of unique characters.
Examples:
Input : test_list = [‘gfg’, ‘best’, ‘for’, ‘geeks’], Output : [‘gfg’, ‘for’, ‘best’, ‘geeks’] Explanation : 2, 3, 4, 4 are unique elements in lists.
Input : test_list = [‘gfg’, ‘for’, ‘geeks’], Output : [‘gfg’, ‘for’, ‘geeks’] Explanation : 2, 3, 4 are unique elements in lists. 
Method #1 : Using sort() + len() + set()
In this, we perform task of sorting using sort(), and len and sort functions are used to get length of unique characters in string.
Python3
# Python3 code to demonstrate working of # Sort Strings by Unique characters# Using sort() + len() + set()  # helper functiondef hlper_fnc(ele):          # getting Unique elements count     return len(list(set(ele)))  # initializing listtest_list = ['gfg', 'best', 'for', 'geeks']  # printing original listprint("The original list is : " + str(test_list))  # perform sorttest_list.sort(key = hlper_fnc)      # printing result print("Sorted List : " + str(test_list))
The original list is : ['gfg', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'best', 'geeks']

Method #2 : Using sorted() + len() + set() + lambda
Similar to above method, difference being not inplace sort, and also uses lambda function for performing task. 
Python3
# Python3 code to demonstrate working of # Sort Strings by Unique characters# Using sorted() + len() + set() + lambda  # initializing listtest_list = ['gfg', 'best', 'for', 'geeks']  # printing original listprint("The original list is : " + str(test_list))  # perform sortres = sorted(test_list, key = lambda sub : len(list(set(sub))))      # printing result print("Sorted List : " + str(res))
The original list is : ['gfg', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'best', 'geeks']

Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Navigation Bars in Flask

26 May, 2022
Navigation across HTML pages is quite a common way to work across pages. The client-side navigation approach is commonly used in HTML. However, having custom server-end navigations can provide greater flexibilities as far as customizations are concerned. This article walks you through a way to integrate Server end navigation using Navbars in Flask.
This module is used to build navigation bars in the flask application.
Allows server end navigation from one page to another.
Helps to define HTML classes and Navigation items from Python.
To install this module type the below command in the terminal.
pip install Flask-Navigation
nav.Bar(name, items) : Initializing name of navigation class with items definition.nav.Item( label, url, args) : Assigns items or lists for each bar. Label name, its linked page URL and extra args like parameter and value of dictionary.
After installation, the next step is to initialize the app context with Navigation(), and define the basic HTML to navigate. Navigation bars also need to be defined in the code using Bar(), with takes position and list of items are parameters of Navigation Bars. Each Item is input with its label, URL, and parameters passed in the URL.
Step 1: Importing Libraries, adding app context and  Initializing Navigation Class Object. 
Python3
from flask import Flask, render_templatefrom flask_navigation import Navigation  app = Flask(__name__)nav = Navigation(app)
Step 2: Adding Navigation Definition
Python3
# initializing Navigationsnav.Bar('top', [    nav.Item('Home', 'index'),    nav.Item('Gfg', 'gfg', {'page': 5}),])
Step 3: Adding flask Routes and run application.
Python3
@app.route('/')def index():    return render_template('index.html')    @app.route('/navpage')def navpage():    return render_template('navpage.html')    @app.route('/gfg/<int:page>')def gfg(page):    return render_template('gfg.html', page=page)    if __name__ == '__main__':    app.run()
navpage.html
In this, for loop is used to iterate to render all the items defined under the top bar, with their url and labels.
HTML
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><ul>    {% for item in nav.top %}    <li class="{{ 'active' if item.is_active else '' }}">        <a href="{{ item.url }}">{{ item.label }}</a>    </li>    {% endfor %}</ul></body></html>
index.html
HTML
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><b>Index page</b></body></html>
gfg.html
HTML
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><b>GFG Page 5</b></body></html>
While opening navpage.html, on click of each item, the page is navigated to the required URL as configured for navigation. 
Output:
Explanation:
In navpage.html, each item of navbar is iterated and rendered. Onclick, class is activated and anchor tag takes to the defined path, the linked pages.
Flask Projects
Python Flask
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Create acronyms from words

21 Jun, 2022
Given a string, the task is to write a Python program to extract the acronym from that string.
Examples:
Input: Computer Science Engineering
Output: CSE
Input: geeks for geeks
Output: GFG
Input: Uttar pradesh
Output: UP
Approach 1:
The following steps are required:
Take input as a string.
Add the first letter of string to output.
Iterate over the full string and add every next letter to space to output.
Change the output to uppercase(required acronym).
Python3
# function to create acronymdef fxn(stng):       # add first letter    oupt = stng[0]         # iterate over string    for i in range(1, len(stng)):        if stng[i-1] == ' ':                       # add letter next to space            oupt += stng[i]                 # uppercase oupt    oupt = oupt.upper()    return oupt  # input stringinpt1 = "Computer Science Engineering" # output acronymprint(fxn(inpt1)) # input stringinpt1 = "geeks for geeks" # output acronymprint(fxn(inpt1)) # input stringinpt1 = "Uttar pradesh" # output acronymprint(fxn(inpt1))
Output:
CSE
GFG
UP
Time Complexity: O(n) -> looping once through string of length n.
Space Complexity: O(n) -> as space is required for storing individual characters of a string of length n.
Approach 2:
The following steps are required:
Take input as a string.
Split the words.
Iterate over words and add the first letter to output.
Change the output to uppercase(required acronym).
Python3
# function to create acronymdef fxn(stng):       # get all words    lst = stng.split()    oupt = ""         # iterate over words    for word in lst:               # get first letter of each word        oupt += word[0]             # uppercase oupt    oupt = oupt.upper()    return oupt  # input stringinpt1 = "Computer Science Engineering" # output acronymprint(fxn(inpt1)) # input stringinpt1 = "geeks for geeks" # output acronymprint(fxn(inpt1)) # input stringinpt1 = "Uttar pradesh" # output acronymprint(fxn(inpt1))
Output:
CSE
GFG
UP
Time Complexity: O(n) -> looping once through an array of length n.
Space Complexity: O(n) -> as space is required for storing individual characters of a string and an array of length n.
harshmaster07705
Python string-programs
Python
Python Programs
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
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | sympy.integrate() using limits

12 Jun, 2019
With the help of sympy.integrate(expression, limit) method, we can find the integration of mathematical expressions using limits in the form of variables by using sympy.integrate(expression, limit) method.
Syntax : sympy.integrate(expression, reference variable, limit)Return : Return integration of mathematical expression.
Example #1 :
In this example we can see that by using sympy.integrate(expression, limits) method, we can find the integration of mathematical expression using limits with variables. Here we use symbols() method also to declare a variable as symbol.
# import sympyfrom sympy import *   x, y = symbols('x y')gfg_exp = cos(x)  print("Before Integration : {}".format(gfg_exp))  # Use sympy.integrate() methodintr = integrate(gfg_exp,  (x, -oo, oo))  print("After Integration : {}".format(intr))
Output :
Before Integration : cos(x)
After Integration : AccumBounds(-2, 2)
 Example #2 :
# import sympyfrom sympy import *   x, y = symbols('x y')gfg_exp = tan(x)  print("Before Integration : {}".format(gfg_exp))  # Use sympy.integrate() methodintr = integrate(gfg_exp,  (x, -1, 1))  print("After Integration : {}".format(intr))
Output :
Before Integration : tan(x)
After Integration : 0
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2011 | Question 4

16 Mar, 2018
Consider different activities related to email:
m1: Send an email from a mail client to a mail server
m2: Download an email from mailbox server to a mail client
m3: Checking email in a web browser
Which is the application level protocol used in each activity?(A) m1: HTTP m2: SMTP m3: POP(B) m1: SMTP m2: FTP m3: HTTP(C) m1: SMTP m2: POP m3: HTTP(D) m1: POP m2: SMTP m3: IMAPAnswer: (C)Explanation: Simple Mail Transfer Protocol (SMTP) is typically used by user clients for sending mails.Post Office Protocol (POP) is used by clients for receiving mails.Checking mails in web browser is a simple HTTP process.
Option (C) is correct.
Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find Median of List in Python

03 Oct, 2019
Sometimes, while working with Python list we can have a problem in which we need to find Median of list. This problem is quite common in the mathematical domains and generic calculations. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + "~" operatorThis task can be performed in brute force manner using the combination of above functionalities. In this, we sort the list and the by using the property of “~” operator to perform negation, we access the list from front and rear, performing the required computation required for finding median.
# Python3 code to demonstrate working of# Median of list# Using loop + "~" operator  # initializing listtest_list = [4, 5, 8, 9, 10, 17]  # printing listprint("The original list : " + str(test_list))  # Median of list# Using loop + "~" operatortest_list.sort()mid = len(test_list) // 2res = (test_list[mid] + test_list[~mid]) / 2  # Printing resultprint("Median of list is : " + str(res))
 
The original list : [4, 5, 8, 9, 10, 17]
Median of list is : 8.5

 
Method #2 : Using statistics.median()This is the most generic method to perform this task. In this we directly use inbuilt function to perform the median of the list.
# Python3 code to demonstrate working of# Median of list# Using statistics.median()import statistics  # initializing listtest_list = [4, 5, 8, 9, 10, 17]  # printing listprint("The original list : " + str(test_list))  # Median of list# Using statistics.median()res = statistics.median(test_list)  # Printing resultprint("Median of list is : " + str(res))
 
The original list : [4, 5, 8, 9, 10, 17]
Median of list is : 8.5

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.scandir() method - GeeksforGeeks

08 Aug, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.
The os.scandir() method in Python is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by the specified path. 
The entries are yielded in arbitrary order and special entries ‘.’ and ‘..’ are not included.  
Syntax: os.scandir(path = ‘.’)Parameter: path: A path-like object representing the file system path. This specify the directory to be scanned. If path is not specified then current working directory is used as path. A path-like object is a string or bytes object which represents a path.Return Type: This method returns an iterator of os.DirEntry objects corresponding to the entries in the given directory.  
Code: Use of os.scandir() method 
Python3
# Python program to explain os.scandir() method # importing os moduleimport os  # Directory to be scannedpath = '/home/ihritik' # Scan the directory and get# an iterator of os.DirEntry objects# corresponding to entries in it# using os.scandir() methodobj = os.scandir(path) # List all files and directories# in the specified pathprint("Files and Directories in '% s':" % path)for entry in obj :    if entry.is_dir() or entry.is_file():        print(entry.name)  # entry.is_file() will check# if entry is a file or not and# entry.is_dir() method will# check if entry is a# directory or not.  # To Close the iterator and# free acquired resources# use scandir.close() methodobj.close() # scandir.close() method is called automatically# when the iterator is exhausted# or garbage collected, or# when an error happens during iterating.
Files and Directories in '/home':
GeeksforGeeks
Videos
Downloads
Pictures
Documents
sample.txt
Public
Desktop
Images
R
 
Reference: https://docs.python.org/3/library/os.html#os.scandir 
sooda367
bassdropca
python-os-module
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Structure declaration in C language

The structure is a collection of different datatype variables, grouped together under a single name. It is a heterogeneous collection of data items that share a common name.
It is possible to copy the contents of all structural elements of different data types to another structure variable of its type by using an assignment operator.
It is possible to copy the contents of all structural elements of different data types to another structure variable of its type by using an assignment operator.
To handle complex datatypes, it is possible to create a structure within another structure, which is called nested structures.
To handle complex datatypes, it is possible to create a structure within another structure, which is called nested structures.
It is possible to pass an entire structure, individual elements of structure, and address of structure to a function.
It is possible to pass an entire structure, individual elements of structure, and address of structure to a function.
It is possible to create structure pointers.
It is possible to create structure pointers.
The general form of structure declaration is as follows −
datatype member1;
struct tagname{
   datatype member2;
   datatype member n;
};
Here,
struct is the keyword.
struct is the keyword.
tagname specifies the name of a structure
tagname specifies the name of a structure
member1, member2 specifies the data items that makeup structure.
member1, member2 specifies the data items that makeup structure.
For example,
struct book{
   int pages;
   char author [30];
   float price;
};
There are three ways of declaring structure variables, which are as follows −
Type 1
struct book{
   int pages;
   char author[30];
   float price;
}b;
Type 2
struct{
   int pages;
   char author[30];
   float price;
}b;
Type 3
struct book{
   int pages;
   char author[30];
   float price;
};
struct book b;
Convert a NumPy array into a csv file - GeeksforGeeks

02 Sep, 2020
In this article, we are going to see different methods to save an NumPy array into a CSV file. CSV file format is the easiest and useful format for storing data
There are different methods by which we can save the NumPy array into a CSV file
Method 1: Using Dataframe.to_csv().
This method is used to write a Dataframe into a CSV file.
Example: Converting the array into pandas Dataframe and then saving it to CSV format.
Python3
# import necessary librariesimport pandas as pdimport numpy as np  # create a dummy arrayarr = np.arange(1,11).reshape(2,5)  # display the arrayprint(arr)  # convert array into dataframeDF = pd.DataFrame(arr)  # save the dataframe as a csv fileDF.to_csv("data1.csv")
Output:
[[ 1  2  3  4  5]
[ 6  7  8  9 10]]

Method 2: Using numpy_array.tofile().
This method is used to write an array into the file.
Example: Create an array then save into a CSV file.
Python3
# import the necessary libraryimport numpy as np  # create a dummy arrayarr = np.arange(1,11)  # display the arrayprint(arr)  # use the tofile() method # and use ',' as a separator# as we have to generate a csv filearr.tofile('data2.csv', sep = ',')
Output:
[ 1  2  3  4  5  6  7  8  9 10]

Method 3: Using numpy.savetext().
This method is used to save an array to a text file.
Example: Create an array then save as a CSV file.
Python3
# import numpy libraryimport numpy  # create an arraya = numpy.array([[1, 6, 4],                 [2, 4, 8],                 [3, 9, 1]])  # save array into csv filenumpy.savetxt("data3.csv", a,               delimiter = ",")
Output:
Python numpy-io
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
Bootstrap lead class

The lead class in Bootstrap is used to add emphasis to a paragraph.
You can try to run the following code to implement the lead class in Bootstrap −
 Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap lead class</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <h2>Lead Example</h2>
      <p class = "lead">This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is an example paragraph demonstrating the use of lead body copy.
      </p>
   </body>
</html>
How to use Meta Tag to redirect an HTML page? - GeeksforGeeks

17 Oct, 2019
URL redirection, also called URL forwarding is a way to send users to a different URL from the one they originally requested. The three most commonly used redirects are 301, 302, and Meta Refresh.Meta Refresh Redirect is a client-side redirect. Unlike 301 and 302 redirects that happen on the webserver, Meta Refresh Redirect takes place in a web browser and instructs the web browser to go to a different web page after a specified time span.The use of Meta Refresh Redirect is deprecated or in other words, disapproved by W3C(World Wide Web Consortium), since it is a non-standard procedure of redirection, it disorients users, and it can also disrupt a browser’s history of visited pages.
Syntax:
<meta http-equiv = "refresh" content = "20; url = https://ide.geeksforgeeks.org"/>

Example:
<!DOCTYPE html><html>  <head>    <title>Meta Refresh Redirection</title>    <meta http-equiv="refresh"           content="20; url = https://ide.geeksforgeeks.org" /></head>  <body>    <h1 style="text-align:center;color:green;">      GeeksforGeeks  </h1>    <p style="text-align:center;">       If your browser supports Refresh,      you'll be redirected to GeeksforGeeks       IDE, in 20 seconds. </p></body>  </html>
Output:Before:After:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubhamr238
Picked
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
JupyterLab - Installing R Kernel

Project Jupyter now supports kernels of programming environments. We shall now see how to install R kernel in anaconda distribution.
In Anaconda prompt window enter following command −
conda install -c r r-essentials

Now, from the launcher tab, choose R kernel to start a new notebook.
The following is a screenshot of Jupyter notebook having R kernel −

    22 Lectures 
     49 mins

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page