code-rag-bench/online-tutorials huggingface dataset:
reflect.StructOf() Function in Golang with Examples - GeeksforGeeks

28 Apr, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.StructOf() Function in Golang is used to get the struct type containing fields. To access this function, one needs to imports the reflect package in the program.
Syntax:
func StructOf(fields []StructField) Type

Parameters: This function takes only one parameters of StructFields( fields ).
Return Value: This function returns the struct type containing fields.
Below examples illustrate the use of above method in Golang:
Example 1:
// Golang program to illustrate// reflect.SliceOf() Function   package main  import (    "fmt"    "reflect")  // Main functionfunc main() {      // use of StructOf method    typ := reflect.StructOf([]reflect.StructField{        {            Name: "Height",            Type: reflect.TypeOf(float64(0)),        },        {            Name: "Name",            Type: reflect.TypeOf("abc"),        },    })      fmt.Println(typ)  }
Output:
struct { Height float64; Name string }

Example 2:
// Golang program to illustrate// reflect.SliceOf() Function   package main  import (    "fmt"    "reflect")  // Main functionfunc main() {      // use of StructOf method    tt:= reflect.StructOf([]reflect.StructField{        {            Name: "Height",            Type: reflect.TypeOf(0.0),            Tag:  `json:"height"`,        },        {            Name: "Name",            Type: reflect.TypeOf("abc"),            Tag:  `json:"name"`,        },    })      fmt.Println(tt.NumField())     fmt.Println(tt.Field(0))    fmt.Println(tt.Field(1))  }
Output:
2
{Height  float64 json:"height" 0 [0] false}
{Name  string json:"name" 8 [1] false}

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Strings in Golang
Time Durations in Golang
How to Parse JSON in Golang?
Structures in Golang
Defer Keyword in Golang
How to iterate over an Array using for loop in Golang?
Class and Object in Golang
Loops in Go Language
6 Best Books to Learn Go Programming Language
Rune in Golang
C | Macro & Preprocessor | Question 4 - GeeksforGeeks

04 Feb, 2013
#include <stdio.h>#define X 3#if !X    printf("Geeks");#else    printf("Quiz");   #endifint main(){        return 0;}
(A) Geeks(B) Quiz(C) Compiler Error(D) Runtime ErrorAnswer: (C)Explanation: A program is converted to executable using following steps
1) Preprocessing
2) C code to object code conversion
3) Linking
The first step processes macros. So the code is converted to following after the preprocessing step.
printf("Quiz");
int main()
{
        return 0;
}

The above code produces error because printf() is called outside main. The following program works fine and prints “Quiz”
#include 
#define X 3

int main()
{
#if !X
    printf("Geeks");
#else
    printf("Quiz");

#endif
    return 0;
}

C-Macro & Preprocessor
Macro & Preprocessor
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
C | Pointer Basics | Question 14
C Program for Sum the digits of a given number - GeeksforGeeks

19 Jul, 2021
Given a number, find sum of its digits.Example :  
Input : n = 687
Output : 21

Input : n = 12
Output : 3
1. Iterative: 
C
C
// C program to compute sum of digits in// number.# include<stdio.h> /* Function to get sum of digits */int getSum(int n){   int sum = 0;   while (n != 0)   {       sum = sum + n % 10;       n = n/10;   }   return sum;} int main(){  int n = 687;  printf(" %d ", getSum(n));  return 0;}
Time Complexity: O(log10n)
Auxiliary Space: O(1)
How to compute in single line?
C
c
# include<stdio.h>/* Function to get sum of digits */int getSum(int n){    int sum;     /* Single line that calculates sum */    for (sum=0; n > 0; sum+=n%10,n/=10);     return sum;} int main(){  int n = 687;  printf(" %d ", getSum(n));  return 0;}
2. Recursive
C
c
int sumDigits(int no){   return no == 0 ? 0 : no%10 + sumDigits(no/10) ;} int main(void){    printf("%d", sumDigits(687));    return 0;}
Please refer complete article on Program for Sum the digits of a given number for more details!
souravmahato348
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Create n-child process from same parent process using fork() in C
Conditional wait and signal in multi-threading
Lamport's logical clock
Algorithms Quiz | Sudo Placement : Set 1 | Question 5 - GeeksforGeeks

28 Dec, 2020
What will be the output of following C program?
main()
{
char g[] = "geeksforgeeks";
printf("%s", g + g[6] - g[8]);
}
(A) geeks(B) rgeeks(C) geeksforgeeks(D) forgeeksAnswer: (A)Explanation:
char g[] = “geeksforgeeks”;  

// g now has the base address string “geeksforgeeks”  

// g[6] is ‘o’ and g[1] is ‘e’.  

// g[6] – g[1] = ASCII value of ‘o’ – ASCII value of ‘e’ = 8

// So the expression  g + g[6] – g[8] becomes g + 8 which is  

// base address of string “geeks”  

printf(“%s”, g + g[6] – g[8]);  // prints geeks 
Hence, option (A) is correctQuiz of this Question
Saurabh17a
ApurvaRaj
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Bit Algorithms | Question 3
Algorithms | Bit Algorithms | Question 2
Data Structures and Algorithms | Set 38
Algorithms | Divide and Conquer | Question 2
Algorithms | Bit Algorithms | Question 1
Algorithms | Dynamic Programming | Question 7
Algorithms | Divide and Conquer | Question 4
C++ | Function Overloading and Default Arguments | Question 3 - GeeksforGeeks

28 Jun, 2021
Which of the following overloaded functions are NOT allowed in C++?
1) Function declarations that differ only in the return type
    int fun(int x, int y);
         void fun(int x, int y); 
2) Functions that differ only by static keyword in return type
    int fun(int x, int y);
         static int fun(int x, int y); 
3)Parameter declarations that differ only in a pointer * versus an array []
int fun(int *ptr, int n);
int fun(int ptr[], int n); 
4) Two parameter declarations that differ only in their default arguments
int fun( int x, int y); 
int fun( int x, int y = 10); 
(A) All of the above
(B) All except 2)(C) All except 1)(D) All except 2 and 4Answer: (A)Explanation: See Function overloading in C++Quiz of this Question
C++-Function Overloading and Default Arguments
Function Overloading and Default Arguments
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Substring in C++
rand() and srand() in C/C++
fork() in C
C++ | new and delete | Question 4
C++ | new and delete | Question 1
C++ | References | Question 4
C++ | Inheritance | Question 3
C++ | Inheritance | Question 1
CSS | blur() Function - GeeksforGeeks

07 Aug, 2019
The blur() function is an inbuilt function which is used to apply a blurred effect filter on the image.
Syntax:
blur( radius )
Parameters: This function accepts single parameter radius which holds the blur radius in form of length. This parameter defines the value of the standard deviation to the Gaussian function.
Below example illustrates the blur() function in CSS:
Example:
<!DOCTYPE html> <html>   <head>     <title>CSS blur() Function</title>           <style>        h1 {            color:green;        }        body {            text-align:center;        }        .blur_effect {            filter: blur(5px);        }    </style></head>   <body>     <h1>GeeksforGeeks</h1>           <h2>CSS blur() function</h2>          <img class="blur_effect" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"        alt="GeeksforGeeks logo"> </body>   </html> 
Output:
Supported Browsers: The browsers supported by blur() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 style a checkbox using CSS?
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
Top 10 Angular Libraries For Web Developers
How to get only files but not the folders with Get-ChildItem using PowerShell?

To get only files, you need to use NOT operator in Directory attribute parameter.
Get-ChildItem D:\Temp\ -Attributes !Directory
irectory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       07-05-2018     23:00            301 cars.xml
-a----       29-12-2017     15:16           4526 healthcheck.htm
-a----       29-12-2017     15:16           4526 healthcheck1.htm
-ar---       13-01-2020     18:19              0 Readonlyfile.txt
-a----       08-12-2017     10:24          48362 servicereport.htm
-a----       08-12-2017     10:24          48362 servicereport1.htm
-a----       08-12-2017     10:16            393 style.css
-a----       12-12-2017     23:04           1034 tes.htmoutput.htm
-a----       08-12-2017     11:29           7974 Test.xlsx
-a----       25-10-2017     08:13            104 testcsv.csv
You can combine different options together to get the desired result. To get only hidden files but not the folders.
Get-ChildItem D:\Temp\ -Attributes !Directory -Hidden

To get only, system Readonly files,
Get-ChildItem D:\Temp\ -Attributes !Directory –System -Readonly
Find smallest and largest elements in singly linked list in C++

In this problem, we are given a singly linked list. Our task is to find the
smallest and largest elements in single linked list.
Let’s take an example to understand the problem,
linked List : 5 -> 2 -> 7 -> 3 ->9 -> 1 -> 4
Smallest element = 1
Largest element = 9
A simple solution to the problem is using by traversing the linked list node
by node. Prior to this, we will initialise maxElement and minElement to the
value of the first element i.e. head -> data. Then we will traverse the linked
list element by element. And then compare the value of the current node with maxElement and store the greater value in maxElement variable. Perform the same to store smaller values in minElement. When the traversal is done print both the values.
Program to illustrate the working of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void printLargestSmallestLinkedList(struct Node* head) {
   int maxElement = INT_MIN;
   int minElement = INT_MAX;
   while (head != NULL) {
      if (minElement > head->data)
         minElement = head->data;
      if (maxElement < head->data)
         maxElement = head->data;
      head = head->next;
   }
   cout<<"Smallest element in the linked list is : "<<minElement<<endl;
   cout<<"Largest element in the linked list is : "<<maxElement<<endl;
}
void push(struct Node** head, int data) {
   struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
   newNode->data = data;
   newNode->next = (*head);
   (*head) = newNode;
}
int main() {
   struct Node* head = NULL;
   push(&head, 5);
   push(&head, 2);
   push(&head, 7);
   push(&head, 3);
   push(&head, 9);
   push(&head, 1);
   push(&head, 4);
   printLargestSmallestLinkedList(head);
   return 0;
}
Smallest element in the linked list is : 1
Largest element in the linked list is : 9
List containsAll() method in Java with Examples - GeeksforGeeks

11 Dec, 2018
The containsAll() method of List interface in Java is used to check if this List contains all of the elements in the specified Collection. So basically it is used to check if a List contains a set of elements or not.
Syntax:
boolean containsAll(Collection col)
Parameters: This method accepts a mandatory parameter col which is of the type of collection. This is the collection whose elements are needed to be checked if it is present in the List or not.
Return Value: The method returns True if all elements in the collection col are present in the List otherwise it returns False.
Exception: The method throws NullPointerException if the specified collection is NULL.
Below programs illustrates the containsAll() method:
Program 1:
// Java code to illustrate containsAll() methodimport java.util.*;  public class ListDemo {    public static void main(String args[])    {        // Creating an empty list        List<String> list = new ArrayList<String>();          // Use add() method to add elements        // into the List        list.add("Welcome");        list.add("To");        list.add("Geeks");        list.add("4");        list.add("Geeks");          // Displaying the List        System.out.println("List: " + list);          // Creating another empty List        List<String> listTemp = new ArrayList<String>();          listTemp.add("Geeks");        listTemp.add("4");        listTemp.add("Geeks");          System.out.println("Are all the contents equal? "                           + list.containsAll(listTemp));    }}
List: [Welcome, To, Geeks, 4, Geeks]
Are all the contents equal? true

Program 2:
// Java code to illustrate containsAll() methodimport java.util.*;  public class ListDemo {    public static void main(String args[])    {        // Creating an empty list        List<Integer> list = new ArrayList<Integer>();          // Use add() method to add elements        // into the List        list.add(10);        list.add(15);        list.add(30);        list.add(20);        list.add(5);          // Displaying the List        System.out.println("List: " + list);          // Creating another empty List        List<Integer> listTemp = new ArrayList<Integer>();          listTemp.add(30);        listTemp.add(15);        listTemp.add(5);          System.out.println("Are all the contents equal? "                           + list.containsAll(listTemp));    }}
List: [10, 15, 30, 20, 5]
Are all the contents equal? true

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#containsAll(java.util.Collection)
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Set in Java
Create Toast Message in Java Swing


A toast message is an alert which disappears with time automatically. With JDK 7, we can create a toast message similar to an alert on android very easily. Following are the steps needed to make a toast message.
Make a rounded rectangle shaped frame. Add a component listener to frame and override the componentResized() to change the shape of the frame. This method recalculates the shape of the frame correctly whenever the window size is changed.
frame.addComponentListener(new ComponentAdapter() {
   @Override
   public void componentResized(ComponentEvent e) {
      frame.setShape(new  RoundRectangle2D.Double(0,0,frame.getWidth(),
      frame.getHeight(), 20, 20));
   }
});
During display, initially show the frame then hide it slowly by making the opacity towards 0.
for (double d = 1.0; d > 0.2; d -= 0.1) {
   Thread.sleep(100);
   setOpacity((float)d);
}
See the example below of a toast message window.
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Tester {
   public static void main(String[] args) {
      ToastMessage message = new ToastMessage("Welcome to TutorialsPoint.Com");
      message.display();
   }
}

class ToastMessage extends JFrame {
   public ToastMessage(final String message) {
      setUndecorated(true);
      setLayout(new GridBagLayout());
      setBackground(new Color(240,240,240,250));
      setLocationRelativeTo(null);
      setSize(300, 50);
      add(new JLabel(message));
       
      addComponentListener(new ComponentAdapter() {
         @Override
         public void componentResized(ComponentEvent e) {
            setShape(new  RoundRectangle2D.Double(0,0,getWidth(),
            getHeight(), 20, 20));                      
         }
      });        
   }

   public void display() {
      try {
         setOpacity(1);
         setVisible(true);
         Thread.sleep(2000);

         //hide the toast message in slow motion
         for (double d = 1.0; d > 0.2; d -= 0.1) {
            Thread.sleep(100);
            setOpacity((float)d);
         }

         // set the visibility to false
         setVisible(false);
      }catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}
Can we override final methods in Java?

Overriding is a one of the mechanisms to achieve polymorphism. This is the case when we have two classes where, one inherits the properties of another using the extends keyword and, these two classes same method including parameters and return type (say, sample).
Since it is inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the subclass.
When we invoke this method (sample) JVM calls the respective method based on the object used to call the method.
No, you cannot override final method in java. If you try to do so, it generates a compile time error saying
class Super{
   public final void demo() {
      System.out.println("This is the method of the superclass");
   }
}
class Sub extends Super{
   public final void demo() {
      System.out.println("This is the method of the subclass");
   }
}
Sub.java:7: error: demo() in Sub cannot override demo() in Super
   public final void demo() {
          ^
   overridden method is final
1 error
If you try to compile the same program in eclipse you will get the following error −
Short-circuit evaluation in JavaScript

Short circuit evaluation basically works with the && and || logical operators. The expressions
are evaluated left to right.
For && operator − Short circuit evaluation with &&(AND) logical operator means if the first expression evaluates to false then whole expression will be false and the rest of the expressions will not be evaluated.
For || operator − Short circuit evaluation with ||(OR) logical operator means if the first expression evaluates to true then the whole expression will be true and the rest of the expressions will not be evaluated.
Following is the code for short circuit evaluation in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Short-circuit evaluation</h1>
<div class="result"></div>
<br />
<button class="Btn">&& short circuit evaluation</button>
<button class="Btn">|| short circuit evaluation</button>
<h3>Click on the above button to see the the short circuit evaluation</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelectorAll(".Btn");
   function retTrue() {
      resEle.innerHTML += "True <br>";
      return true;
   }
   function retFalse() {
      resEle.innerHTML += "False <br>";
      return false;
   }
   BtnEle[0].addEventListener("click", () => {
      resEle.innerHTML = "&& evaluation<br>";
      retFalse() && retTrue();
   });
   BtnEle[1].addEventListener("click", () => {
      resEle.innerHTML = "|| evaluation <br>";
      retTrue() || retFalse();
   });
</script>
</body>
</html>
On clicking the “&& short circuit evaluation” button −
On clicking the ‘|| short circuit evaluation” button −
Groovy - toLowerCase()

Converts all of the characters in this String to lower case.
String toLowerCase()

None
The modified string in lower case.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      String a = "HelloWorld"; 
      println(a.toLowerCase()); 
   } 
}
When we run the above program, we will get the following result −
helloworld


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
sciPy stats.nanmedian() function | Python - GeeksforGeeks

11 Feb, 2019
scipy.stats.nanmedian(array, axis=0) function calculates the median by ignoring the Nan (not a number) values of the array elements along the specified axis of the array.
Parameters :array : Input array or object having the elements, including Nan values, to calculate the median.axis : Axis along which the median is to be computed. By default axis = 0
Returns : median of the array elements (ignoring the Nan values) based on the set parameters.
Code #1:
# median import scipyimport numpy as np  arr1 = [1, 3, np.nan, 27, 2, 5]    print("median using nanmedian :", scipy.nanmedian(arr1))  print("median without handling nan value :", scipy.median(arr1)) 
Output:
median using nanmedian : 3.0
median without handling nan value : nan
 Code #2: With multi-dimensional data
# median from scipy import medianfrom scipy import nanmedianimport numpy as np  arr1 = [[1, 3, 27],         [3, np.nan, 6],         [np.nan, 6, 3],         [3, 6, np.nan]]    print("median is :", median(arr1)) print("median handling nan :", nanmedian(arr1))   # using axis = 0print("\nmedian is with default axis = 0 : \n",       median(arr1, axis = 0))print("\nmedian handling nan with default axis = 0 : \n",       nanmedian(arr1, axis = 0))  # using axis = 1print("\nmedian is with default axis = 1 : \n",       median(arr1, axis = 1))  print("\nmedian handling nan with default axis = 1 : \n",       nanmedian(arr1, axis = 1))  
Output:
median is : nan
median handling nan : 3.0

median is with default axis = 0 : 
 [ nan  nan  nan]

median handling nan with default axis = 0 : 
 [ 3.  6.  6.]

median is with default axis = 1 : 
 [  3.  nan  nan  nan]

median handling nan with default axis = 1 : 
 [ 3.   4.5  4.5  4.5]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
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
How to get battery level and state in Android?

This example demonstrates how to get battery level and state in Android.
Step 1 - Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 - Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:id = "@+id/parent"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:gravity = "center"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/text"
      android:textSize = "18sp"
      android:textAlignment = "center"
      android:text = "batter percentage"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a text view. it contains battery percentage.
Step 3 - Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView text;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      text = findViewById(R.id.text);
      BatteryManager bm = (BatteryManager)getSystemService(BATTERY_SERVICE);
      if (android.os.Build.VERSION.SDK_INT > = android.os.Build.VERSION_CODES.LOLLIPOP) {
         int percentage = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
         text.setText("Battery Percentage is "+percentage+" %");
      }
   }
}
In the above code, we have used the battery manager system service. To get the battery percentage use the following code -
BatteryManager bm = (BatteryManager)getSystemService(BATTERY_SERVICE);
if (android.os.Build.VERSION.SDK_INT > = android.os.Build.VERSION_CODES.LOLLIPOP) {
   int percentage = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
   text.setText("Battery Percentage is "+percentage+" %");
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -
In the above result shows the initial screen and it is showing 100% battery percentage.
Click here to download the project code
Java labelled statement

Yes. Java supports labeled statements. You can put a label before a for statement and use the break/continue controls to jump to that label. 
See the example below.
Live Demo
public class Tester {
   public static void main(String args[]) {

      first:
         for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++){
               if(i == 1){
                  continue first;
               }
               System.out.print(" [i = " + i + ", j = " + j + "] ");
            }
         }
         System.out.println();
     
      second:
         for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++){
               if(i == 1){
                  break second;
               }
               System.out.print(" [i = " + i + ", j = " + j + "] ");
            }
         }
   }
}
first is the label for first outermost for loop and continue first cause the loop to skip print statement if i = 1;
second is the label for second outermost for loop and continue second cause the loop to break the loop.
How to plot one single data point in Matplotlib?

To plot one single data point in matplotlib, we can take the following steps −
Initialize a list for x and y, with a single value.
Initialize a list for x and y, with a single value.
Limit x and y axis range for 0 to 5.
Limit x and y axis range for 0 to 5.
Lay out a grid in current line style.
Lay out a grid in current line style.
Plot given x and y using plot() method, with marker="o", markeredgecolor="red", markerfacecolor="green".
Plot given x and y using plot() method, with marker="o", markeredgecolor="red", markerfacecolor="green".
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [4]
y = [3]
plt.xlim(0, 5)
plt.ylim(0, 5)
plt.grid()
plt.plot(x, y, marker="o", markersize=20, markeredgecolor="red",
markerfacecolor="green")
plt.show()
Elixir - Basic Syntax

We will start with the customary 'Hello World' program.
To start the Elixir interactive shell, enter the following command.
iex

After the shell starts, use the IO.puts function to "put" the string on the console output. Enter the following in your Elixir shell −
IO.puts "Hello world"
In this tutorial, we will use the Elixir script mode where we will keep the Elixir code in a file with the extension .ex. Let us now keep the above code in the test.ex file. In the succeeding step, we will execute it using elixirc−
IO.puts "Hello world"
Let us now try to run the above program as follows −
$elixirc test.ex
The above program generates the following result −
Hello World

Here we are calling a function IO.puts to generate a string to our console as output. This function can also be called the way we do in C, C++, Java, etc., providing arguments in parentheses following the function name −
IO.puts("Hello world") 

Single line comments start with a '#' symbol. There's no multi-line comment, but you can stack multiple comments. For example −
#This is a comment in Elixir

There are no required line endings like ';' in Elixir. However, we can have multiple statements in the same line, using ';'. For example,
IO.puts("Hello"); IO.puts("World!")
The above program generates the following result −
Hello 
World!

Identifiers like variables, function names are used to identify a variable, function, etc. In Elixir, you can name your identifiers starting with a lower case alphabet with numbers, underscores and upper case letters thereafter. This naming convention is commonly known as snake_case. For example, following are some valid identifiers in Elixir −
var1       variable_2      one_M0r3_variable

Please note that variables can also be named with a leading underscore. A value that is not meant to be used must be assigned to _ or to a variable starting with underscore −
_some_random_value = 42

Also elixir relies on underscores to make functions private to modules. If you name a function with a leading underscore in a module, and import that module, this function will not be imported.
There are many more intricacies related to function naming in Elixir which we will discuss in coming chapters.
Following words are reserved and cannot be used as variables, module or function names.
after     and     catch     do     inbits     inlist     nil     else     end 
not     or     false     fn     in     rescue     true     when     xor 
__MODULE__    __FILE__    __DIR__    __ENV__    __CALLER__ 


    35 Lectures 
     3 hours 

 Pranjal Srivastava

    54 Lectures 
     6 hours 

 Pranjal Srivastava, Harshit Srivastava

    80 Lectures 
     9.5 hours 

 Pranjal Srivastava

    43 Lectures 
     4 hours 

 Mohammad Nauman
 Print
 Add Notes
 Bookmark this page
Install Python package using Jupyter Notebook - GeeksforGeeks

06 Mar, 2020
Jupyter Notebook is an open-source web application that is used to create and share documents that contain data in different formats which includes live code, equations, visualizations, and text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.
Jupyter has support for over 40 different programming languages and Python is one of them. Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook itself.
Refer to the following articles for the installation of the Jupyter Notebook.
How to install Jupyter Notebook in Linux?
How to install Jupyter Notebook in Windows?
In Jupyter everything runs in cells. It gives options to change the cell type to markup, text, Python console, etc. Within the Python IPython console cell, jupyter allows Python code to be executed.
To install Python libraries, we use pip command on the command line console of the Operating System. The OS has a set of paths to executable programs in its so-called environment variables through which it identifies directly what exactly the pip means. This is the reason that whenever pip command can directly be run on the console.
In Jupyter, the console commands can be executed by the ‘!’ sign before the command within the cell. For example, If the following code is written in the Jupyter cell, it will execute as a command in CMD.
! echo GeeksforGeeks

Output
Similarly we can install any package via jupyter in the same way, and it will run it directly in the OS shell.
Syntax:
! pip install [package_name] 
Example: Let’s install NumPy using Jupyter.
But using this method is not recommended because of the OS behavior. This command executed on the current version in the $PATH variable of the OS. So in the case of multiple Python versions, this might not install the same package in the jupyter’s Python version. In the simplest case it may work.
To solve the above-mentioned problem, it is recommended to use sys library in Python which will return the path of the current version’s pip on which the jupyter is running. sys.executable will return the path of the Python.exe of the version on which the current Jupyter instance is
Syntax:
import sys
!{sys.executable} -m pip install [package_name]

Example:
By the above code, the package will be installed in the same Python version on which the jupyter notebook is running.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks

28 Jun, 2021
Which one of the following combinations is incorrect?(A) Acquiescence – Submission(B) Wheedle – Roundabout(C) Flippancy – Lightness(D) Profligate – ExtravagantAnswer: (B)Explanation:
Flippancy     ---> lack of respect or seriousness.
Acquiescence  ---> the reluctant acceptance of 
                   something without protest.
Wheedle      --->  use endearments or flattery to 
                   persuade someone to do something or 
Profligate   ---> recklessly extravagant 
Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2000 | Question 43
GATE | GATE CS 2021 | Set 1 | Question 47
Including an external stylesheet file in your HTML document

The <link> element can be used to include an external style sheet file in your HTML document.
An external style sheet is a separate text file with .css extension. You define all the Style rules within this text file and then you can include this file in any HTML document using <link> element.
Consider a simple style sheet file with a name new.css having the following rules:
h1, h2, h3 {
   color: #36C;
   font-weight: normal;
   letter-spacing: .4em;
   margin-bottom: 1em;
   text-transform: lowercase;
}
Now you can include this file new.css in any HTML document as follows:
<head>
   <link type = "text/css" href = "new.css" media = " all" />
</head>
How to preserve leading 0 with JavaScript numbers?

There’s no way to preserve the leading 0 in JavaScript. However, you can consider this id as a string and pass as an argument.
You can try to run the following code to preserve leading 0 by making it a string −
Live Demo
<html>
   <head>
      <script>
         function sayHello(name, age, id) {
            document.write (name + " is " + age + " years old, with id = "+id);
         }
      </script>
   </head>
   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type="button" onclick="sayHello('John', 26, '0678')"
            value="Display Employee Info">
      </form>
   </body>
</html>
Java DatabaseMetaData getUserName() method with example

This method retrieves the user name used to establish the current connection −
To retrieve the user name as known to the database −
Make sure your database is up and running.
Make sure your database is up and running.
Register the driver using the registerDriver() method of the DriverManager class. Pass an object of the driver class corresponding to the underlying database.
Register the driver using the registerDriver() method of the DriverManager class. Pass an object of the driver class corresponding to the underlying database.
Get the connection object using the getConnection() method of the DriverManager class. Pass the URL the database and, user name, password of a user in the database, as String variables.
Get the connection object using the getConnection() method of the DriverManager class. Pass the URL the database and, user name, password of a user in the database, as String variables.
Get the DatabaseMetaData object with respect to the current connection using the getMetaData() method of the Connection interface.
Get the DatabaseMetaData object with respect to the current connection using the getMetaData() method of the Connection interface.
Finally, retrieve the user name using the getUserName() method of the DatabaseMetaData interface .
Finally, retrieve the user name using the getUserName() method of the DatabaseMetaData interface .
Following JDBC program establishes connection with MySQL database and, retrieves the user name as known to the database.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseMetaData_getUserName {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql://localhost/";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Retrieving the meta data object
      DatabaseMetaData metaData = con.getMetaData();
      //Retrieving the user name
      String user_name = metaData.getUserName();
      System.out.println(user_name);
   }
}
Connection established......
root@localhost
Add a single element to a LinkedList in Java

A single element can be added to a LinkedList by using the java.util.LinkedList.add() method. This method has one parameter parameters i.e. the element that is to be inserted in the LinkedList.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Magic");
      System.out.println("The LinkedList is: " + l);
   }
}
The LinkedList is: [Magic]
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add a single element to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>();
l.add("Magic");
System.out.println("The LinkedList is: " + l);
Program to convert Milliseconds to Date Format in Java

Let us first declare and initialize milliseconds value variable −
long milliSeconds = 656478;
Now, convert Milliseconds to Date format −
DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
Date date = new Date(milliSeconds);
Following is the program to convert Milliseconds to Date Format in Java −
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String args[]) {
      long milliSeconds = 656478;
      DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
      Date date = new Date(milliSeconds);
      System.out.println(dateFormat.format(date));
   }
}
01 Jan 1970 00:10:56:478 +0000
What is encapsulation in Java?

Encapsulation in Java is a mechanism for wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java:
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
public class EncapTest {
   private String name;
   private String idNum;
   private int age;
   
   public int getAge() {
      return age;
   }
   public String getName() {
      return name;
   }
   public String getIdNum() {
      return idNum;
   }
   public void setAge( int newAge) {
      age = newAge;
   }
   public void setName(String newName) {
      name = newName;
   }
   public void setIdNum( String newId) {
      idNum = newId;
   }
}
public class RunEncap {
   public static void main(String args[]) {
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");
      
      System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
   }
}
Name : James Age : 20
C++ Library - <functional>

Function objects are objects specifically designed to be used with a syntax similar to that of functions. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.
Following is the declaration for std::function.
template<class >
class function; 
template< class R, class... Args >
class function<R(Args...)>
R − result_type.
R − result_type.
argument_type − T if sizeof...(Args)==1 and T is the first and only type in Args.
argument_type − T if sizeof...(Args)==1 and T is the first and only type in Args.
In below example for std::function.
#include <functional>
#include <iostream>

struct Foo {
   Foo(int num) : num_(num) {}
   void print_add(int i) const { std::cout << num_+i << '\n'; }
   int num_;
};
 
void print_num(int i) {
   std::cout << i << '\n';
}

struct PrintNum {
   void operator()(int i) const {
      std::cout << i << '\n';
   }
};

int main() {
   std::function<void(int)> f_display = print_num;
   f_display(-9);

   std::function<void()> f_display_42 = []() { print_num(42); };
   f_display_42();

   std::function<void()> f_display_31337 = std::bind(print_num, 31337);
   f_display_31337();

   std::function<void(const Foo&, int)> f_add_display = &Foo::print_add;
   const Foo foo(314159);
   f_add_display(foo, 1);

   std::function<int(Foo const&)> f_num = &Foo::num_;
   std::cout << "num_: " << f_num(foo) << '\n';

   using std::placeholders::_1;
   std::function<void(int)> f_add_display2= std::bind( &Foo::print_add, foo, _1 );
   f_add_display2(2);
 
   std::function<void(int)> f_add_display3= std::bind( &Foo::print_add, &foo, _1 );
   f_add_display3(3);

   std::function<void(int)> f_display_obj = PrintNum();
   f_display_obj(18);
}
The sample output should be like this −
-9
42
31337
314160
num_: 314159
314161
314162
18

 Print
 Add Notes
 Bookmark this page
HTML <datalist> Tag

17 Mar, 2022
The <datalist> tag is used to provide autocomplete feature in the HTML files. It can be used with an input tag so that users can easily fill the data in the forms using select the data.Syntax:
<datalist> ... </datalist>
Example 1: The below code explains datalist Tag.
HTML
<!DOCTYPE html><html><body>    <form action="">        <label>Your Cars Name: </label>        <input list="cars">                    <!--datalist Tag starts here -->        <datalist id="cars">            <option value="BMW"/>            <option value="Bentley"/>            <option value="Mercedes"/>            <option value="Audi"/>            <option value="Volkswagen"/>        </datalist>        <!--datalist Tag ends here -->     </form></body></html>
Output: 
Example 2: The <datalist> tag object can be easily accessed by an input attribute type.
HTML
<!DOCTYPE html><html><body>    <form action="">        <label>Your Cars Name: </label>        <input list="cars" id="carsInput" />         <!--datalist Tag starts here -->        <datalist id="cars">            <option value="BMW" />            <option value="Bentley" />            <option value="Mercedes" />            <option value="Audi" />            <option value="Volkswagen" />        </datalist>        <!--datalist Tag ends here -->         <button onclick="datalistcall()" type="button">            Click Here        </button>    </form>    <p id="output"></p>      <!-- Will display the select option -->    <script type="text/javascript">        function datalistcall() {            var o1 = document.getElementById("carsInput").value;            document.getElementById("output").innerHTML =              "You select " + o1 + " option";        }    </script></body></html>
Output:
Supported Browsers: 
Google Chrome 20.0 and above
Internet Explorer 10.0 and above
Firefox 4.0 and above
Opera 9.0 and above
Safari 11.1
 
arorakashish0911
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2006 | Question 32

28 Jun, 2021
Consider the following statements about the context free grammar
G = {S → SS, S → ab, S → ba, S → Ε}
I. G is ambiguous
II. G produces all strings with equal number of a’s and b’s
III. G can be accepted by a deterministic PDA.
Which combination below expresses all the true statements about G?(A) I only(B) I and III only(C) II and III only(D) I, II and IIIAnswer: (B)Explanation:  
Statement I: G is ambiguous because, as shown in the image below there can be two decision tree for string S = ababab [TRUE]
Statement II: G produces all strings with equal number of a’s and b’s [FALSE]
string ‘aabb’ cannot be produced by G
Statement III: G can be accepted by a deterministic PDA [TRUE]
Assume there is a PDA which pushes if top of the stack is $ (bottom most alphabet of the stack) and pops otherwise. A string is rejected while popping if the current letter and top of the stack are same. This PDA can derive G.
Hence, correct answer should be (B) I and III only
Reference:Ambiguity in Context free Grammar and Context free Languages
This solution is contributed by Vineet Purswani.Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding CSS Absolute and Relative Units

The absolute length units are fixed in relation to each other. These units are used when the output format is already known. Following are some of the Absolute Length Units −
picas (1pc = 12 pt)
Let us now see an example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
   text-decoration: overline underline;
   text-decoration-color: blue;
   font-size: 0.3in;
}
</style>
</head>
<body>
<h1>Details</h1>
<p class="demo">Examination Center near ABC College.</p>
<p class="demo2">Exam begins at 9AM.</p>
</body>
</html>
Relative length units in CSS is used to specify a length relative to another length property.
Relative to the x-height of the current font
Let us see an example using Relative Length Units −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
   text-decoration: overline underline;
   text-decoration-color: blue;
   font-size: 1.4em;
}
</style>
</head>
<body>
<h1>Details</h1>
<p class="demo">Examination Center near ABC College.</p>
<p class="demo2">Exam begins at 9AM.</p>
</body>
</html>