code-rag-bench/online-tutorials huggingface dataset:
How to make Mergesort to perform O(n) comparisons in best case?

18 Sep, 2017
As we know, Mergesort is a divide and conquer algorithm that splits the array to halves recursively until it reaches an array of the size of 1, and after that it merges sorted subarrays until the original array is fully sorted. Typical implementation of merge sort works in O(n Log n) time in all three cases (best, average and worst).
We need to reduce the best case performance from O(n log n) to O(n).
The idea is to consider the case when array is already sorted. Before merging, just check if arr[mid] > arr[mid+1], because we are dealing with sorted subarrays. This will lead us to the recursive relation T(n) = 2*T(n/2) + 1 which can be resolved by the master’s theorem, so T(n) = n.
Examples:
Input : 1 2 3 4
Subarrays with size of 1:|1||2| |3||4|
Subarrays with size of 2: |1 2| |3 4|
Output : 1 2 3 4

Input : 1 2 3 4 5 6 7 8 
        Subarrays with size of 1: |1||2| |3||4| |5||6| |7||8|
        Subarrays with size of 2: |1 2| |3 4| |5 6| |7 8|
        Subarrays with size of 4: |1 2 3 4| |5 6 7 8|
Output : 1 2 3 4 5 6 7 8 

// C program to implement merge sort that works// in O(n) time in best case.#include <stdio.h>#include <stdlib.h>  void merge(int* arr, int low, int mid, int high);  void mergesort(int* arr, int low, int high){    if (low < high) {        int mid = (low + high) / 2;        mergesort(arr, low, mid);        mergesort(arr, mid + 1, high);          // This is where we optimize for best        // case.        if (arr[mid] > arr[mid + 1])            merge(arr, low, mid, high);    }}  void merge(int* arr, int low, int mid, int high){    int i = low, j = mid + 1, k = 0;    int* temp = (int*)calloc(high - low + 1, sizeof(int));    while ((i <= mid) && (j <= high))        if (arr[i] < arr[j])            temp[k++] = arr[i++];        else            temp[k++] = arr[j++];    while (j <= high) // if( i>mid )        temp[k++] = arr[j++];    while (i <= mid) // j>high        temp[k++] = arr[i++];      // copy temp[] to arr[]    for (i = low, k = 0; i <= high; i++, k++)        arr[i] = temp[k];    free(temp);}  int main(){    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 };    mergesort(a, 0, 7);    for (int i = 0; i < 8; i++)        printf("%d ", a[i]);    return 0;}
Output:
 1 2 3 4 5 6 7 8

This article is contributed by Shlomi Elhaiani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
featured
Merge Sort
Sorting
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Longest Common Prefix using Sorting
Sort a nearly sorted (or K sorted) array
Segregate 0s and 1s in an array
Sorting in Java
Quick Sort vs Merge Sort
Quickselect Algorithm
Stability in sorting algorithms
Find whether an array is subset of another array
Find all triplets with zero sum
How to Replace a Character with the String in C#?

03 Dec, 2021
Given a string, now our task is to replace a specified character with the string. This task is performed with the help of Replace() method. This method is used to replace all the Unicode characters with the specified string and return a modified string. 
Syntax:
string.Replace(character, new_string)
Here, string is the input string, a character is present in the string that is going to replace, and new_string is the string that replaces the character.
Examples:
Input: A portal in India
Replace A with Hello
Output: Hello portal in India

Input: Python is not equal to java
Replace is with was
Output: Python was not equal to java
Approach:
To replace a character with the specified string follow the following step:
Declare a string
Use Replace() function to replace the character(i.e., “A”) with string(i.e., “Geeks For Geeks”))
input_string.Replace("A", "Geeks For Geeks")
Display the modified string
Example:
C#
// C# program to replace a character// with a specified stringusing System; class GFG{ public static void Main(){         // Define string    String input_string = "A portal in India";     Console.WriteLine("Actual String : " + input_string);     // Replace the string 'A' with 'Geeks For Geeks'    Console.WriteLine("Replaced String: " +         input_string.Replace("A", "Geeks For Geeks"));}}
Output:
Actual String : A portal in India
Replaced String: Geeks For Geeks portal in India
surinderdawra388
CSharp-programs
CSharp-Strings-Programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.sort_values()

05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.sort_values() function is used to sort the given series object in ascending or descending order by some criterion. The function also provides the flexibility of choosing the sorting algorithm.
Syntax: Series.sort_values(axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
Parameter :axis : Axis to direct sorting.ascending : If True, sort values in ascending order, otherwise descending.inplace : If True, perform operation in-place.kind : Choice of sorting algorithm.na_position : Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.
Returns : Series
Example #1: Use Series.sort_values() function to sort the elements of the given series object in lexicographical order.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe/Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.sort_values() function to sort the elements of the given series object in ascending order.
# sort the values in ascending ordersr.sort_values()
Output :
As we can see in the output, the Series.sort_values() function has successfully sorted the elements of the given series object in ascending order. Example #2: Use Series.sort_values() function to sort the elements of the given series object in descending order.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])  # Print the seriesprint(sr)
Output :
Now we will use Series.sort_values() function to sort the elements of the given series object in descending order.
# sort the values in descending ordersr.sort_values(ascending = False)
Output :
As we can see in the output, the Series.sort_values() function has successfully sorted the elements of the given series object in descending order.
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
Iterate over a list in Python
Python OOPs Concepts
How to set Text alignment in HTML?

To set text alignment in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property text-align for the center, left and right alignment. HTML5 do not support the align attribute of the <p> tag, so the CSS style is used to set text alignment.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to set text alignment in HTML
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Document</title>
   </head>

   <body>
      <h1>Tutorial</h1>
      <p style="text-align:center;">Learn for free</p>
   </body>
</html>
How to set the background image for an element with JavaScript DOM?

To set the background image in JavaScript, use the backgroundImage property. It allows you to set the background image.
You can try to run the following code to learn how to set the background image with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <button onclick="display()">Click to Set background image</button>
      <script>
         function display() {
            document.body.style.backgroundImage = "url('https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg')";
         }
      </script>
   </body>
</html>
Why do we need a wrapper class in Java?

A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc). In other words, wrapper classes provide a way to use primitive data types
(int, char, short, byte, etc) as objects. These wrapper classes come under java.util package.
Wrapper Class will convert primitive data types into objects. The objects are necessary if we wish to modify the arguments passed into the method (because primitive types are passed by value).
The classes in java.util package handles only objects and hence wrapper classes help in this case also.
Data
structures in the Collection framework such as ArrayList and Vector store only the objects (reference types) and not the primitive types.
The object is needed to support synchronization in multithreading.
Autoboxing is used to convert primitive data types into corresponding objects.
Live Demo
public class AutoBoxingTest {
   public static void main(String args[]) {
      int num = 10; // int primitive
      Integer obj = Integer.valueOf(num); // creating a wrapper class object
      System.out.println(num + " " + obj);
   }
}
10 10
Unboxing is used to convert the Wrapper class object into corresponding primitive data types.
Live Demo
public class UnboxingTest {
   public static void main(String args[]) {
      Integer obj = new Integer(10); // Creating Wrapper class object
      int num = obj.intValue(); // Converting the wrapper object to primitive datatype
      System.out.println(num + " " + obj);
   }
}
10 10
Display AM/PM time marker with SimpleDateFormat(“a”) in Java

You can display AM/PM time marker easily in Java using SimpleDateFormat(“a”).
Firstly, to work with SimpleDateFormat class in Java, import the following package.
import java.text.SimpleDateFormat;
Now, set the format with SimpleDateFormat(“a”) to display AM/PM marker −
Format f = new SimpleDateFormat(”a”);
Now, get the marker in a string −
String strMarker = f.format(new Date());
The following is an example −
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
      System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
      // displaying hour
      Format f = new SimpleDateFormat("H");
      String strHour = f.format(new Date());
      System.out.println("Current Hour = "+strHour);
      // displaying minutes
      f = new SimpleDateFormat("mm");
      String strMinute = f.format(new Date());
      System.out.println("Current Minutes = "+strMinute);
      // displaying seconds in two-digits
      f = new SimpleDateFormat("ss");
      String strSeconds = f.format(new Date());
      System.out.println("Current Seconds = "+strSeconds);
      // displaying AM/ PM
      f = new SimpleDateFormat("a");
      String strMarker = f.format(new Date());
      System.out.println("Current AM/PM Marker = "+strMarker);
   }
}
Today's date = 26/November/2018 08:08:52
Current Hour = 8
Current Minutes = 08
Current Seconds = 52
Current AM/PM Marker = AM
Python Convert nested dictionary into flattened dictionary?

As the world embraces more unstructured data, we come across many formats of data where the data structure can be deeply nested like nested JSONS. Python has the ability to deal with nested data structure by concatenating the inner keys with outer keys to flatten the data. In this article we will take a nested dictionary and flattened it.
In this approach we design a function to recursively process each item in the dictionary. We pass the dictionary, design a place holder for the output dictionary, the key and separator as parameters. We use the isinstance to check if the next item itself is a dictionary and then pass it through the recursive call if it is also a dictionary.
dictA = {
   "id": "0001",
   "name": "hotdog",
   "image":
      {
         "url": "images/0001.jpg",

            "thumbnail":
               {
                  "url": "images/thumbnails/0001.jpg",
                  "height,width": "2x4"
               }
      }
}
def dict_flatten(in_dict, dict_out=None, parent_key=None, separator="_"):
   if dict_out is None:
      dict_out = {}

   for k, v in in_dict.items():
      k = f"{parent_key}{separator}{k}" if parent_key else k
      if isinstance(v, dict):
         dict_flatten(in_dict=v, dict_out=dict_out, parent_key=k)
         continue

      dict_out[k] = v

   return dict_out

final_dict = dict_flatten(dictA)
print(final_dict)
Running the above code gives us the following result −
{
   'id': '0001',
   'name': 'hotdog',
   'image_url': 'images/0001.jpg',
   'image_thumbnail_url': 'images/thumbnails/0001.jpg',
   'image_thumbnail_height,width': '2x4'
}
This is a module which can be directly used by giving it the dictionary as input. The default separator is -.
from cherrypicker import CherryPicker

dictA = {
   "id": "0001",
   "name": "hotdog",
   "image":
      {
         "url": "images/0001.jpg",

            "thumbnail":
               {
                  "url": "images/thumbnails/0001.jpg",
                  "height,width": "2x4"
               }
      }
}

picker = CherryPicker(dictA)
print(picker.flatten().get())
Running the above code gives us the following result −
{
   'id': '0001',
   'name': 'hotdog',
   'image_url': 'images/0001.jpg',
   'image_thumbnail_url': 'images/thumbnails/0001.jpg',
   'image_thumbnail_height,
   width': '2x4'
}
Foundation - Combined Column/Row

The column and row classes are used on the same element to get the full-width column to use as container.
The following example demonstrates the use of combined column/row class in Foundation −
<!DOCTYPE html>
<html>
   <head>
      <title>Foundation Template</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">

      <!-- Compressed CSS -->
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous">

      <!-- Compressed JavaScript -->
      <script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script>
   </head>

   <body>
      <h3>Example of combined column and row</h3>

      <div class = "column row" style = "background-color:#8BD6EE;">
         Lorem Ipsum is simply dummy text of the printing and typesetting industry.
         Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
         when an unknown printer took a galley of type and scrambled it to make a type
         specimen book.
      </div>

   </body>
</html>
Let us carry out the following steps to see how the above given code works −
Save the above given html code combined_row_column.html file.
Save the above given html code combined_row_column.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.

    117 Lectures 
     5.5 hours 

 Shakthi Swaroop

    61 Lectures 
     1.5 hours 

 Hans Weemaes

    17 Lectures 
     4 hours 

 Stephen Kahuria

    8 Lectures 
     50 mins

 Zenva

    28 Lectures 
     2 hours 

 Sandra L

    16 Lectures 
     2.5 hours 

 GreyCampus Inc.
 Print
 Add Notes
 Bookmark this page
HTTP headers | Expect - GeeksforGeeks

18 Oct, 2019
The HTTP headers Expect request-header field is used to indicate specific behaviors or expectations that the server needs to fulfill in order to respond to the client. Generally, Expect: 100-continue is the only expectation defined for the header field. If the data provided in the header field meets the expectation value, then the server responds with 100 indicating that it is a success, else it responds with status 417 specifying that the expectation has failed. The reason behind putting the Expect, that would be to work around broken web servers.
Syntax:
Expect: 100-continue
Directives:
100-continue: It means that the server has received the request header and in order to send the request body, the server must respond with status 100 to the client.
Note: There is no need to put a blank header if you are not going to put any Expect clause.
Example:
PUT /demo/program HTTP/1.1
Host: original.sample.com
Content-Type: video/h264
Content-Length: 2342564178765
Expect: 100-continue
The server now goes through the request headers and either responds with 100 indicating the client to send the request body or return status 417 if the expectations are not met.
Supported Browsers: The browsers compatibility for HTTP headers Expect is unknown right now.
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
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 create footer to stay at the bottom of a Web page?
How to Insert Form Data into Database using PHP ?
How to redirect to another page in ReactJS ?
How to execute PHP code using command line ?
How to generate an UnsupportedOperationException in Java?


An UnsupportedOperationException is a subclass of RuntimException in Java and it can be thrown to indicate that the requested operation is not supported. The UnsupportedOperationException class is a member of the Java Collections Framework. This exception is thrown by almost all of the concrete collections like List, Queue, Set and Map.
public class UnsupportedOperationException extends RuntimeException
import java.util.*;
public class UnsupportedOperationExceptionTest {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add('a');
      aList.add('b');
      List newList = Collections.unmodifiableList(aList);
      newList.add('c');
   }
}
In the above example, it will generate an UnsupportedOperationException. In order to avoid this, we need to use the object of the collection rather than using the view object for modification.
Exception in thread "main" java.lang.UnsupportedOperationException
  at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
     at UnsupportedOperationExceptionTest.main(UnsupportedOperationExceptionTest.java:9)
SciPy Graphs

Graphs are an essential data structure.
SciPy provides us with the module scipy.sparse.csgraph for working with 
such data structures.
Adjacency matrix is a nxn matrix where n
is the number of elements in a graph.
And the values represents the connection between the elements.
Example:
For a graph like this, with elements A, B and C, the connections are:
A & B are connected with weight 1.
A & C are connected with weight 2.
C & B is not connected.
The Adjency Matrix would look like this:

      A B C
   A:[0 1 2]  
   B:[1 0 0]
   C:[2 0 0]


Below follows some of the most used methods for working with adjacency matrices.
Use the dijkstra method to find the shortest path in a graph from one element to 
another.
It takes following arguments:

return_predecessors: boolean (True to return whole path of traversal 
otherwise False).
indices: index of the element to return all paths from that element only.
limit: max weight of path.

return_predecessors: boolean (True to return whole path of traversal 
otherwise False).
indices: index of the element to return all paths from that element only.
limit: max weight of path.
Find the shortest path from element 1 to 2:
Use the floyd_warshall() method to find shortest path between all pairs of elements.
Find the shortest path between all pairs of elements:
The bellman_ford() method can also find the shortest path between all pairs of elements, but this method can handle negative weights as well.
Find shortest path from element 1 to 2 with given graph with a negative weight:
The depth_first_order() method returns a depth first traversal from a node.
This function takes following arguments:

the graph.
the starting element to traverse graph from.

the graph.
the starting element to traverse graph from.
Traverse the graph depth first for given adjacency matrix:
The breadth_first_order() method returns a breadth first traversal from a node.
This function takes following arguments:

the graph.
the starting element to traverse graph from.

the graph.
the starting element to traverse graph from.
Traverse the graph breadth first for given adjacency matrix:
Insert the missing method to find all the connected components:
import numpy as np
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

arr = np.array([
  [0, 1, 2],
  [1, 0, 0],
  [2, 0, 0]
])

newarr = csr_matrix(arr)

print((newarr))

Start the Exercise
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.
Python Program To Remove all control characters

27 Dec, 2021
In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is an essential utility. In this article, we will discuss how to remove all those control characters.
Example:
Input : test_str = ‘Geeks\0\r for \n\bge\tee\0ks\f’
Output : Geeks for geeeks
Explanation : \n, \0, \f, \r, \b, \t being control characters are removed from string.
Input : test_str = ‘G\0\r\n\fg’
Output : Gfg
Explanation : \n, \0, \f, \r being control characters are removed from string, giving Gfg as output.
Method 1 : Using translate().
The logic applied here is that each non-control character is at the top 33 ASCII characters, hence translation is used to avoid all others except these via mapping.
Python3
# Python3 code to demonstrate working of# Remove all control characters# Using translate() # initializing stringtest_str = 'Geeks\0\r for \n\bge\tee\0ks\f' # printing original stringprint("The original string is : " + str(test_str)) # using translate() and fromkeys()# to escape all control charactersmapping =  dict.fromkeys(range(32))res = test_str.translate(mapping) # printing resultprint("String after removal of control characters : " + str(res))
Output:
 for original string is : Geeks
ge    eeks
String after removal of control characters : Geeks for geeeks
Method 2: Using unicodedata library
In this, using unicodedata.category(), we can check each character starting with “C” is the control character and hence be avoided in the result string.
Python3
# Python3 code to demonstrate working of# Remove all control characters# Using unicodedata libraryimport unicodedata # initializing stringtest_str = 'Geeks\0\r for \n\bge\tee\0ks\f' # printing original stringprint("The original string is : " + str(test_str)) # surpassing all control characters# checking for starting with Cres = "".join(char for char in test_str if unicodedata.category(char)[0]!="C") # printing resultprint("String after removal of control characters : " + str(res))
Output:
 for original string is : Geeks
ge    eeks
String after removal of control characters : Geeks for geeeks
germanshephered48
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the version of the Pandas and its dependencies

23 Jan, 2019
Pandas is one of the most important packages for data analysis in Python and that means frequent updates of the version of the Pandas. This leads to compatibility issues with other dependencies of Pandas. Let’s discuss the ways to check the version of the Pandas and its dependencies running on any system.
Find the version of the Pandas running on any system.
We can use pd.__version__ to check the version of the Pandas running on any system.
# importing pandas as pdimport pandas as pd  # Check the versionprint(pd.__version__)
Output :
 
Find the version of the dependencies for the given version of the Pandas running on any system.
We can use the utility function pd.show_versions() to check the version of the dependencies.
# importing pandas as pdimport pandas as pd  # Check the version of the dependenciespd.show_versions()
Output :
Python pandas-basics
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java lang.Integer.toBinaryString() method

05 Dec, 2018
The java.lang.Integer.toBinaryString() method returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Syntax:
public static String toBinaryString(int num)

Parameter : The function accepts a single mandatory parameter num 
num - This parameter specifies the number to be converted to binary string. 
It is of int data-type 
Return Value: This function returns the string representation of the unsigned Integer value represented by the argument in binary (base 2).Examples:
Input : 10 
Output : 1010 

Input : 9
Output : 1001 

// Java program to demonstrate// java.lang.Integer.toBinaryString() methodimport java.lang.Math;  class Gfg1 {      // driver code    public static void main(String args[])    {          int l = 10;        // returns the string representation of the unsigned int value        // represented by the argument in binary (base 2)        System.out.println("Binary is " + Integer.toBinaryString(l));          l = 9;        System.out.println("Binary is " + Integer.toBinaryString(l));    }}
Output:
Binary is 1010
Binary is 1001

Java-Functions
Java-Integer
Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7

Tryit: Template 1 - using grid
How to move button in the same line with Checkbox and Textbox using JavaScript ? - GeeksforGeeks

16 Jul, 2020
The style “display” property in HTML DOM is used to set elements to “display” property. To set the button in the same line with other elements of the web page is done using the inline property.
Syntax:
It returns the “display” property.object.style.display
object.style.display
It sets the “display” property.object.style.display = inline;
object.style.display = inline;
Example:
<!DOCTYPE html><html>  <head>      <!-- script to set display property -->    <script>        function myGeeks() {            document.getElementById("GFG")                .style.display = "inline";        }     </script></head>  <body>    <div id="GFG">        <input type="checkbox" checked> computer        <input type="checkbox"> mobile          <input type="text">    </div>      <button onclick="myGeeks()">        Press    </button></body>  </html>
Output:
Before click on the button:
After click on the button:
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to Upload Image into Database and Display it using PHP ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
LocalDate compareTo() method in Java - GeeksforGeeks

28 Nov, 2018
The compareTo() method of LocalDate class in Java method compares this date to another date.
Syntax:
public int compareTo(ChronoLocalDate other)

Parameter: This method accepts a parameter other which specifies the other date to compare to and it is not specifically null.
Return Value: It returns the comparator value which is negative if it is less else it is positive if it is greater.
Below programs illustrate the compareTo() method of LocalDate in Java:
Program 1:
// Program to illustrate the compareTo() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // First date        LocalDate dt = LocalDate.parse("2018-11-01");        System.out.println(dt);          // Second date        LocalDate dt1 = LocalDate.parse("2018-11-14");        System.out.println(dt1);          // Compare both dates        System.out.println(dt1.compareTo(dt));    }}
2018-11-01
2018-11-14
13

Program 2:
// Program to illustrate the compareTo() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // First date        LocalDate dt = LocalDate.parse("2018-11-21");        System.out.println(dt);          // Second date        LocalDate dt1 = LocalDate.parse("2018-11-14");        System.out.println(dt1);          // Compare both dates        System.out.println(dt1.compareTo(dt));    }}
2018-11-21
2018-11-14
-7

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#compareTo(java.time.chrono.ChronoLocalDate)
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
HTML <hgroup> Tag - GeeksforGeeks

17 Mar, 2022
The <hgroup> tag in HTML stands for heading group and is used to group the heading elements. The <hgroup> tag in HTML is used to wrap one or more heading elements from <h1> to <h6>, such as the headings and sub-headings. The <hgroup> tag requires the starting tag as well as ending tag.
Note: <hgroup> is deprecated from HTML5 specification.Syntax :  
<hgroup> ... </hgroup>
Below examples illustrate the <hgroup> tag in HTML:Example 1: This example contains the Title and Sub-Title.  
HTML
<!DOCTYPE html> <html>     <body>         <!--HTML hgroup tag starts here-->            <hgroup>                <h1>This is the title.</h1>                <h2>This is sub-title.</h2>            </hgroup>         <!--HTML hgroup tag ends here-->        </body>          </html>                   
Output:  
Example 2: This example contains Title, Sub-Title, and Metadata.  
HTML
<!DOCTYPE html> <html>     <body>         <!--HTML hgroup tag starts here-->         <hgroup>            <h1>This is the title.</h1>            <h2>This is sub-title.</h2>              <p>This is the metadata.</p>          </hgroup>        <!--HTML hgroup tag ends here-->        </body>          </html>                   
Output:  
Supported Browsers: 
Google Chrome 5.0
Internet Explorer 9.0
Firefox 4.0
Opera 11.1
Safari 5.0
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
shubhamyadav4
ManasChhabra2
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Adding Text to Plots in R programming - text() and mtext () Function - GeeksforGeeks

07 Dec, 2021
Text is defined as a way to describe data related to graphical representation. They work as labels to any pictorial or graphical representation. In this article, we will learn to add a text to a plot in R Programming Language by using the text() and mtext() functions.
text () Function in R Programming Language is used to draw text elements to plots in Base R.
Syntax: text(x, y, labels)
Parameters: 
x and y: numeric values specifying the coordinates of the text to plot
labels: the text to be written
Returns: Added text to plot 
Example 1: 
R
# R program to add text to plot # Calling data setd<-head(mtcars) # Plotting the graphplot(d[, 'wt'], d[, 'mpg'],     main = " Car Weight vs. Milage ",     xlab = "Miles", ylab = " Weight",     pch = 19, col = "darkgreen") # Calling text() functiontext(d[, 'wt'], d[, 'mpg'],  row.names(d),     cex = 0.88, pos = 2, col = "darkgreen")
Output: 
In the above example, the text is added to the plot of ‘mtcar’ dataset.
Example 2: Implementation of text() to add a mathematical annotation to a plot 
R
# R program to add text to plot # Plotting the graphplot(1:5, 1:5,     main = "text() Function  examples") # Calling text() functiontext(2, 3, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))text(3, 4, expression(bar(x) == sum(frac(x[i], n), i==1, n)))
Output:
In the above example, the text() function is used to add a mathematical annotation to a plot
mtext() function in R Programming Language is used to add text to the margins of the plot. 
Syntax: mtext(text, side)
Parameters: 
text: text to be written
side: An integer specifying the side of the plot, such as: bottom, left, top, and right.
Returns: Added text in the margins of the graph 
Example: 
R
# R program to add text to a plot # Creating a plotplot(1:5, 1:5,     main = "mtext examples") # Calling mtext() functionmtext("mtext() function", side = 3)
Output:
Here, in the above example, the side specifies the side of the plot such as the bottom, left, top, right. And in the given the side=3 i.e the top part of the plot.
kumar_satyam
R Plot-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
ISRO | ISRO CS 2018 | Question 76 - GeeksforGeeks

04 Jul, 2018
Let us assume that transaction T1 has arrived before transaction T2. Consider the schedule
S=r1(A); r2(B) ; w2(A); w1(B) 
Which of the following is true?(A) Allowed under basic timestamp protocol.(B) Not allowed under basic timestamp protocols because T1 is rolled back(C) Not allowed under basic timestamp protocols because T2 is rolled back(D) None of theseAnswer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2016 | Question 29
ISRO | ISRO CS 2017 - May | Question 17
ISRO | ISRO CS 2017 | Question 54
ISRO | ISRO CS 2007 | Question 55
ISRO | ISRO CS 2017 - May | Question 40
ISRO | ISRO CS 2007 | Question 80
ISRO | ISRO CS 2017 - May | Question 13
ISRO | ISRO CS 2013 | Question 54
ISRO | ISRO CS 2013 | Question 51
ISRO | ISRO CS 2014 | Question 31
Difference between AI and Soft Computing - GeeksforGeeks

25 Mar, 2020
Artificial Intelligence:AI manages more comprehensive issues of automating a system. This computerization should be possible by utilizing any field such as image processing, cognitive science, neural systems, machine learning etc. AI manages the making of machines, frameworks and different gadgets savvy by enabling them to think and do errands as all people generally do.
Soft Computing:Soft Computing could be a computing model evolved to resolve the non-linear issues that involve unsure, imprecise and approximate solutions of a tangle. These sorts of issues square measure thought of as real-life issues wherever the human-like intelligence is needed to resolve it.
Difference between AI and Soft Computing:
1. Reasoning
2. Perception
3. Natural language processing  
1. Fuzzy systems
2. Evolutionary computation
3. Artificial neural computing  
Difference Between
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Naive Bayes Classifiers
Linear Regression (Python Implementation)
ML | Linear Regression
Reinforcement learning
Removing stop words with NLTK in Python
Python - Extract selective keys' values Including Nested Keys - GeeksforGeeks

04 Jan, 2022
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys’ values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys’ values. Let’s discuss certain way in which this task can be solved. 
Input : test_dict = {‘gfg’: {‘geeks’: {‘best’ : 3}}} key_list = [‘best’, ‘geeks’] Output : {‘geeks’: {‘best’: 3}, ‘best’: 3}Input : test_dict = {‘gfg’: {‘geek’: {‘good’ : 3}}} key_list = [‘best’, ‘geeks’] Output : {}  
Method : Using recursion + loop + yield The combination of above functionalities can be used to solve this problem. In this, we perform the task of checking for key using conditional statements and check for nestings using recursion. The yield operator is used to dynamically return the key for assignment as it occurs. 
Python3
# Python3 code to demonstrate working of# Extract selective keys' values [ Including Nested Keys ]# Using recursion + loop + yield def get_vals(test_dict, key_list):   for i, j in test_dict.items():     if i in key_list:        yield (i, j)     yield from [] if not isinstance(j, dict) else get_vals(j, key_list) # initializing dictionarytest_dict = {'gfg': {'is': {'best' : 3}}, 'for': {'all' : 4}, 'geeks': 5} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing keys listkey_list = ['best', 'geeks'] # Extract selective keys' values [ Including Nested Keys ]# Using recursion + loop + yieldres = dict(get_vals(test_dict, key_list)) # printing resultprint("The extracted values : " + str(res))
The original dictionary is : {'gfg': {'is': {'best': 3}}, 'for': {'all': 4}, 'geeks': 5}
The extracted values : {'best': 3, 'geeks': 5}
 
nnr223442
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
insmod command in Linux with examples - GeeksforGeeks

22 May, 2019
insmod command in Linux systems is used to insert modules into the kernel. Linux is an Operating System which allows the user to load kernel modules on run time to extend the kernel functionalities. LKMs(Loadable Kernel Modules) are usually used to add support for new hardware (as device drivers) and/or filesystems, or for adding system calls. This command here inserts the kernel object file (.ko) into the kernel with/without arguments, along with a few additional options.
Syntax:
insmod [file name] [module-options...]
Options:
insmod command with help option: The insmod command throws an error if no options, filename or arguments are passed. So, when we use the -h option, it gives the general syntax along with the various options that can be used with the insmod command.insmod -h

insmod -h

insmod command with version option: This is used to view the version of the insmod command.insmod -V

insmod -V

Examples:
insmod + file name: This command is used to insert the LKM file (.ko) into the Linux Kernel. The working directory is changed to the one with the LKM file, and then the command is executed. Root privilege is needed to run this instruction.Note: The LKM file used here is present in the desktop(which is the working directory), and doesn’t take any arguments, and prints a message to the system log. This message can be viewed by using the dmesg command.sudo insmod geeksforgeeks.ko
Example:
Note: The LKM file used here is present in the desktop(which is the working directory), and doesn’t take any arguments, and prints a message to the system log. This message can be viewed by using the dmesg command.
sudo insmod geeksforgeeks.ko

Example:
insmod + file directory + file name: Like the previous command, insmod works when you specify the file directory along with the LKM file’s name. This is illustrated below.Example:sudo insmod /home/mukkesh/Desktop/geeksforgeeks.ko

Example:
sudo insmod /home/mukkesh/Desktop/geeksforgeeks.ko

Passing parameters to the module using insmod: LKM files can have parameters/arguments passed to them through the insmod command. These arguments essentially act as inputs for the LKMs. Depending on how the LKM is written, the arguments are used.Note:The LKM used here takes the string parameter “user” and prints a message which includes the passed parameter.Example:sudo insmod geeks4geeks.ko user="Mukkesh"

Note:The LKM used here takes the string parameter “user” and prints a message which includes the passed parameter.
Example:
sudo insmod geeks4geeks.ko user="Mukkesh"

linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
How to set title for action bar in android?

This example demonstrates How to set title for action bar in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show status bar tittle.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      getSupportActionBar().setTitle("Home");
      getSupportActionBar().setSubtitle("sairam");
      textView.setText(" tittle is Home");
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code