code-rag-bench/online-tutorials huggingface dataset:
Area of a n-sided regular polygon with given Radius?

Here we will see how to get the area of an n-sided regular polygon whose radius is given. Here the radius is the distance from the center of any vertex. To solve this problem, we have drawn one perpendicular from the center to one side. Let each side is of length ‘a’. The perpendicular is dividing the side into two parts. The length of each part is a/2. The perpendicular and one radius is making an angle x. Let the length of the radius is h.
Here we can see that the polygon is divided into N equal triangles. So for any polygon with N sides, will be divided into N triangles. So the angle at the center is 360. That is divided into 360°/N different angles (Here 360°/6 = 60°). So the angle x is 180°/N. Now we can easily get the h and a using trigonometric equations.
Now the area of whole polygon is N*A.
#include <iostream>
#include <cmath>
using namespace std;
float polygonArea(float r, int n){
   return ((r * r * n) * sin((360 / n) * 3.1415 / 180)) / 2; //convert
   angle to rad then calculate
}
int main() {
   float rad = 9.0f;
   int sides = 6;
   cout << "Polygon Area: " << polygonArea(rad, sides);
}
Polygon Area: 210.44
Hamming Distance in Python

Consider we have two integers. We have to find the Hamming distance of them. The hamming distance is the number of bit different bit count between two numbers. So if the numbers are 7 and 15, they are 0111 and 1111 in binary, here the MSb is different, so the Hamming distance is 1.
To solve this, we will follow these steps −
For i = 31 down to 0b1 = right shift of x (i AND 1 time)b2 = right shift of y (i AND 1 time)if b1 = b2, then answer := answer + 0, otherwise answer := answer + 1
b1 = right shift of x (i AND 1 time)
b2 = right shift of y (i AND 1 time)
if b1 = b2, then answer := answer + 0, otherwise answer := answer + 1
return answer
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def hammingDistance(self, x, y):
      """
      :type x: int
      :type y: int
      :rtype: int
      """
      ans = 0
      for i in range(31,-1,-1):
         b1= x>>i&1
         b2 = y>>i&1
         ans+= not(b1==b2)
         #if not(b1==b2):
            # print(b1,b2,i)
      return ans
ob1 = Solution()
print(ob1.hammingDistance(7, 15))
7
15
1
Python - Ways to Copy Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. They copy() method returns a shallow copy of the dictionary.
 Live Demo
#creating a dictionary
original = {1:'vishesh', 2:'python'}
# copying using copy() function
new = original.copy()
# removing all elements from the list Only new list becomes empty as #copy() does shallow copy.
new.clear()
print('new: ', new)
print('original: ', original)
# between = and copy()
original = {1:'Vishesh', 2:'python'}
# copying using copy() function
new = original.copy()
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)
original = {1:'one', 2:'two'}
# copying using =
new = original
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)
('new: ', {})
('original: ', {1: 'vishesh', 2: 'python'})
('new: ', {})
('original: ', {1: 'Vishesh', 2: 'python'})
('new: ', {})
('original: ', {})
MIME Media Types

MIME (Multipurpose Internet Mail Extension) media types were originally devised so that e-mails could include information other than plain text. MIME media types indicate the following things −
How different parts of a message, such as text and attachments, are combined into the message.
How different parts of a message, such as text and attachments, are combined into the message.
The way in which each part of the message is specified.
The way in which each part of the message is specified.
The way different items are encoded for transmission so that even software that was designed to work only with ASCII text can process the message.
The way different items are encoded for transmission so that even software that was designed to work only with ASCII text can process the message.
Now MIME types are not just for use with e-mail; they have been adopted by Web servers as a way to tell Web browsers what type of material was being sent to them so that they can cope with that kind of messages correctly.
MIME content types consist of two parts −
A main type
A sub-type
The main type is separated from the subtype by a forward slash character. For example, text/html for HTML.
This chapter is organized for the main types −
text
image
multipart
audio
video
message
model
application
For example, the text main type contains types of plain text files, such as −
text/plain for plain text files
text/html for HTML files
text/rtf for text files using rich text formatting
MIME types are officially supposed to be assigned and listed by the Internet Assigned Numbers Authority (IANA).
Many of the popular MIME types in this list (all those begin with "x-") are not assigned by the IANA and do not have official status. You can see the list of official MIME types at http://www.iana.org/assignments/media-types/. Those preceded with .vnd are vendorspecific.
When specifying the MIME type of a content-type field you can also indicate the character set for the text being used. If you do not specify a character set, the default is US-ASCII. For example −
content-type:text/plain; charset=iso-8859-1


    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Histograms Equalization in OpenCV - GeeksforGeeks

22 Feb, 2018
Prerequisite : Analyze-image-using-histogram
Histogram equalization is a method in image processing of contrast adjustment using the image’s histogram.
This method usually increases the global contrast of many images, especially when the usable data of the image is represented by close contrast values. Through this adjustment, the intensities can be better distributed on the histogram. This allows for areas of lower local contrast to gain a higher contrast. Histogram equalization accomplishes this by effectively spreading out the most frequent intensity values. The method is useful in images with backgrounds and foregrounds that are both bright or both dark.
OpenCV has a function to do this, cv2.equalizeHist(). Its input is just grayscale image and output is our histogram equalized image.
Input Image :
Below is Python3 code implementing Histogram Equalization :
# import Opencvimport cv2  # import Numpyimport numpy as np  # read a image using imreadimg = cv2.imread(\'F:\\do_nawab.png\', 0)  # creating a Histograms Equalization# of a image using cv2.equalizeHist()equ = cv2.equalizeHist(img)  # stacking images side-by-sideres = np.hstack((img, equ))  # show image input vs outputcv2.imshow(\'image\', res)  cv2.waitKey(0)cv2.destroyAllWindows()
Output :
  

Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
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
CSS cue Property - GeeksforGeeks

20 Nov, 2020
It is a shorthand version for both cue-before and cue-after property. It specifies that an auditory icon played before or after the element to distinguish and set the element. 
Syntax: 
cue: <cue-before> <cue-after>?
Property Values:
CSS cue-before: It is used to define an auditory icon played before the element to distinguish and set the element.Syntax:cue-before: url|none;Example:<!DOCTYPE html> <html>   <head>     <style>         .gfg {             cue-before: url("bell.wav");         }     </style> </head>   <body style="text-align: center;">     <h1 style="color: green;">GeeksforGeeks</h1>     <p class="gfg">CSS cue-before Property</p>       <audio controls>         <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3"        type="audio/mp3">     </audio> </body>   </html> Output:
Syntax:
cue-before: url|none;
Example:
<!DOCTYPE html> <html>   <head>     <style>         .gfg {             cue-before: url("bell.wav");         }     </style> </head>   <body style="text-align: center;">     <h1 style="color: green;">GeeksforGeeks</h1>     <p class="gfg">CSS cue-before Property</p>       <audio controls>         <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3"        type="audio/mp3">     </audio> </body>   </html> 
Output:
CSS cue-after: It is used to define an auditory icon played after the element to distinguish and set the element.Syntax:cue-after: url | none ;Example:<!DOCTYPE html> <html>   <head>     <style>         .gfg {             cue-after: url("bell.wav");         }     </style> </head>   <body style="text-align: center;">     <h1 style="color: green;">GeeksforGeeks</h1>     <p class="gfg">CSS cue-after Property</p>       <audio controls>         <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3"        type="audio/mp3">     </audio> </body>   </html> Output:
Syntax:
cue-after: url | none ;
Example:
<!DOCTYPE html> <html>   <head>     <style>         .gfg {             cue-after: url("bell.wav");         }     </style> </head>   <body style="text-align: center;">     <h1 style="color: green;">GeeksforGeeks</h1>     <p class="gfg">CSS cue-after Property</p>       <audio controls>         <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3"        type="audio/mp3">     </audio> </body>   </html> 
Output:
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
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
Permutations in Python

Suppose we have a collection of distinct integers; we have to find all possible permutations. So if the array is like [2,1,3], then the result will be [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
To solve this, we will follow these steps −
We will use the recursive approach, this will make the list, start, curr and res
if start > length of list – 1, then add curr into the res, and return
for i in range start to length of given list – 1swap the elements of list present at index start and (start + (i – start))permutation(list, start + 1, curr + [list[start]], res)swap the elements of list present at index start and (start + (i – start))initially call the permutation(arr, 0, [], res)
swap the elements of list present at index start and (start + (i – start))
permutation(list, start + 1, curr + [list[start]], res)
swap the elements of list present at index start and (start + (i – start))
initially call the permutation(arr, 0, [], res)
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def permute(self, nums):
      result = []
      self.permute_util(nums,0,[],result)
      return result
   def permute_util(self,given_list,start,curr,result):
      if start > len(given_list)-1:
         #print(curr)
         result.append(curr)
         return
      for i in range(start,len(given_list)):
         self.swap(given_list,start,start+(i-start)) self.permute_util(given_list,start+1,curr+[given_list[start]],result)
         #print(given_list)
         self.swap(given_list, start, start + (i - start))
   def swap(self,nums,index1,index2):
      temp = nums[index1]
      nums[index1] = nums[index2]
      nums[index2] = temp
ob1 = Solution()
print(ob1.permute([1,2,3,4]))
[1,2,3,4]
[[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,3,2],[1,4,2,3],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,3,1],[2,4,1,3],[3,2,1,4],[3,2,4,1],[3,1,2,4],[3,1,4,2],[3,4,1,2],[3,4,2,1],[4,2,3,1],[4,2,1,3],[4,3,2,1],[4,3,1,2],[4,1,3,2],[4,1,2,3]]
Generate array of random unique numbers in PHP?

For random unique numbers array, use range() along with shuffle().
The PHP code is as follows
 Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
$limit_random_array_values = range(10, 20);
shuffle($limit_random_array_values);
$all_five_random_array_value = array_slice($limit_random_array_values ,0,5);
print_r($all_five_random_array_value);
?>
</body>
</html>
This will produce the following output
Array ( [0] => 11 [1] => 14 [2] => 15 [3] => 12 [4] => 18 )
How to select the second index in Java JList?

To select the second index, use the setSelectedIndex() method −
JList new JList(sports);
list.setSelectedIndex(2);
The following is an example to select the second index in Java JList −
package my;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class SwingDemo extends JFrame {
   static JFrame frame;
   static JList list;
   public static void main(String[] args) {
      frame = new JFrame("JList Demo");
      SwingDemo s = new SwingDemo();
      JPanel panel = new JPanel();
      String sports[]= { "Cricket","Football","Hockey","Rugby"};
      list = new JList(sports);
      list.setSelectedIndex(2);
      panel.add(list);
      frame.add(panel);
      frame.setSize(400,400);
      frame.setVisible(true);
   }
}
What is Interface segregation principle and how to implement it in C#?

Clients should not be forced to depend upon interfaces that they don't use.
The Interface Segregation Principle states that clients should not be forced to implement interfaces they don't use.
Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one submodule
public interface IProduct {
   int ID { get; set; }
   double Weight { get; set; }
   int Stock { get; set; }
   int Inseam { get; set; }
   int WaistSize { get; set; }
}
public class Jeans : IProduct {
   public int ID { get; set; }
   public double Weight { get; set; }
   public int Stock { get; set; }
   public int Inseam { get; set; }
   public int WaistSize { get; set; }
}
public class BaseballCap : IProduct {
   public int ID { get; set; }
   public double Weight { get; set; }
   public int Stock { get; set; }
   public int Inseam { get; set; }
   public int WaistSize { get; set; }
   public int HatSize { get; set; }
}
public interface IProduct {
   int ID { get; set; }
   double Weight { get; set; }
   int Stock { get; set; }
}
public interface IPants {
   int Inseam { get; set; }
   int WaistSize { get; set; }
}
public interface IHat {
   int HatSize { get; set; }
}
public class Jeans : IProduct, IPants {
   public int ID { get; set; }
   public double Weight { get; set; }
   public int Stock { get; set; }
   public int Inseam { get; set; }
   public int WaistSize { get; set; }
}
public class BaseballCap : IProduct, IHat {
   public int ID { get; set; }
   public double Weight { get; set; }
   public int Stock { get; set; }
   public int HatSize { get; set; }
}
What are class instances in C#?

Class instances are objects. Like any other object-oriented language, C# also has object and classes. Objest are real-world entities and instance of a class. Access the members of the class using an object.
To access the class members, you use the dot (.) operator after the object name. The dot operator links the name of an object with the name of a member for example,
Box Box1 = new Box();
Above you can see Box1 is our object. We will use it to access the members −
Box1.height = 7.0;
You can also use it to call member functions −
Box1.getVolume();
The following is an example showing how objects and class work in C# −
 Live Demo
using System;

namespace BoxApplication {
   class Box {
      private double length; // Length of a box
      private double breadth; // Breadth of a box
      private double height; // Height of a box

      public void setLength( double len ) {
         length = len;
      }
      public void setBreadth( double bre ) {
         breadth = bre;
      }
      public void setHeight( double hei ) {
         height = hei;
      }
      public double getVolume() {
         return length * breadth * height;
      }
   }

   class Boxtester {
      static void Main(string[] args) {
         // Creating two objects
         Box Box1 = new Box(); // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;
   
         // using objects to call the member functions
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         Console.ReadKey();
      }
   }
}
Volume of Box1 : 210
Volume of Box2 : 1560
jQuery Set Content and Attributes

We will use the same three methods from the previous page to set content:
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields
The following example demonstrates how to set content with the jQuery text(), html(), 
and val() methods:
All of the three jQuery methods above: text(), html(), 
and val(), also come with a callback function. The callback function has two 
parameters: the index of the current element in the list of elements selected 
and the original (old) value. You then return the string you wish to use as the 
new value from the function.
The following example demonstrates text() and html() with a callback 
function:
The jQuery attr() method is also used to set/change attribute values.
The following example demonstrates how to change (set) the value of the href attribute 
in a link:
The attr() method also allows you to set multiple attributes at the same 
time.
The following example demonstrates how to set both the href and title attributes 
at the same time:
The jQuery method attr(), also comes with a callback function. The callback function has two 
parameters: the index of the current element in the list of elements selected 
and the original (old) attribute value. You then return the string you wish to use as the 
new attribute value from the function.
The following example demonstrates attr() with a callback 
function:
Use a jQuery method to change the text of a <div> element to "Hello World".
$("div").("");

Start the Exercise
For a complete overview of all jQuery HTML methods, please go to our
jQuery HTML/CSS Reference.
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.
GATE | GATE CS 2012 | Question 33 - GeeksforGeeks

28 Jun, 2021
Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n elements. Assume that the insertion and deletion operation are carried out using REAR and FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions to detect queue full and queue empty are(A) Full: (REAR+1) mod n == FRONT, empty: REAR == FRONT(B) Full: (REAR+1) mod n == FRONT, empty: (FRONT+1) mod n == REAR(C) Full: REAR == FRONT, empty: (REAR+1) mod n == FRONT(D) Full: (FRONT+1) mod n == REAR, empty: REAR == FRONTAnswer: (A)Explanation:Implementation of Circular Queue :
Head – It always points to the location from where next deletion takes place from the queue.Tail – It always points to the next empty location in which next insertion will take place in the queue.
We will be using wrap around feature since it is a circular queue which is when the tail or head is at the index n-1, next operation will bring them to index 0. In Spite of having capacity of n inside array, we will reserve one empty spot in order to detect the overflow(Queue Full) and underflow(Queue Empty) conditions. The elements in the queue reside in locations Q.head, Q.head + 1, . . . , Q.tail + 1, where we “wrap around” in the sense that location 0 immediately follows location n-1 in a circular order.
Algorithm :
ENQUEUE(Q, x)                        
{

  if Q.head == Q.tail + 1
      error "Queue overflow"

  Q[Q.tail] = x

  if Q.tail == Q.length    - 1
      Q.tail = 0
  else
      Q.tail = Q.tail + 1
}


DEQUEUE(Q)
{
  if Q.head == Q.tail
      error "Queue underflow"

  x = Q[Q.head]

  if Q.head == Q.length - 1
      Q.head = 0
  else
      Q.head = Q.head + 1

  return x
}


See http://en.wikipedia.org/wiki/Circular_buffer#Always_Keep_One_Slot_Open
This solution is contributed by Pranjul AhujaQuiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
Whitespace in C++

Whitespace is a term that refers to characters that are used for formatting purposes. In C++, this refers primarily to spaces, tabs, and (sometimes) newlines. The C++ compiler generally ignores whitespace, with a few minor exceptions. For example, all the 4 lines below mean the same thing −
cout<<"Hello";
cout << "Hello";
cout                <<          "Hello"     ;
cout
<<
"Hello";
The exceptions where C++ compiler takes whitespace in consideration is inside quotes and for operator detection. So whenever you put in a string, c++ takes note of the whitespace. For example,
"Hello world!"
"Hello     world!"
Both of these are different strings. Also when you use compound operators or any multi-character operator, you cannot put in space between. For example,
<< and < < are different. Similarly, += and + = are different, with the latter not being a valid expression.
Check the number is Armstrong or not using C

How to check whether the given number is an Armstrong number or not using C Programming language?
Armstrong number is the number that is equal to the sum of cubes of its digits.
pqrs.........=pow(p,n)+pow(q,n)+pow(r,n)+..........
For example, 153,371,1634, etc., are Armstrong numbers.
153=1*1*1 + 5*5*5 + 3*3*3
   =1+125+27
   =153 (Armstrong number)
 Live Demo
#include<stdio.h>
int main(){
   int number,remainder,total=0,temp;
   printf("enter the number=");
   scanf("%d",&number);
   temp=number;
   while(number>0){
      remainder=number%10;
      total=total+(remainder*remainder*remainder);
      number=number/10;
   }
   if(temp==total)
      printf("This number is Armstrong number");
   else
      printf("This number is not Armstrong number");
   return 0;
}
enter the number=371
This number is Armstrong number
Check: 371=3*3*3 +7*7*7 + 1*1*1
           =27 + 343 +1
           =371
enter the number=53
This number is not Armstrong number
53 = 5*5*5 + 3*3*3
   =125 +27
   = 152 != 53
C++ Program for Sieve of Eratosthenes - GeeksforGeeks

27 Feb, 2018
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”.
// C++ program to print all primes smaller than or equal to// n using Sieve of Eratosthenes#include <bits/stdc++.h>using namespace std;  void SieveOfEratosthenes(int n){    // Create a boolean array "prime[0..n]" and initialize    // all entries it as true. A value in prime[i] will    // finally be false if i is Not a prime, else true.    bool prime[n+1];    memset(prime, true, sizeof(prime));      for (int p=2; p*p<=n; p++)    {        // If prime[p] is not changed, then it is a prime        if (prime[p] == true)        {            // Update all multiples of p            for (int i=p*2; i<=n; i += p)                prime[i] = false;        }    }      // Print all prime numbers    for (int p=2; p<=n; p++)       if (prime[p])          cout << p << " ";}  // Driver Program to test above functionint main(){    int n = 30;    cout << "Following are the prime numbers smaller "         << " than or equal to " << n << endl;    SieveOfEratosthenes(n);    return 0;}
Output:
Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29
Please refer complete article on Sieve of Eratosthenes for more details!
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
isdigit() function in C/C++ with Examples
Why it is important to write "using namespace std" in C++ program?
Different ways to print elements of vector
Setting up Sublime Text for C++ Competitive Programming Environment
Program to count Number of connected components in an undirected graph
Python - Cast datatype of only a single column in a Pandas DataFrame

To cast only a single column, use the astype() method. Let us first create a DataFrame with 2 columns. One of them is a “float64” type and another “int64” −
dataFrame = pd.DataFrame(
   {
      "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
      "Units": [90, 120, 100, 150, 200, 130]
   }
)
Check the types −
dataFrame.dtypes

Let’s say we need to cast only a single column “Units” from int64 to int32. For that, use astype() −
dataFrame.astype({'Units': 'int32'}).dtypes
Following is the code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
      "Units": [90, 120, 100, 150, 200, 130]
   }
)

print"DataFrame ...\n",dataFrame
print"\nDataFrame Types ...\n",dataFrame.dtypes
print"\nCast only a single column to int32..."

print"\nUpdated DataFrame Types ...\n",dataFrame.astype({'Units': 'int32'}).dtypes



This will produce the following output −
DataFrame ...
   Reg_Price   Units
0 7000.50570     90
1 1500.00000    120
2 5000.00000    100
3 8000.00000    150
4 9000.75768    200
5 6000.00000    130

DataFrame Types ...
Reg_Price   float64
Units         int64
dtype: object

Cast only a single column to int32...

Updated DataFrame Types ...
Reg_Price   float64
Units         int32
dtype: object
What is the difference between setTimeout() and setInterval() in JavaScript?

setTimeout( function, duration) − This function calls function after duration milliseconds from now. This goes for one execution. Let’s see an example −
It waits for 2000 milliseconds, and then runs the callback function alert(‘Hello’) −
setTimeout(function() { alert('Hello');}, 2000);
setInterval(function, duration) − This function calls function after every duration milliseconds. This goes for unlimited times. Let’s see an example −
It triggers the alert(‘Hello’) after every 2000 milliseconds, not only once.
setInterval(function() { alert('Hello');}, 2000);
Unrestricted Grammar 

Theory of Computation
In automaton, Unrestricted Grammar or Phrase Structure Grammar is the most general in the Chomsky Hierarchy of classification. This is type0 grammar, generally used to generate Recursively Enumerable languages. It is called unrestricted because no other restriction is made on this except each of their left hand sides being non-empty. The left hand sides of the rules can contain terminal and non-terminal, but the condition is at least one of them must be non-terminal.
A Turning Machine can simulate Unrestricted Grammar and Unrestricted Grammar can simulate Turning Machine configurations. It can always be found for the language recognized or generated by any Turning Machine.
The unrestricted grammar is 4 tuple -
G = (N,Σ,P,S)
N - A finite set of non-terminal symbols or variables,
Σ - It is a set of terminal symbols or the alphabet of the language being described, where N ∩ Σ = φ,
P - It is a finite set of "productions" or "rules",
S - It is a start variable or non-terminal symbol.
If, α and β are two strings over the alphabet N ∪  Σ. 
Then, the rules or productions are of the form α → β. The start variable S appears on the left side of the rule.
 L={anbncn | n≥0}
S→aBSc {Equal Number of a's, B's, c's}

S→ ε {Eliminate S} 

Ba→aB {Move a's to Right of B's} 

Bc→bc {Reduce B before first c to b}
 
Bb→bb {Reduce all remaining B's to b}
Jackson - Object Serialization

let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class. We'll create a student.json file which will have a json representation of Student object.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
      JacksonTester tester = new JacksonTester();
      try {
         Student student = new Student();
         student.setAge(10);
         student.setName("Mahesh");
         tester.writeJSON(student);

         Student student1 = tester.readJSON();
         System.out.println(student1);

      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
      ObjectMapper mapper = new ObjectMapper();	
      mapper.writeValue(new File("student.json"), student);
   }

   private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
      ObjectMapper mapper = new ObjectMapper();
      Student student = mapper.readValue(new File("student.json"), Student.class);
      return student;
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }	
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 10 ]
Python – Maximum and Minimum K elements in Tuple

16 Aug, 2021
Sometimes, while dealing with tuples, we can have problem in which we need to extract only extreme K elements, i.e maximum and minimum K elements in Tuple. This problem can have applications across domains such as web development and Data Science. Let’s discuss certain ways in which this problem can be solved. 
Input : test_tup = (3, 7, 1, 18, 9), k = 2 Output : (3, 1, 9, 18)Input : test_tup = (3, 7, 1), k=1 Output : (1, 3)  
Method #1 : Using sorted() + loop The combination of above functionalities can be used to solve this problem. In this, we perform the sort operation using sorted(), and the problem of extraction of max and min K elements using loop. 
Python3
# Python3 code to demonstrate working of# Maximum and Minimum K elements in Tuple# Using sorted() + loop # initializing tupletest_tup = (5, 20, 3, 7, 6, 8) # printing original tupleprint("The original tuple is : " + str(test_tup)) # initializing KK = 2 # Maximum and Minimum K elements in Tuple# Using sorted() + loopres = []test_tup = list(sorted(test_tup)) for idx, val in enumerate(test_tup):    if idx < K or idx >= len(test_tup) - K:        res.append(val)res = tuple(res) # printing resultprint("The extracted values : " + str(res))
The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)
 
 Method #2 : Using list slicing + sorted() The combination of above functions can be used to solve this problem. In this, we perform the task of max, min extraction using slicing rather than brute force loop logic. 
Python3
# Python3 code to demonstrate working of# Maximum and Minimum K elements in Tuple# Using slicing + sorted() # initializing tupletest_tup = (5, 20, 3, 7, 6, 8) # printing original tupleprint("The original tuple is : " + str(test_tup)) # initializing KK = 2 # Maximum and Minimum K elements in Tuple# Using slicing + sorted()test_tup = list(test_tup)temp = sorted(test_tup)res = tuple(temp[:K] + temp[-K:]) # printing resultprint("The extracted values : " + str(res))
The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)
 
dasaritejaswaroop8
Python tuple-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
How to Install PIP on Windows ?
*args and **kwargs in Python
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 | Convert string dictionary to dictionary
Python | Pandas Series.subtract()

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.subtract() function basically perform subtraction of series and other, element-wise (binary operator sub). It is equivalent to series - other, but with support to substitute a fill_value for missing data in one of the inputs.
Syntax: Series.subtract(other, level=None, fill_value=None, axis=0)
Parameter :other : Series or scalar valuefill_value : Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation.level : Broadcast across a level, matching Index values on the passed MultiIndex level
Returns : Series
Example #1 : Use Series.subtract() function to subtract a scalar from the given Series object element-wise.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None])  # Print the seriesprint(sr)
Output :
Now we will use Series.subtract() function to perform subtraction of the series with a scalar element-wise.
# subtract all the elements of the # series by 10sr.subtract(10)
Output :
As we can see in the output, Series.subtract() function has successfully subtracted all the elements of the given Series object by 10. Notice no subtraction has been performed on the missing values. Example #2 : Use Series.subtract() function to subtract a scalar from the given Series object element-wise. Also replace the missing values by 100.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None])  # Print the seriesprint(sr)
Output :
Now we will use Series.subtract() function to perform subtraction of the series with a scalar element-wise. We will replace the missing value in our series object by 100.
# subtract all the elements of the # series by 10 and also fill 100 at# the place of missing values.sr.subtract(10, fill_value = 100)
Output :
As we can see in the output, Series.subtract() function has successfully subtracted all the elements of the given Series object by 10. Notice how we have substituted 100 at the places of the missing values.
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Difference between 3-address instruction and 2-address instructions

20 Jun, 2020
Prerequisite – Instruction Formats1. Three-Address Instructions :Three-address instruction is a format of machine instruction. It has one opcode and three address fields. One address field is used for destination and two address fields for source.
Example –
X = (A + B) x (C + D) 
Solution:
ADD R1, A, B      R1 <- M[A] + M[B]
ADD R2, C, D      R2 <- M[C] + M[D]
MUL X, R1, R2     M[X] <- R1 x R2 
2. Two-Address Instructions :Two-address instruction is a format of machine instruction. It has one opcode and two address fields. One address field is common and can be used for either destination or source and other address field for source.
Example –
X = (A + B) x (C + D) 
Solution:
MOV R1, A      R1 <- M[A]
ADD R1, B      R1 <- R1 + M[B]
MOV R2, C      R2 <- M[C]
ADD R2, D      R2 <- R2 + D
MUL R1, R2     R1 <- R1 x R2
MOV X, R1      M[X] <- R1 
Difference between Three-Address Instruction and Two-Address Instruction :
Computer Organization & Architecture
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP 7 - Return Type Declarations

In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.
int
float
bool
string
interfaces
array
callable
<?php
   declare(strict_types = 1);
   function returnIntValue(int $value): int {
      return $value;
   }
   print(returnIntValue(5));
?>
It produces the following browser output −
5

<?php
   declare(strict_types = 1);
   function returnIntValue(int $value): int {
      return $value + 1.0;
   }
   print(returnIntValue(5));
?>
It produces the following browser output −
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...
\Bbbk - Tex Command

\Bbbk - Used to draw blackboard-bold lowercase k.
{ \Bbbk }
\Bbbk command draws draw blackboard-bold lowercase k.
Type Switches in GoLang

15 Oct, 2021
A switch is a multi-way branch statement used in place of multiple if-else statements but can also be used to find out the dynamic type of an interface variable. A type switch is a construct that performs multiple type assertions to determine the type of variable (rather than values) and runs the first matching switch case of the specified type. It is used when we do not know what the interface{} type could be.Example 1: 
C
// Golang program to illustrate the// concept of type switchespackage main  import (    "fmt")  // main functionfunc main() {          // an interface that has    // a string value    var value interface{} = "GeeksforGeeks"          // type switch to find    // out interface{} type    switch t := value.(type){              case int64:             // if type is an integer            fmt.Println("Type is an integer:", t)         case float64:             // if type is a floating point number            fmt.Println("Type is a float:", t)         case string:             // if type is a string            fmt.Println("Type is a string:", t)         case nil:             // if type is nil (zero-value)            fmt.Println("Type is nil.")         case bool:             // if type is a boolean            fmt.Println("Type is a bool:", t)         default:             // if type is other than above            fmt.Println("Type is unknown!")    }}
Output:  
Type is a string: GeeksforGeeks
The switch can have multiple value cases for different types and is used to select a common block of code for many similar cases.Note: Golang does not needs a ‘break’ keyword at the end of each case in the switch.Example 2: 
C
// Golang program to illustrate the// concept of type switch with// multiple value casespackage main  import (    "fmt")  // function which implements type// switch with multiple cases valuefunc find_type(value interface{}) {          // type switch to find    // out interface{} type    switch t := value.(type) {              case int, float64:             // type is an int or float            fmt.Println("Type is a number, either an int or a float:", t)                      case string, bool:             // type is a string or bool            fmt.Println("Type is either a string or a bool:", t)                      case *int, *bool:             // type is either an int pointer            // or a bool pointer            fmt.Println("Type is a pointer to an int or a bool:", t)                      default:             // type of the interface is unknown            fmt.Println("Type unknown!")    }}  // main functionfunc main() {          // an interface that has    // a string value    var v interface{} = "GeeksforGeeks"          // calling the find_type method    // to determine type of interface    find_type(v)          // re-assigning v with a    // float64 value    v = 34.55          find_type(v)}
Output: 
Type is either a string or a bool: GeeksforGeeks
Type is a number, either an int or a float: 34.55
 
surinderdawra388
Golang-Misc
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add filter to the background image using CSS ? - GeeksforGeeks

15 Oct, 2020
The purpose of this article is to learn how to add filters to an image using CSS. The CSS filter property is used to set the visual effect of an element. This property is mostly used in image content.
Syntax:
filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() | hue-rotate() | invert() | opacity() | saturate() | sepia() | url();
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        body {            background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/rk.png");            filter: brightness(90%);            filter: grayscale(70%);        }    </style></head>  <body>    <center>        <h2>            GeeksForGeeks        </h2>        <h2>            How to add a filter to a             background image using CSS?        </h2>    </center></body>  </html>    
Output:
Example 2:
HTML
<!DOCTYPE html><html>  <head>    <style>        .darkened-image {            filter: brightness(50%);            background-image: url("https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png");            height: 94px;            width: 120px;        }    </style></head>  <body>    <h1 style="color: green">        GeeksForGeeks    </h1>    <p>        The image below is the        normal image    </p>      <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png">      <p>        The image below is the        darkened image:    </p>      <div class="darkened-image"></div></body>  </html>                    
Output:
Supported browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
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 ?
LocalDate isEqual() method in Java with Examples - GeeksforGeeks

29 Nov, 2018
The isEqual() method of LocalDate class in Java checks if this date is equal to the specified date or not.
Syntax:
public boolean isEqual(ChronoLocalDate date2)

Parameter: This method accept a single mandatory parameter date2 the other date to compare to and not null.
Return Value: The function returns true if this date is equal to the specified date.
Below programs illustrate the isEqual() method of LocalDate in Java:
Program 1:
// Program to illustrate the isEqual() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the first date        LocalDate dt1 = LocalDate.parse("2018-11-27");        // Parses the second date        LocalDate dt2 = LocalDate.parse("2018-11-27");          // Checks        System.out.println(dt1.isEqual(dt2));    }}
true

Program 2:
// Program to illustrate the isEqual() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the first date        LocalDate dt1 = LocalDate.parse("2018-11-27");        // Parses the second date        LocalDate dt2 = LocalDate.parse("2015-11-27");          // Checks        System.out.println(dt1.isEqual(dt2));    }}
false

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#isEqual(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.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
How to convert NaN to 0 using JavaScript ? - GeeksforGeeks

15 Apr, 2020
NaN (Not a Number) is usually used to indicate an error condition for a function that should return a valid number but it can be converted to 0 using JavaScript. In this article, we will convert the NaN to 0.
Using isNaN() method: The isNan() method is used to check the given number is NaN or not. If isNaN() returns true for “number” then it assigns the value 0.
Example:<script>    number = NaN;    if (isNaN(number)) number = 0;    console.log(number);</script>
<script>    number = NaN;    if (isNaN(number)) number = 0;    console.log(number);</script>
Output:0
0
Using || Operator: If “number” is any falsey value, it will be assigned to 0.
Example:<script>    number = NaN;    number = number || 0;    console.log(number);</script>
<script>    number = NaN;    number = number || 0;    console.log(number);</script>
Output:0
0
Using ternary operator: Here number is checked via ternary operator, similar to 1, if NaN it converts to 0.
Example:<script>    number = NaN;    number = number ? number : 0;    console.log(number);</script>
<script>    number = NaN;    number = number ? number : 0;    console.log(number);</script>
Output:0
0
Note: While executing the code on our IDE or on your browser, check console (F12) to see the result.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Form validation using HTML and JavaScript
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript