code-rag-bench/online-tutorials huggingface dataset:
How to Enable Full-Screen Mode in Android?

16 Sep, 2021
In this article, we are going to learn how to enable full screen in Android Studio. Like if we are especially viewing an image then we want to view that on full screen. Here what we are going to implement is that we are basically hiding the navigation, status bar, and enabling the full-screen mode. We are going to discuss 4 different methods for doing this task.
Following is the code to hide the navigation and enabling full-screen mode.
// This is the code to hide the navigation and enabling full screen mode
View.SYSTEM_UI_FLAG_IMMERSIVE
                            // Set the content to appear under the system bars so that the
                            // content doesn't resize when the system bars hide and show.
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            // Hide the nav bar and status bar
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN);
Made these changes in your manifest.xml file
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
Made these changes in your styles.xml file
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->

    <item name="android:windowFullscreen">true</item>
</style>
Made these changes in your styles.xml file
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
nnr223442
Android-Misc
Android-Studio
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C program to find the areas of geometrical figures using switch case

Find the areas of rectangle, square, triangle, circle by using the switch case statement,
User need to enter base, height, side, radius, breadth and length at runtime to calculate the areas of all geometrical figures.
The solution to find the areas of rectangle, square, triangle, circle by using the switch case statement is explained below −
Formulae
The formulae for finding the areas of the respective geometrical figures are as follows −
Area of rectangle = breadth *length;
Area of square = side * side;
Area of circle = 3.142*radius*radius;
Area of triangle = 0.5 *base*height;
Following is the C program to find the areas of rectangle, square, triangle, circle by using the switch case statement −
 Live Demo
#include <stdio.h>
void main(){
   int fig_code;
   float side, base, length, breadth, height, area, radius;
   printf("-------------------------\n");
   printf(" 1 --> Circle\n");
   printf(" 2 --> Rectangle\n");
   printf(" 3 --> Triangle\n");
   printf(" 4 --> Square\n");
   printf("-------------------------\n");
   printf("Enter the Figure code\n");
   scanf("%d", &fig_code);
   switch(fig_code){
      case 1:
         printf(" Enter the radius\n");
         scanf("%f",&radius);
         area=3.142*radius*radius;
         printf("Area of a circle=%f\n", area);
         break;
      case 2:
         printf(" Enter the breadth and length\n");
         scanf("%f %f",&breadth, &length);
         area=breadth *length;
         printf("Area of a Rectangle=%f\n", area);
         break;
      case 3:
         printf(" Enter the base and height\n");
         scanf("%f %f", &base, &height);
         area=0.5 *base*height;
         printf("Area of a Triangle=%f\n", area);
         break;
      case 4:
         printf(" Enter the side\n");
         scanf("%f", &side);
         area=side * side;
         printf("Area of a Square=%f\n", area);
         break;
      default:
      printf(" Error in figure code\n");
      break;
   }
}
When the above program is executed, it produces the following result −
Run 1:
-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
3
Enter the base and height
4
7

Area of a Triangle=14.000000

Run 2:
-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
1
Enter the radius
8
Area of a circle=201.087997
How many ways can get the instance of a Class class in Java?

You can create an object of the class named Class in two ways −
Using new keyword as −
Class obj = new Class();
Using the forName() method of the class named Class.
Class obj = Class.forName("DemoTest");
How do I calculate the date six months from the current date using the datetime Python module?

You can use the timedelta function from datetime module to achieve this. For example,
>>> import datetime
>>> today = datetime.date.today()
>>> print today
2017-09-12
>>> six_months_later = today + datetime.timedelta(30*6)
>>> print six_months_later
2018-03-11
iOS - File Handling

File handling cannot be explained visually with the application and hence the key methods that are used for handling files are explained below. Note that the application bundle only has read permission and we won’t be able to modify the files. You can anyway modify the documents directory of your application.
The methods used for accessing and manipulating the files are discussed below. Here we have to replace FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.
NSFileManager *fileManager = [NSFileManager defaultManager];

//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];

if ([fileManager fileExistsAtPath:@""]==YES) {
   NSLog(@"File exists");
}
if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
   NSLog(@"Same content");
}
if ([fileManager isWritableFileAtPath:@"FilePath"]) {
   NSLog(@"isWritable");
}

if ([fileManager isReadableFileAtPath:@"FilePath"]) {
   NSLog(@"isReadable");
}

if ( [fileManager isExecutableFileAtPath:@"FilePath"]) {
   NSLog(@"is Executable");
}
if([fileManager moveItemAtPath:@"FilePath1" 
   toPath:@"FilePath2" error:NULL]) {
   NSLog(@"Moved successfully");
}
if ([fileManager copyItemAtPath:@"FilePath1" 
   toPath:@"FilePath2"  error:NULL]) {
   NSLog(@"Copied successfully");
}
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
   NSLog(@"Removed successfully");
}
NSData *data = [fileManager contentsAtPath:@"Path"];
[fileManager createFileAtPath:@"" contents:data attributes:nil];

    23 Lectures 
     1.5 hours 

 Ashish Sharma

    9 Lectures 
     1 hours 

 Abhilash Nelson

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    10 Lectures 
     1 hours 

 Abhilash Nelson

    69 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
PyQt5 - QPixmap Class

QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button.
Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible.
The types of image files that can be read into a QPixmap object are as follows −
Following methods are useful in handling QPixmap object −
copy()
Copies pixmap data from a QRect object
fromImage()
Converts QImage object into QPixmap
grabWidget()
Creates a pixmap from the given widget
grabWindow()
Create pixmap of data in a window
Load()
Loads an image file as pixmap
save()
Saves the QPixmap object as a file
toImage
Converts a QPixmap to QImage
The most common use of QPixmap is to display image on a label/button.
The following example shows an image displayed on a QLabel by using the setPixmap() method.
The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   win = QWidget()
   l1 = QLabel()
   l1.setPixmap(QPixmap("python.png"))

   vbox = QVBoxLayout()
   vbox.addWidget(l1)
   win.setLayout(vbox)
   win.setWindowTitle("QPixmap Demo")
   win.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Koa.js - Cookies

Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps keep track of the users actions. There are numerous uses of HTTP Cookies.
Session management
Personalization(Recommendation systems)
User tracking
To use cookies with Koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie, let’s define a new route in our Koa app.
var koa = require('koa');
var router = require('koa-router');
var app = koa();

_.get('/', setACookie);

function *setACookie() {
   this.cookies.set('foo', 'bar', {httpOnly: false});
}

var _ = router();

app.use(_.routes());
app.listen(3000);
To check if the cookie is set or not, just go to your browser, fire up the console, and enter −
console.log(document.cookie);

This will produce the following output (you may have more cookies set maybe due to extensions in your browser).
"foo = bar"

Here is an example of the above.
The browser also sends back cookies every time it queries the server. To view a cookie on your server, on the server console in a route, add the following code to that route.
console.log('Cookies: foo = ', this.cookies.get('foo'));

Next time you send a request to this route, you'll get the following output.
Cookies: foo = bar

You can add cookies that expire. To add a cookie that expires, just pass an object with the property 'expires' set to the time when you want it to expire. For example,
var koa = require('koa');
var router = require('koa-router');
var app = koa();

_.get('/', setACookie);

function *setACookie(){
   //Expires after 360000 ms from the time it is set.
	this.cookies.set('name', 'value', { 
      httpOnly: false, expires: 360000 + Date.now() });
}

var _ = router();

app.use(_.routes());
app.listen(3000);
To unset a cookie, simply set the cookie to an empty string. For example, if you need to clear a cookie named foo, use the following code.
var koa = require('koa');
var router = require('koa-router');
var app = koa();

_.get('/', setACookie);

function *setACookie(){
   //Expires after 360000 ms from the time it is set.
   this.cookies.set('name', '');
}

var _ = router();

app.use(_.routes());
app.listen(3000);
This will unset the said cookie. Note that you should leave the HttpOnly option to be true when not using the cookie in the client side code.
 Print
 Add Notes
 Bookmark this page
How to convert XML to Json and Json back to XML using Newtonsoft.json?

Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter.
Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the two
The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text.
The second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into an XmlNode.
static void Main(string[] args) {
   string xml = @"Alanhttp://www.google1.com Admin1";
   XmlDocument doc = new XmlDocument();
   doc.LoadXml(xml);
   string json = JsonConvert.SerializeXmlNode(doc);
   Console.WriteLine(json);
   Console.ReadLine();
}
{"person":{"@id":"1","name":"Alan","url":"http://www.google1.com","role":"Admin1"}}
static void Main(string[] args) {
   string json = @"{
      '?xml': {
         '@version': '1.0',
         '@standalone': 'no'
      },
      'root': {
         'person': [
            {
            '@id': '1',
            'name': 'Alan',
            'url': 'http://www.google1.com'
            },
            {
            '@id': '2',
            'name': 'Louis',
            'url': 'http://www.yahoo1.com'
            }
         ]
      }
   }";
   XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
   Console.WriteLine(json);
   Console.ReadLine();
}
'?xml': {
   '@version': '1.0',
   '@standalone': 'no'
},
'root': {
   'person': [
      {
      '@id': '1',
      'name': 'Alan',
      'url': 'http://www.google1.com'
      },
      {
      '@id': '2',
      'name': 'Louis',
      'url': 'http://www.yahoo1.com'
      }
   ]
}
MariaDB - Indexes & Statistics Tables

Indexes are tools for accelerating record retrieval. An index spawns an entry for each value within an indexed column.
There are four types of indexes −
Primary (one record represents all records)
Primary (one record represents all records)
Unique (one record represents multiple records)
Unique (one record represents multiple records)
Plain
Plain
Full-Text (permits many options in text searches).
Full-Text (permits many options in text searches).
The terms “key” and “index” are identical in this usage.
Indexes associate with one or more columns, and support rapid searches and efficient record organization. When creating an index, consider which columns are frequently used in your queries. Then create one or multiple indexes on them. In addition, view indexes as essentially tables of primary keys.
Though indexes accelerate searches or SELECT statements, they make insertions and updates drag due to performing the operations on both the tables and the indexes.
You can create an index through a CREATE TABLE...INDEX statement or a CREATE INDEX statement. The best option supporting readability, maintenance, and best practices is CREATE INDEX.
Review the general syntax of Index given below −
CREATE [UNIQUE or FULLTEXT or...] INDEX index_name ON table_name column;

Review an example of its use −
CREATE UNIQUE INDEX top_sellers ON products_tbl product;

You can drop an index with DROP INDEX or ALTER TABLE...DROP. The best option supporting readability, maintenance, and best practices is DROP INDEX.
Review the general syntax of Drop Index given below −
DROP INDEX index_name ON table_name;

Review an example of its use −
DROP INDEX top_sellers ON product_tbl;

Rename an index with the ALTER TABLE statement. Review its general syntax given below −
ALTER TABLE table_name DROP INDEX index_name, ADD INDEX new_index_name;

Review an example of its use −
ALTER TABLE products_tbl DROP INDEX top_sellers, ADD INDEX top_2016sellers;

You will need to examine and track all indexes. Use SHOW INDEX to list all existing indexes associated with a given table. You can set the format of the displayed content by using an option such as “\G”, which specifies a vertical format.
Review the following example −
mysql > SHOW INDEX FROM products_tbl\G

Indexes are used heavily to optimize queries given the faster access to records, and the statistics provided. However, many users find index maintenance cumbersome. MariaDB 10.0 made storage engine independent statistics tables available, which calculate data statistics for every table in every storage engine, and even statistics for columns that are not indexed.
 Print
 Add Notes
 Bookmark this page
C# program to count occurrences of a word in string

Set the string first −
string str = "Hello World! Hello!";
Now check the string for the occurrences of a word “Hello’ and loop through −
while ((a = str1.IndexOf(pattern, a)) != -1) {
   a += pattern.Length;
   count++;
}
You can try to run the following code to count occurrences of a word in a string.
Live Demo
using System;
class Program {
   static void Main() {
      string str = "Hello World! Hello!";
      Console.WriteLine("Occurrence:"+Check.CheckOccurrences(str, "Hello"));
   }
}
public static class Check {
   public static int CheckOccurrences(string str1, string pattern) {
      int count = 0;
      int a = 0;
      while ((a = str1.IndexOf(pattern, a)) != -1) {
         a += pattern.Length;
         count++;
      }
      return count;
   }
}
Occurrence:2
C++ Program to Check if a Point d lies inside or outside a circle defined by Points a, b, c in a Plane

We shall consider a C++ Program to check if a point d lies inside or outside a circle defined by points a, b, c in a plane by using equation
s = (x-xt)^2 + (y-yt)^2 – r*r
Where, For any point t (xt, yt) on the plane, its position with respect to the circle defined by 3 points (x1, y1), (x2, y2), (x3, y3).
for s < 0, t lies inside the circle.
For s >0, t lies outside the circle.
For s = 0, t lies on the circle.
Begin
   Take the points at input.
   Declare constant L = 0 and H = 20
   Declare the variables of the equation.
   For generating equation, generate random numbers for coefficient of x and y by using rand at every time of compilation.
   Calculate the center of the circle.
   Calculate the radius of the circle.
   Calculate s.
   if s < 0, print point lies inside the circle.
      else if s >0, print point lies outside the circle.
         else if s = 0, print point lies on the circle.
End
 Live Demo
#include<time.h>
#include<stdlib.h>
#include<iostream>
#include<math.h>

using namespace std;
const int L= 0;
const int H = 20;

int main(int argc, char **argv) {
   time_t s;
   time(&s);
   srand((unsigned int) s);

   double x1, x2, y1, y2, x3, y3;
   double a1, a2, c1, c2, r;
   x1 = rand() % (H - L+ 1) + L;
   x2 = rand() % (H - L + 1) + L;
   x3 = rand() % (H- L + 1) + L;
   y1 = rand() % (H- L + 1) + L;
   y2 = rand() % (H- L+ 1) + L;
   y3 = rand() % (H- L + 1) + L;
   a1 = (y1 - y2) / (x1 - x2);
   a2 = (y3 - y2) / (x3 - x2);

   c1 = ((a1 * a2 * (y3 - y1)) + (a1 * (x2 + x3)) - (a2 * (x1 + x2))) / (2 * (a1 - a2));//calculate center of circle
   c2 = ((((x1 + x2) / 2) - c1) / (-1 * a1)) + ((y1 + y2) / 2);//calculate center of circle
   r = sqrt(((x3 - c1) * (x3 - c1)) + ((y3 - c2) * (y3 - c2)));//calcultate radius
   cout << "The points on the circle are: (" << x1 << ", " << y1 << "), (" << x2 << ", " << y2 << "), (" << x3 << ", " << y3 << ")";
   cout << "\nThe center of the circle is (" << c1 << ", " << c2 << ") and radius is " << r;

   cout << "\nEnter the point : ";
   int u, v;
   cin >>u;
   cin >>v;

   double s1 = ((u - c1) * (u - c1)) + ((v - c2) * (v - c1)) - (r * r);
   if (s1 < 0)
      cout << "\nThe point lies inside the circle";
   else if (s1 >0)
      cout << "\nThe point lies outside the circle";
   else
      cout << "\nThe point lies on the circle";
      return 0;
}
The points on the circle are: (8, 4), (9, 17), (5, 9)
The center of the circle is (12.6364, 10.8182) and radius is 7.84983
Enter the point : 7
6

The point lies outside the circle
How to shift a graph along the X-axis in matplotlib?

To shift a graph along the X-axis in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Plot the x and y data points for the original curve.
Plot the shifted graph, in the range of (1, 1+len(y)) with y data points.
Place a legend on the figure.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# x and y data points
x = np.linspace(-5, 5, 100)
y = np.sin(x)

# Original graph and shifted graph
plt.plot(x, y, label='Original Graph')
plt.plot(range(1, 1+len(y)), y, label='Shifted Graph')

# Place a legend
plt.legend(loc='upper right')

plt.show()
It will produce the following output
MVC Framework - Bundling

Bundling and Minification are two performance improvement techniques that improves the request load time of the application. Most of the current major browsers limit the number of simultaneous connections per hostname to six. It means that at a time, all the additional requests will be queued by the browser.
To enable bundling and minification in your MVC application, open the Web.config file inside your solution. In this file, search for compilation settings under system.web −
<system.web>
   <compilation debug = "true" />
</system.web>
By default, you will see the debug parameter set to true, which means that bundling and minification is disabled. Set this parameter to false.
To improve the performance of the application, ASP.NET MVC provides inbuilt feature to bundle multiple files into a single, file which in turn improves the page load performance because of fewer HTTP requests.
Bundling is a simple logical group of files that could be referenced by unique name and loaded with a single HTTP request.
By default, the MVC application's BundleConfig (located inside App_Start folder) comes with the following code −
public static void RegisterBundles(BundleCollection bundles) { 
   
   // Following is the sample code to bundle all the css files in the project         
   
   // The code to bundle other javascript files will also be similar to this 
  
   bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( 
      "~/Content/themes/base/jquery.ui.core.css", 
      "~/Content/themes/base/jquery.ui.tabs.css", 
      "~/Content/themes/base/jquery.ui.datepicker.css",  
      "~/Content/themes/base/jquery.ui.progressbar.css", 
      "~/Content/themes/base/jquery.ui.theme.css")); 
}
The above code basically bundles all the CSS files present in Content/themes/base folder into a single file.
Minification is another such performance improvement technique in which it optimizes the javascript, css code by shortening the variable names, removing unnecessary white spaces, line breaks, comments, etc. This in turn reduces the file size and helps the application to load faster.
For using this option, you will have to first install the Web Essentials Extension in your Visual Studio. After that, when you will right-click on any css or javascript file, it will show you the option to create a minified version of that file.
Thus, if you have a css file named Site.css, it will create its minified version as Site.min.css.
Now when the next time your application will run in the browser, it will bundle and minify all the css and js files, hence improving the application performance.

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    42 Lectures 
     18 hours 

 SHIVPRASAD KOIRALA

    57 Lectures 
     3.5 hours 

 University Code

    55 Lectures 
     4.5 hours 

 University Code

    40 Lectures 
     2.5 hours 

 University Code

    140 Lectures 
     9 hours 

 Bhrugen Patel
 Print
 Add Notes
 Bookmark this page
Nested interface in Java

We can declare an interface in another interface or class. Such an interface is termed as a nested interface.
The following are the rules governing a nested interface.
A nested interface declared within an interface must be public.
A nested interface declared within a class can have any access modifier.
A nested interface is by default static.
Following is an example of a nested interface.
Live Demo
class Animal {
   interface Activity {
      void move();
   }
}
class Dog implements Animal.Activity {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}
public class Tester {
   public static void main(String args[]) {
      Dog dog = new Dog();
      dog.move();
   }
}
Dogs can walk and run
Commons Collections - Safe Empty Checks

CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API.
isNotEmpty() method of CollectionUtils can be used to check if a list is not empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.isNotEmpty() method −
public static boolean isNotEmpty(Collection<?> coll)

coll − The collection to check, may be null.
coll − The collection to check, may be null.
True if non-null and non-empty.
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isNotEmpty() method. We'll check a list is empty or not.
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

public class CollectionUtilsTester {
   public static void main(String[] args) {
      List<String> list = getList();
      System.out.println("Non-Empty List Check: " + checkNotEmpty1(list));
      System.out.println("Non-Empty List Check: " + checkNotEmpty1(list));
   }
   static List<String> getList() {
      return null;
   }
   static boolean checkNotEmpty1(List<String> list) {
      return !(list == null || list.isEmpty());
   }
   static boolean checkNotEmpty2(List<String> list) {
      return CollectionUtils.isNotEmpty(list);
   }
}
The output is given below −
Non-Empty List Check: false
Non-Empty List Check: false

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.isEmpty() method −
public static boolean isEmpty(Collection<?> coll)

coll − The collection to check, may be null.
coll − The collection to check, may be null.
True if empty or null.
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isEmpty() method. We'll check a list is empty or not.
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

public class CollectionUtilsTester {
   public static void main(String[] args) {
      List<String> list = getList();
      System.out.println("Empty List Check: " + checkEmpty1(list));
      System.out.println("Empty List Check: " + checkEmpty1(list));
   }
   static List<String> getList() {
      return null;
   }
   static boolean checkEmpty1(List<String> list) {
      return (list == null || list.isEmpty());
   }
   static boolean checkEmpty2(List<String> list) {
      return CollectionUtils.isEmpty(list);
   }
}
Given below is the output of the code −
Empty List Check: true
Empty List Check: true

 Print
 Add Notes
 Bookmark this page
How to Create a Pivot table with multiple indexes from an excel sheet using Pandas in Python? - GeeksforGeeks

28 Jul, 2020
 The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. It can be created using the pivot_table() method.
Syntax: pandas.pivot_table(data, index=None)
Parameters:
data : DataFrameindex: column, Grouper, array, or list of the previous
index: It is the feature that allows you to group your data. 
Returns: DataFrame
Note: We can filter the table further by adding the optional parameters. 
Example 1: Link to the CSV File: CSV FILE We can have a look at the data by running the following program: 
Python3
# importing pandas as pd import pandas as pd  # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv')  # Print the dataframe df
Output:
We know that the index is the feature that allows us to group our data and specifying multiple columns as the indices in pivot function increases the level of details and grouping the data. Keeping a single index in the table:  
Python3
# importing pandas as pd import pandas as pd  # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv')  # Print the resultant tableprint(pd.pivot_table(df,index=["Country"]))
Output:
As we can see that the grouping is done country wise and the numerical data is printed as the average of all the values with regard to the specified index.Now, Keeping multiple indices in the table:  
Python3
# importing pandas as pd import pandas as pd  # Create the dataframe df=pd.read_csv('GeeksForGeeks.csv')  # Print the resultant tableprint(pd.pivot_table(df,index=["Country","Salary"]))
Output:
Example 2: Link to the CSV File: CSV FILE  
Python3
# importing pandas as pd import pandas as pd  # Create the dataframe df=pd.read_csv('GeeksForGeeks_1.csv')  # Print the dataframe df
Output:
Keeping the number of centuries scored by players and their names as indices, we get:  
Python3
# importing pandas as pd import pandas as pd  # Create the dataframe df=pd.read_csv('dataset/new_players.csv')  # Print the resultant tableprint(pd.pivot_table(df,index=["century","name"]))
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
C# Program to Implement an Interface in a Structure - GeeksforGeeks

15 Nov, 2021
Structure is a value type and a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. We can create a structure by using struct keyword. A structure can also hold constructors, constants, fields, methods, properties, indexers, and events, etc. 
Syntax:
public struct 
{
    // Fields
    // Methods
}
Interface is like a class, it can also have methods, properties, events, and indexers as its members. But interfaces can only have the declaration of the members. The implementation of the interface’s members will be given by the class that implements the interface implicitly or explicitly. Or we can say that it is the blueprint of the class.
Syntax:
interface interface_name
{
    // Method Declaration in interface
}
Now given that two interfaces, now our task is to implement both interfaces in a structure.
Approach:
Create two interfaces named interface1 and interface2 with method declaration in it.
Create a structure that implements these interfaces.
struct GFG : interface1, interface2
{
    // Method definition for interface method
    // Method definition for interface method
}
Write the method definitions for both interfaces in the GFG struct.
Inside the main method, create the two objects named M1 and M2.
Call the methods of interface1 and interface2 using M1 and M2 object and display the output.
Example:
C#
// C# program to illustrate how to implement// interface in a structureusing System; // Interface 1interface interface1{         // Declaration of Method    void MyMethod1();} // Interface 2interface interface2{         // Declaration of Method    void MyMethod2();} // Structure which implement interface1// and interface2struct GFG : interface1, interface2{         // Method definitions of interface 1    void interface1.MyMethod1()    {        Console.WriteLine("interface1.Method() is called");    }         // Method definitions of interface 2    void interface2.MyMethod2()    {        Console.WriteLine("interface2.Method() is called");    }} class Geeks{ // Driver code   public static void Main(String[] args){         // Declare interfaces    interface1 M1;    interface2 M2;         // Create objects    M1 = new GFG();    M2 = new GFG();         M1.MyMethod1();    M2.MyMethod2();}}
Output:
interface1.Method() is called
interface2.Method() is called
sweetyty
CSharp-Interfaces
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
\xrightarrow - Tex Command

\xrightarrow - Used to create xrightarrow symbol.
{ \xrightarrow[optionalArgument] #1 }
\xrightarrow command draws xrightarrow symbol.

\xrightarrow a

→a


\xrightarrow ab

→ab


\xrightarrow{ab}

→ab


\xrightarrow[f]{\text{see (1)}}

→fsee (1)



\xrightarrow a

→a


\xrightarrow a
\xrightarrow ab

→ab


\xrightarrow ab
\xrightarrow{ab}

→ab


\xrightarrow{ab}
\xrightarrow[f]{\text{see (1)}}

→fsee (1)


\xrightarrow[f]{\text{see (1)}}

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
How to call C / C++ from Python? - GeeksforGeeks

29 Jul, 2020
In order to take advantage of the strength of both languages, developers use Python bindings which allows them to call C/C++ libraries from python.
Now, the question arises that why there is a need for doing this?
As we know that, C has faster execution speed and to overcome the limitation of Global Interpreter Lock(GIL) in python, python bindings are helpful.We have a large, stable and tested library in C/C++, which will be advantageous to use.For performing large scale testing of the systems using Python test tools.
As we know that, C has faster execution speed and to overcome the limitation of Global Interpreter Lock(GIL) in python, python bindings are helpful.
We have a large, stable and tested library in C/C++, which will be advantageous to use.
For performing large scale testing of the systems using Python test tools.
Let’s see the C code which we want to execute with Python :
C++
#include <iostream>class Geek{    public:        void myFunction(){            std::cout << "Hello Geek!!!" << std::endl;        }};int main(){    // Creating an object    Geek t;       // Calling function    t.myFunction();         return 0;}
We have to provide those cpp declarations as extern “C” because ctypes can only interact with C functions.
C++
extern "C" {    Geek* Geek_new(){ return new Geek(); }    void Geek_myFunction(Geek* geek){ geek -> myFunction(); }}
Now, compile this code to the shared library :
Finally, write the python wrapper:
Python3
# import the modulefrom ctypes import cdll  # load the librarylib = cdll.LoadLibrary('./libgeek.so')  # create a Geek classclass Geek(object):      # constructor    def __init__(self):          # attribute        self.obj = lib.Geek_new()      # define method    def myFunction(self):        lib.Geek_myFunction(self.obj)  # create a Geek class objectf = Geek()  # object method callingf.myFunction()
Output :
Hello Geek!!!

python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Difference between float and double in C/C++ - GeeksforGeeks

26 Apr, 2018
For representing floating point numbers, we use float, double and long double.
What’s the difference ?
double has 2x more precision then float.
float is a 32 bit IEEE 754 single precision Floating Point Number1 bit for the sign, (8 bits for the exponent, and 23* for the value), i.e. float has 7 decimal digits of precision.
double is a 64 bit IEEE 754 double precision Floating Point Number (1 bit for the sign, 11 bits for the exponent, and 52* bits for the value), i.e. double has 15 decimal digits of precision.
Let’s take a example(example taken from here) :For a quadratic equation x2 – 4.0000000 x + 3.9999999 = 0, the exact roots to 10 significant digits are, r1 = 2.000316228 and r2 = 1.999683772
// C program to demonstrate // double and float precision values  #include <stdio.h>#include <math.h>  // utility function which calculate roots of // quadratic equation using double valuesvoid double_solve(double a, double b, double c){    double d = b*b - 4.0*a*c;    double sd = sqrt(d);    double r1 = (-b + sd) / (2.0*a);    double r2 = (-b - sd) / (2.0*a);    printf("%.5f\t%.5f\n", r1, r2);}  // utility function which calculate roots of // quadratic equation using float valuesvoid float_solve(float a, float b, float c){    float d = b*b - 4.0f*a*c;    float sd = sqrtf(d);    float r1 = (-b + sd) / (2.0f*a);    float r2 = (-b - sd) / (2.0f*a);    printf("%.5f\t%.5f\n", r1, r2);}     // driver programint main(){    float fa = 1.0f;    float fb = -4.0000000f;    float fc = 3.9999999f;    double da = 1.0;    double db = -4.0000000;    double dc = 3.9999999;      printf("roots of equation x2 - 4.0000000 x + 3.9999999 = 0 are : \n");    printf("for float values: \n");    float_solve(fa, fb, fc);      printf("for double values: \n");    double_solve(da, db, dc);    return 0;}  
Output:
roots of equation x2 - 4.0000000 x + 3.9999999 = 0 are : 
for float values: 
2.00000    2.00000
for double values: 
2.00032    1.99968

This article is contributed by Mandeep Singh. 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.
msdeep14
cpp-data-types
C Language
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Tryit Editor v3.7

Tryit: HTML title attribute
C program to compare if the two matrices are equal or not

The user has to enter the order of two matrices and elements of two matrices. Then, these two matrix are compared.
If both matrix elements and size are equal, then it displays that the two matrices are equal.
If size of matrix is equal but the elements are not equal, then it displays that the matrix can be compared but is not equal.
If the size and elements are not matched, then it displays that the matrices cannot be compared.
Following is the C program to compare if the two matrices are equal or not −
#include <stdio.h>
#include <conio.h>
main(){
   int A[10][10], B[10][10];
   int i, j, R1, C1, R2, C2, flag =1;
   printf("Enter the order of the matrix A\n");
   scanf("%d %d", &R1, &C1);
   printf("Enter the order of the matrix B\n");
   scanf("%d %d", &R2,&C2);
   printf("Enter the elements of matrix A\n");
   for(i=0; i<R1; i++){
      for(j=0; j<C1; j++){
         scanf("%d",&A[i][j]);
      }
   }
   printf("Enter the elements of matrix B\n");
   for(i=0; i<R2; i++){
      for(j=0; j<C2; j++){
         scanf("%d",&B[i][j]);
      }
   }
   printf("MATRIX A is\n");
   for(i=0; i<R1; i++){
      for(j=0; j<C1; j++){
         printf("%3d",A[i][j]);
      }
      printf("\n");
   }
   printf("MATRIX B is\n");
   for(i=0; i<R2; i++){
      for(j=0; j<C2; j++){
         printf("%3d",B[i][j]);
      }
      printf("\n");
   }
   /* Comparing two matrices for equality */
   if(R1 == R2 && C1 == C2){
      printf("Matrices can be compared\n");
      for(i=0; i<R1; i++){
         for(j=0; j<C2; j++){
            if(A[i][j] != B[i][j]){
               flag = 0;
               break;
            }
         }
      }
   }
   else{
      printf(" Cannot be compared\n");
      exit(1);
   }
   if(flag == 1 )
      printf("Two matrices are equal\n");
   else
   printf("But,two matrices are not equal\n");
}
When the above program is executed, it produces the following result −
Run 1:
Enter the order of the matrix A
2 2
Enter the order of the matrix B
2 2
Enter the elements of matrix A
1
2
3
4
Enter the elements of matrix B
1
2
3
4
MATRIX A is
   1 2
   3 4
MATRIX B is
   1 2
   3 4
Matrices can be compared
Two matrices are equal

Run 2:
Enter the order of the matrix A
2 2
Enter the order of the matrix B
2 2
Enter the elements of matrix A
1
2
3
4
Enter the elements of matrix B
5
6
7
8
MATRIX A is
   1 2
   3 4
MATRIX B is
   5 6
   7 8
Matrices can be compared
But,two matrices are not equal
Check if two lists are identical in Python

In python data analysis, we may come across situation when we need to compare two lists and find out if they are identical meaning having same elements or not.
 Live Demo
listA = ['Mon','Tue','Wed','Thu']
listB = ['Mon','Wed','Tue','Thu']
# Given lists
print("Given listA: ",listA)
print("Given listB: ",listB)
# Sort the lists
listA.sort()
listB.sort()

# Check for equality
if listA == listB:
   print("Lists are identical")
else:
   print("Lists are not identical")
Running the above code gives us the following result −
Given listA: ['Mon', 'Tue', 'Wed', 'Thu']
Given listB: ['Mon', 'Wed', 'Tue', 'Thu']
Lists are identical
The Counter function from collections module can help us in finding the number of occurrences of each item in the list. In the below example we also take two duplicate elements. If the frequency of each element is equal in both the lists, we consider the lists to be identical.
 Live Demo
import collections
listA = ['Mon','Tue','Wed','Tue']
listB = ['Mon','Wed','Tue','Tue']
# Given lists
print("Given listA: ",listA)
print("Given listB: ",listB)
# Check for equality
if collections.Counter(listA) == collections.Counter(listB):
   print("Lists are identical")
else:
   print("Lists are not identical")

# Checking again
listB = ['Mon','Wed','Wed','Tue']
print("Given listB: ",listB)

# Check for equality
if collections.Counter(listA) == collections.Counter(listB):
   print("Lists are identical")
else:
   print("Lists are not identical")
Running the above code gives us the following result −
Given listA: ['Mon', 'Tue', 'Wed', 'Tue']
Given listB: ['Mon', 'Wed', 'Tue', 'Tue']
Lists are identical
Given listB: ['Mon', 'Wed', 'Wed', 'Tue']
Lists are not identical
How can we print multiple blank lines in python?

We can print multiple blank lines in python by using the \n character the number of times we need a blank line. For example, If you need 5 blank lines, you can use −
Python 2.x:
print "\n\n\n\n\n"

Python 3.x:
print("\n\n\n\n\n")
You can use features like repetition operator in python to make this easier. For example,
Python 2.x:
print "\n" * 5

Python 3.x:
print("\n" * 5)
All of these commands will print 5 blank lines on the STDOUT.
C++ Program to Store and Display Information Using Structure

A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword.
An example of a structure is as follows −
struct employee {
   int empID;
   char name[50];
   float salary;
};
A program that stores and displays information using structure is given as follows.
 Live Demo
#include <iostream>
using namespace std;
struct employee {
   int empID;
   char name[50];
   int salary;
   char department[50];
};
int main() {
   struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } ,    { 3 , "John" , 15000 , "Technical" } };
   cout<<"The employee information is given as follows:"<<endl;
   cout<<endl;
   for(int i=0; i<3;i++) {
      cout<<"Employee ID: "<<emp[i].empID<<endl;
      cout<<"Name: "<<emp[i].name<<endl;
      cout<<"Salary: "<<emp[i].salary<<endl;
      cout<<"Department: "<<emp[i].department<<endl;
      cout<<endl;
   }
   return 0;
}
The employee information is given as follows:
Employee ID: 1
Name: Harry
Salary: 20000
Department: Finance

Employee ID: 2
Name: Sally
Salary: 50000
Department: HR

Employee ID: 3
Name: John
Salary: 15000
Department: Technical
In the above program, the structure is defined before the main() function. The structure contains the employee ID, name, salary and department of an employee. This is demonstrated in the following code snippet.
struct employee {
   int empID;
   char name[50];
   int salary;
   char department[50];
};
In the main() function, an object array of type struct employee is defined. This contains the employee ID, name, salary and department values. This is shown as follows.
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } };
The structure values are displayed using a for loop. This is shown in the following manner.
cout<<"The employee information is given as follows:"<<endl;
cout<<endl;
for(int i=0; i<3;i++) {
   cout<<"Employee ID: "<<emp[i].empID<<endl;
   cout<<"Name: "<<emp[i].name<<endl;
   cout<<"Salary: "<<emp[i].salary<<endl;
   cout<<"Department: "<<emp[i].department<<endl;
   cout<<endl;
}
Consecutive elements sum array in JavaScript

We are required to write a JavaScript function that takes in an array of Numbers and returns a
new array with elements as the sum of two consecutive elements from the original array.
For example, if the input array is −
const arr1 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9];
Then the output should be −
const output = [2, 9, 9, 13, 17]
The code for this will be −
const arr11 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9];
const consecutiveSum = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i += 2){
      res.push(arr[i] + (arr[i+1] || 0));
   };
   return res;
};
console.log(conseutiveSum(arr1));
The output in the console −
[ 2, 9, 9, 13, 17 ]
Java Generics - No instanceOf

Because compiler uses type erasure, the runtime does not keep track of type parameters, so at runtime difference between Box<Integer> and Box<String> cannot be verified using instanceOf operator.
Box<Integer> integerBox = new Box<Integer>();

//Compiler Error:
//Cannot perform instanceof check against 
//parameterized type Box<Integer>. 
//Use the form Box<?> instead since further 
//generic type information will be erased at runtime
if(integerBox instanceof Box<Integer>) { }

    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Find all the patterns of “1(0+)1” in a given string using Python Regex

In this tutorial, we are going to write a program which finds all the occurrences of the 1(0+1) in a string using the regexes. We have a re module in Python which helps us to work with the regular expressions.
Let's see one sample case.
Input:
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output:
Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']
Follow the below steps to write the code for the program.
1. Import the re module.
2. Initialise a string.
3. Create a regex object using regular expression which matches the pattern using the re.compile(). Remember to pass a raw string to the function instead of the usual string.
4. Now, match all the occurrence of the pattern using regex object from the above step and regex_object.findall() method.
5. The above steps return a match object and print the matched patterns using match_object.group() method.
Let's see the code.
 Live Demo
# importing the re module
import re
# initializing the string
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
# creating a regex object for our patter
regex = re.compile(r"\d\(\d\+\)\d") # this regex object will find all the patter ns which are 1(0+)1
# storing all the matches patterns in a variable using regex.findall() method
result = regex.findall(string) # result is a match object
# printing the frequency of patterns
print(f"Total number of pattern maches are {len(result)}")
print()
# printing the matches from the string using result.group() method
print(result)
If you run the above code, you will get the following output.
Total number of pattern maches are 3
['1(0+)1', '1(0+)1', '1(0+)1']
If you have any doubts regarding the tutorial, mention them in the comment section.