code-rag-bench/online-tutorials huggingface dataset:
ML | Principal Component Analysis(PCA) - GeeksforGeeks

20 Jul, 2021
Principal Component Analysis (PCA) is a statistical procedure that uses an orthogonal transformation that converts a set of correlated variables to a set of uncorrelated variables. PCA is the most widely used tool in exploratory data analysis and in machine learning for predictive models. Moreover, PCA is an unsupervised statistical technique used to examine the interrelations among a set of variables. It is also known as a general factor analysis where regression determines a line of best fit.
Module Needed:
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline
Code #1:
# Here we are using inbuilt dataset of scikit learnfrom sklearn.datasets import load_breast_cancer  # instantiatingcancer = load_breast_cancer()  # creating dataframedf = pd.DataFrame(cancer['data'], columns = cancer['feature_names'])  # checking head of dataframedf.head()
Output:
# Importing standardscalar module from sklearn.preprocessing import StandardScaler  scalar = StandardScaler()  # fittingscalar.fit(df)scaled_data = scalar.transform(df)  # Importing PCAfrom sklearn.decomposition import PCA  # Let's say, components = 2pca = PCA(n_components = 2)pca.fit(scaled_data)x_pca = pca.transform(scaled_data)  x_pca.shape
Output:
569, 2
# giving a larger plotplt.figure(figsize =(8, 6))  plt.scatter(x_pca[:, 0], x_pca[:, 1], c = cancer['target'], cmap ='plasma')  # labeling x and y axesplt.xlabel('First Principal Component')plt.ylabel('Second Principal Component')
Output:
# componentspca.components_
Output:
df_comp = pd.DataFrame(pca.components_, columns = cancer['feature_names'])  plt.figure(figsize =(14, 6))  # plotting heatmapsns.heatmap(df_comp)
Output:
Advanced Computer Subject
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Decision Tree Introduction with example
System Design Tutorial
Python | Decision tree implementation
Copying Files to and from Docker Containers
Decision Tree
Agents in Artificial Intelligence
Activation functions in Neural Networks
Introduction to Recurrent Neural Network
Decision Tree Introduction with example
Find the average of first N natural numbers - GeeksforGeeks

19 Mar, 2021
Write a program to find the Average of first N natural number. Examples:  
Input  : 10
Output : 5.5
1+2+3+4+5+6+7+8+9+10 = 5.5

Input  : 7
Output : 4.0
1+2+3+4+5+6+7 = 4
 
Prerequisite : Sum of first n natural numbers.As discussed in previous post, sum of n natural number n(n+1)/2, we find the Average of n natural number so divide by n is n(n+1)/2*n = (n+1)/2. Here 1 if first term and n is last term.  
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the Average of first// n natural numbers#include <bits/stdc++.h>using namespace std; // Return the average of first n natural numbersfloat avgOfFirstN(int n){    return (float)(1 + n)/2;} // Driven Programint main(){    int n = 20;    cout << avgOfFirstN(n) << endl;    return 0;}
// Java Program to find the Average of first// n natural numbersimport java.io.*; class GFG {     // Return the average of first n    // natural numbers    static float avgOfFirstN(int n)    {        return (float)(1 + n) / 2;    }     // Driven Program    public static void main(String args[])    {        int n = 20;        System.out.println(avgOfFirstN(n));    }} /*This code is contributed by Nikita tiwari.*/
# Python 3 Program to find the Average# of first n natural numbers # Return the average of first n# natural numbersdef avgOfFirstN(n) :    return (float)(1 + n) / 2; # Driven Programn = 20print(avgOfFirstN(n)) # This code is contributed by Nikita Tiwari.
// C#Program to find the Average of first// n natural numbersusing System; class GFG {     // Return the average of first n    // natural numbers    static float avgOfFirstN(int n)    {        return (float)(1 + n) / 2;    }     // Driven Program    public static void Main()    {        int n = 20;        Console.WriteLine(avgOfFirstN(n));    }} /*This code is contributed by vt_m.*/
<?php// PHP Program to find// the Average of first// n natural numbers // Return the average// of first n natural// numbersfunction avgOfFirstN($n){    return (float)(1 + $n) / 2;} // Driver Code$n = 20;echo(avgOfFirstN($n)); // This code is contributed by Ajit.?>
<script> // javascript Program to find the Average of first// n natural numbers // Return the average of first n natural numbersfunction avgOfFirstN( n){    return (1 + n)/2;} // Driven Program     let n = 20;    document.write(avgOfFirstN(n)); // This code is contributed by todaysgaurav </script>
Output: 
10.5
Time Complexity : O(1)  
jit_t
todaysgaurav
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Matcher pattern() method in Java with Examples - GeeksforGeeks

26 Nov, 2018
The pattern() method of Matcher Class is used to get the pattern to be matched by this matcher.
Syntax:
public Pattern pattern()

Parameters: This method do not accepts any parameter.
Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher.
Below examples illustrate the Matcher.pattern() method:
Example 1:
// Java code to illustrate pattern() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "Geeks";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GeeksForGeeks";          // Create a matcher for the input String        Matcher matcher            = pattern.matcher(stringToBeMatched);          // Get the Pattern using pattern() method        System.out.println("Pattern: "                           + matcher.pattern());    }}
Pattern: Geeks

Example 2:
// Java code to illustrate pattern() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "GFG";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GFGFGFGFGFGFGFGFGFG";          // Create a matcher for the input String        Matcher matcher            = pattern.matcher(stringToBeMatched);          // Get the Pattern using pattern() method        System.out.println("Pattern: "                           + matcher.pattern());    }}
Pattern: GFG

Reference: Oracle Doc
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Python - Alternate Strings Concatenation - GeeksforGeeks

27 Feb, 2020
The problem of getting concatenation of a list is quite generic and we might some day face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing concatenation of alternate elements. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + list slicing + join()List slicing clubbed with list comprehension can be used to perform this particular task. We can have list comprehension to get run the logic and list slicing can slice out the alternate character, concat by the join() function.
# Python3 code to demonstrate# Alternate Strings Concatenation# using list comprehension + list slicing  # initializing list test_list = ["GFG", "is", "for", "Computer", "Science", "learning"]  # printing original list print("The original list : " + str(test_list))  # using list comprehension + list slicing# Alternate Strings Concatenationres = [" ".join(test_list[i : : 2]) for i in range(len(test_list) //                                                  (len(test_list)//2))]  # print resultprint("The alternate elements concatenation list : " + str(res))
The original list : ['GFG', 'is', 'for', 'Computer', 'Science', 'learning']
The alternate elements concatenation list : ['GFG for Science', 'is Computer learning']

 
Method #2 : Using loopThis is the brute method to perform this particular task in which we have the concatenation of alternate elements in different element indices and then return the output list.
# Python3 code to demonstrate# Alternate Strings Concatenation# using loop  # initializing list  test_list = ["GFG", "is", " for", " Computer", " Science", " learning"]  # printing original list print("The original list : " + str(test_list))  # using loop# Alternate Strings Concatenationres = ["", ""]for i in range(0, len(test_list)):    if(i % 2):        res[1] += test_list[i]    else :        res[0] += test_list[i]  # print resultprint("The alternate elements concatenation list : " + str(res))
The original list : ['GFG', 'is', 'for', 'Computer', 'Science', 'learning']
The alternate elements concatenation list : ['GFG for Science', 'is Computer learning']

Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to check if the Azure resource group is empty or not using PowerShell?

To check if the resource group is empty or not we need to check if the resource group contains any resources.
For this example, We have a resource group name called  the TestRG and we need to check if it is empty.
$resources = Get-AzResource -ResourceGroupName TestRG
if($resources){"Resource group is not empty"}
else{"Resource group is empty"}
Resource group is empty
To check if the resource groups in the particular subscription are empty or not, use the below code.
Connect-AZAccount
Set-AzContext -SubscriptionName 'Your Subscription Name'
$rgs = Get-AzResourceGroup

Write-Output "Empty Resource Groups"
foreach($rg in $rgs.ResourceGroupName){
    $resources = Get-AzResource -ResourceGroupName $rg
    if(!($resources)){ $rg }
}
How can we use SIGNAL statement with MySQL triggers?

Actually, MySQL SIGNAL statement is an error handling mechanism for handling unexpected occurrences and a graceful exit from the application if need to be. Basically, it provides error information to the handler. Its basic syntax would be as follows −
SIGNAL SQLSTATE | condition_value
[SET signal_information_item = value_1,[, signal_information_item] = value_2,
etc;]
Here, the SIGNAL keyword is an SQLSTATE value or a condition name declared by a DECLARE CONDITION statement. The SIGNAL statement must always specify an SQLSTATE value or a named condition that defined with an SQLSTATE value. The SQLSTATE value for a The SIGNAL statement consists of a five-character alphanumeric code. We must not start our own SQLSTATE code with '00' because such values indicate success and are not valid for signaling an error. If our value is invalid, a Bad SQLSTATE error occurs. For catch-all error handling, we should assign an SQLSTATE value of '45000', which signifies an “unhandled user-defined exception.”
To illustrate the use of SIGNAL statement with MySQL triggers we are using the following example in which we are creating a BEFORE INSERT trigger on the student_age table. It will throw an error message using SIGNAL statement if we will try to enter the age of less than 0.
mysql> Create trigger before_insert_studentage BEFORE INSERT on
student_age FOR EACH ROW BEGIN IF NEW.age<0 then SIGNAL SQLSTATE
'45000' SET MESSAGE_TEXT = 'age less than 0'; END if; END; //
Query OK, 0 rows affected (0.12 sec)

mysql> Insert into student_age(age, name) values(-10,'gaurav')//
ERROR 1644 (45000): age less than 0
It is clear from the above result set that if we will try to insert age less than 0 then it will throw an error using SIGNAL statement.
Set the width and margin of the modal with Bootstrap

Use the .modal-dialog class in Bootstrap to set the width and margin of the modal.
You can try to run the following code to implement .modal-dialog class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Web Browser</h2>
         <button type = "button" class = "btn btn-lg" data-toggle = "modal" data-target = "#new">More</button>
         <div class = "modal fade" id="new" role = "dialog">
            <div class = "modal-dialog">
               <div class = "modal-content">
                  <div class = "modal-header">
                     <button type = "button" class = "close" data-dismiss = "modal">&amp;times;</button>
                     <h4 class = "modal-title">Warning</h4>
                  </div>
                  <div class = "modal-body">
                     <p>If JavaScript isn't enabled in your web browser, then you may not be able to see this information correcty.</p>
                  </div>
                  <div class = "modal-footer">
                     <button type = "button" class = "btn btn-default" data-dismiss = "modal">Close</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>
\ddot - Tex Command

\ddot - Used to draw double dot accent over the argument.
{ \ddot #1 }
\ddot command draws double dot accent over the argument.

\ddot x

x ̈



\ddot x

x ̈


\ddot x

    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
Convert Binary Number in a Linked List to Integer in C++

Suppose we have one ‘head’ which is a reference node to a singly-linked list. The value of each node present in the linked list is either 0 or 1. This linked list stores the binary representation of a number. We have to return the decimal value of the number present in the linked list. So if the list is like [1,0,1,1,0,1]
To solve this, we will follow these steps −
x := convert the list elements into an array
x := convert the list elements into an array
then reverse the list x
then reverse the list x
ans := 0, and temp := 1
ans := 0, and temp := 1
for i in range i := 0, to size of x – 1ans := ans + x[i] * temptemp := temp * 2
for i in range i := 0, to size of x – 1
ans := ans + x[i] * temp
ans := ans + x[i] * temp
temp := temp * 2
temp := temp * 2
return ans
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
      int val;
      ListNode *next;
      ListNode(int data){
         val = data;
         next = NULL;
      }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
class Solution {
public:
   vector <int> getVector(ListNode* node){
      vector <int> result;
      while(node){
         result.push_back(node->val);
         node = node->next;
      }
      return result;
   }
   int getDecimalValue(ListNode* head) {
      vector <int> x = getVector(head);
      reverse(x.begin(), x.end());
      int ans = 0;
      int temp = 1;
      for(int i = 0; i < x.size(); i++){
         ans += x[i] * temp;
         temp *= 2;
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,0,1,1,0,1};
   ListNode *head = make_list(v);
   cout << ob.getDecimalValue(head);
}
[1,0,1,1,0,1]
45
Initialize a window as maximized in Tkinter Python

Tkinter creates a default window with its default size while initializing the application. We can customize the geometry of the window using the geometry method.
However, in order to maximize the window, we can use the state() method which can be used for scaling the tkinter window. It maximizes the window after passing the “zoomed” state value to it.
#Import the required libraries
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Set the geometry of frame
win.geometry("600x400")

#Create a text label
Label(win,text="It takes only 21 days to create a new Habit", font=('Times
New Roman bold',15)).pack(pady=20)

#Maximize the window using state property
win.state('zoomed')

win.mainloop()
Running the above code will maximize the tkinter window.
Difference between 'and' and '&' in Python - GeeksforGeeks

25 Jan, 2021
and is a Logical AND that returns True if both the operands are true whereas ‘&’ is a bitwise operator in Python that acts on bits and performs bit by bit operation.
Note: When an integer value is 0, it is considered as False otherwise True when using logically.
Example:
# Python program to demonstrate # the difference between and, & # operator   a = 14b = 4  print(b and a) # print_stat1print(b & a) # print_stat2
Output:
14
4
This is because ‘and’ tests whether both expressions are logically True while ‘&’performs bitwise AND operation on the result of both statements.
In print statement 1, compiler checks if the first statement is True. If the first statement is False, it does not check the second statement and returns False immediately. This is known as “lazy evaluation”. If the first statement is True then the second condition is checked and according to rules of AND operation, True is the result only if both the statements are True. In the case of the above example, the compiler checks the 1st statement which is True as the value of b is 4, then the compiler moves towards the second statement which is also True because the value of a is 14. Hence, the output is also 14.
In print statement 2, the compiler is doing bitwise & operation of the results of statements. Here, the statement is getting evaluated as follows:The value of 4 in binary is 0000 0100 and the value of 14 in binary is 0000 1110. On performing bitwise and we get –
0000 0100
   &  = 0000 0100 = 4
0000 1110

Hence, the output is 4.
To elaborate on this, we can take another example.
Example:
# Python program to demonstrate# the difference between and, & # operator  a, b = 9, 10print(a & b)#line 1print(a and b)#line 2
Output:
8
10
The first line is performing bitwise AND on a and b and the second line is evaluating the statement inside print and printing answer.In line 1, a = 1001, b = 1010, Performing & on a and b, gives us 1000 which is the binary value of decimal value 8.In line 2, the expression ‘a and b’ first evaluates a; if a is False (or Zero), its value is returned immediately because of “lazy evaluation” explained above, else, b is evaluated. If b is also non-zero then the resulting value is returned. The value of b is returned because it is the last value where checking ends for the truthfulness of the statement.Hence the use of boolean and ‘and’ is recommended in a loop.
shrishti_m180521ca
python-basics
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 ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
Koko Eating Bananas in C++

Suppose we have N piles of bananas, the i-th pile has piles[i] bananas. Here the guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed is K. Each hour, she takes some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, then she consumes all of them instead, and won't eat any more bananas during this hour. Consider Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. We have to find the minimum integer K such that she can eat all the bananas within H hours.
So if the input is like [3,6,7,11], and H = 8, then the output will be 4.
To solve this, we will follow these steps −
Define a method called ok(), this will take array a, two values x and h
Define a method called ok(), this will take array a, two values x and h
time := 0
time := 0
for i in range 0 to size of atime := time + a[i] / xtime := time + i when a[i] mod x is 0
for i in range 0 to size of a
time := time + a[i] / x
time := time + a[i] / x
time := time + i when a[i] mod x is 0
time := time + i when a[i] mod x is 0
return true when time <= H
return true when time <= H
From the main method do the following
From the main method do the following
n := size of the piles array, set sum := 0, low := 1, high := 0
n := size of the piles array, set sum := 0, low := 1, high := 0
for i in range 0 to n – 1high := max of piles[i] and high
for i in range 0 to n – 1
high := max of piles[i] and high
high := max of piles[i] and high
while low < highmid := low + (high – low ) /2if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
while low < high
mid := low + (high – low ) /2
mid := low + (high – low ) /2
if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
return high
return high
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   bool ok(vector <int>& a, int x, int H){
      int time = 0;
      for(int i = 0; i < a.size(); i++){
         time += a[i] / x;
         time += (a[i] % x ? 1 : 0);
      }
      return time <= H;
   }
   int minEatingSpeed(vector<int>& piles, int H) {
      int n = piles.size();
      lli low = 1;
      lli sum = 0;
      lli high = 0;
      for(int i = 0; i < n; i++)high = max((lli)piles[i], high);
      while(low < high){
         int mid = low + (high - low) / 2;
         if(ok(piles, mid, H)){
            high = mid;
         }else{
            low = mid + 1;
         }
      }
      return high;
   }
};
main(){
   vector<int> v = {3,6,7,11};
   Solution ob;
   cout << (ob.minEatingSpeed(v, 8));
}
[3,6,7,11]
8
4
How to set background color of an android activity to yellow Programatically?

This example demonstrates how do I set background color of an android activity to yellow programmatically.
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.
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/relativeLayout"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textStyle="bold"
      android:textSize="24sp"
      android:text="The color of the Activity is Yellow"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
   RelativeLayout relativeLayout;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      relativeLayout = findViewById(R.id.relativeLayout);
      relativeLayout.setBackgroundColor(Color.YELLOW);
   }
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
How to make a background 20% transparent on Android

If you want to give transparent background for your view, This example demonstrate about How to make a background 20% transparent on Android.
All hex value from 100% to 0% alpha
100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00
For example, if you want to give 20% transparent background for yellow color (#FFFF00). So your background color would be #33FFFF00
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:background="#33FFFF00"
   android:gravity="center"
   android:orientation="vertical">
   <TextView
      android:id="@+id/text"
      android:textSize="18sp"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code we have give 20% transparent yellow background for text view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView=findViewById(R.id.text);
      textView.setText("Tutorialspoint india pvt ltd");
   }
}
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 Runicon 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, it is not pure yellow color. it shows 20% transparent yellow color
Click here to download the project code
Swap two variables in one line in C/C+

Here is an example of swapping in C language,
 Live Demo
#include <stdio.h>
int main() {
   int a = 28, b = 8;
   a += b -= a = b - a; // method 1
   printf("After Swapping : %d\t%d", a, b);
   (a ^= b), (b ^= a), (a ^= b); // method 2
   printf("\nAfter Swapping again : %d\t%d", a, b);
   return 0;
}
After Swapping : 828
After Swapping again : 288
In the above program, there are two variables a and b and initialized with the values 28 and 8 respectively. There are so many methods to swap two numbers in one line and we displayed two methods here.
a += b -= a = b - a; // method 1
printf("After Swapping : %d\t%d", a, b);
(a ^= b), (b ^= a), (a ^= b); // method 2
printf("\nAfter Swapping again : %d\t%d", a, b);
First Unique Character in a String in Python

Suppose we have a string and we have to find the first unique character in the string. So if the string is like “people”, the first letter whose occurrence is one is ‘o’. So the index will be returned, that is 2 here. If there is no such character, then return -1.
To solve this, we will follow these steps −
create one frequency map
for each character c in the string, doif c is not in frequency, then insert it into frequency, and put value 1otherwise, increase the count in frequency
if c is not in frequency, then insert it into frequency, and put value 1
otherwise, increase the count in frequency
Scan the frequency map, if the value of a specific key is 1, then return that key, otherwise return -1
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def firstUniqChar(self, s):
      """
      :type s: str
      :rtype: int
      """
      frequency = {}
      for i in s:
         if i not in frequency:
            frequency[i] = 1
         else:
            frequency[i] +=1
      for i in range(len(s)):
         if frequency[s[i]] == 1:
            return i
      return -1
ob1 = Solution()
print(ob1.firstUniqChar("people"))
print(ob1.firstUniqChar("abaabba"))
"people"
"abaabba"
2
-1
C++ Program to Add Two Distances (in inch-feet) System Using Structures

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 DistanceFI {
   int feet;
   int inch;
};
The above structure defines a distance in the form of feet and inches.
A program to add two distances in inch-feet using a structure in C++ is given as follows −
 Live Demo
#include <iostream>

using namespace std;
struct DistanceFI {
   int feet;
   int inch;
};
int main() {
   struct DistanceFI distance1, distance2, distance3;
   cout << "Enter feet of Distance 1: "<<endl;
   cin >> distance1.feet;
   cout << "Enter inches of Distance 1: "<<endl;
   cin >> distance1.inch;

   cout << "Enter feet of Distance 2: "<<endl;
   cin >> distance2.feet;
   cout << "Enter inches of Distance 2: "<<endl;
   cin >> distance2.inch;

   distance3.feet = distance1.feet + distance2.feet;
   distance3.inch = distance1.inch + distance2.inch;

   if(distance3.inch > 12) {
      distance3.feet++;
      distance3.inch = distance3.inch - 12;
   }
   cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";
   return 0;
}
The output of the above program is as follows
Enter feet of Distance 1: 5
Enter inches of Distance 1: 9
Enter feet of Distance 2: 2
Enter inches of Distance 2: 6
Sum of both distances is 8 feet and 3 inches
In the above program, the structure DistanceFI is defined that contains the distance in feet and inches. This is given below −
struct DistanceFI{
   int feet;
   int inch;
};
The values of both distances to be added are acquired from the user. This is given below −
cout << "Enter feet of Distance 1: "<<endl;
cin >> distance1.feet;
cout << "Enter inches of Distance 1: "<<endl;
cin >> distance1.inch;

cout << "Enter feet of Distance 2: "<<endl;
cin >> distance2.feet;
cout << "Enter inches of Distance 2: "<<endl;
cin >> distance2.inch;
The feet and inches of the two distances are added individually. If the inches are greater than 12, then 1 is added to the feet and 12 is subtracted from the inches. This is done because 1 feet = 12 inches. The code snippet for this is given below −
distance3.feet = distance1.feet + distance2.feet;
distance3.inch = distance1.inch + distance2.inch;
if(distance3.inch > 12) {
   distance3.feet++;
   distance3.inch = distance3.inch - 12;
}
Finally the value of feet and inches in the added distance is displayed. This is given below −
cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";
Scala List sum() method with example - GeeksforGeeks

26 Jul, 2019
The sum() method is utilized to add all the elements of the stated list.
Method Definition: def sum(num: math.Numeric[B]): B
Return Type: It returns the sum of all the elements of the list.
Example #1:
// Scala program of sum()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 2, 3, 4, 5, 7)                  // Applying sum method        val result = m1.sum                  // Displays output        println(result)          }}
22

Example #2:
// Scala program of sum()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 0)                  // Applying sum method        val result = m1.sum                  // Displays output        println(result)          }}
1

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
Scala Lists
Class and Object in Scala
Break statement in Scala
Scala String substring() method with example
Lambda Expression in Scala
Scala String replace() method with example
Operators in Scala
Scala | Arrays
WPF - Nesting of Layout

Nesting of layout means the use layout panel inside another layout, e.g. define stack panels inside a grid. This concept is widely used to take the advantages of multiple layouts in an application. In the following example, we will be using stack panels inside a grid.
Let’s have a look at the following XAML code.
<Window x:Class = "WPFNestingLayouts.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFNestingLayouts" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
	
   <Grid Background = "AntiqueWhite"> 
      <Grid.RowDefinitions> 
         <RowDefinition Height = "*" /> 
         <RowDefinition Height = "*" /> 
         <RowDefinition Height = "*" /> 
         <RowDefinition Height = "*" /> 
         <RowDefinition Height = "*" /> 
      </Grid.RowDefinitions> 
		
      <Grid.ColumnDefinitions> 
         <ColumnDefinition Width = "*" /> 
      </Grid.ColumnDefinitions> 
		
      <Label Content = "Employee Info" FontSize = "15"
         FontWeight = "Bold" Grid.Column = "0" Grid.Row = "0"/> 
			
      <StackPanel Grid.Column = "0" Grid.Row = "1" Orientation = "Horizontal"> 
         <Label Content = "Name"  VerticalAlignment = "Center" Width = "70"/> 
         <TextBox Name = "txtName" Text = "Muhammad Ali" VerticalAlignment = "Center"
            Width = "200">
         </TextBox> 
      </StackPanel>
		
      <StackPanel Grid.Column = "0" Grid.Row = "2" Orientation = "Horizontal"> 
         <Label Content = "ID" VerticalAlignment = "Center" Width = "70"/> 
         <TextBox Name = "txtCity" Text = "421" VerticalAlignment = "Center"
            Width = "50">
         </TextBox> 
      </StackPanel>
		
      <StackPanel Grid.Column = "0" Grid.Row = "3" Orientation = "Horizontal"> 
         <Label Content = "Age" VerticalAlignment = "Center" Width = "70"/> 
         <TextBox Name = "txtState" Text = "32" VerticalAlignment = "Center"
            Width = "50"></TextBox> 
      </StackPanel> 
		
      <StackPanel Grid.Column = "0" Grid.Row = "4" Orientation = "Horizontal"> 
         <Label Content = "Title" VerticalAlignment = "Center" Width = "70"/> 
         <TextBox Name = "txtCountry" Text = "Programmer" VerticalAlignment = "Center"
            Width = "200"></TextBox> 
      </StackPanel> 
		
   </Grid> 
	
</Window> 		  
When you compile and execute the above code, it will produce the following window.
We recommend that you execute the above example code and try other nesting layouts.

    31 Lectures 
     2.5 hours 

 Anadi Sharma

    30 Lectures 
     2.5 hours 

 Taurius Litvinavicius
 Print
 Add Notes
 Bookmark this page
Create a transition effect on hover pagination with CSS

To create a transition effect on hover pagination, use the transition property.
You can try to run the following code to add transition effect −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .demo {
            display: inline-block;
         }
         .demo a {
            color: red;
            padding: 5px 12px;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 2s;
         }
         .demo a.active {
            background-color: orange;
            color: white;
            border-radius: 5px;
         }
         .demo a:hover:not(.active) {
            background-color: yellow;
         }
      </style>
   </head>
   <body>
      <h2>Our Quizzes</h2>
      <div class = "demo">
         <a href = "prev.html"><</a>
         <a href = "quiz1.html">Quiz1</a>
         <a href = "quiz2.html">Quiz2</a>
         <a href = "quiz3.html">Quiz3</a>
         <a href = "quiz4.html" class="active">Quiz4</a>
         <a href = "next.html">></a>
      </div>
   </body>
</html>
Explain the accessing of structure variable in C language

The structure is a user-defined data type, which is used to store a collection of different data types of data.
The structure is similar to an array. The only difference is that an array is used to store the same data types whereas, the structure is used to store different data types.
The keyword struct is for declaring the structure.
Variables inside the structure are the members of the structure.
A structure can be declared as follows −
Struct structurename{
   //member declaration
};
Following is the C program for accessing a structure variable −
 Live Demo
struct book{
   int pages;
   float price;
   char author[20];
};
Accessing structure members in C
#include<stdio.h>
//Declaring structure//
struct{
   char name[50];
   int roll;
   float percentage;
   char grade[50];
}s1,s2;
void main(){
   //Reading User I/p//
   printf("enter Name of 1st student : ");
   gets(s1.name);
   printf("enter Roll number of 1st student : ");
   scanf("%d",&s1.roll);
   printf("Enter the average of 1st student : ");
   scanf("%f",&s1.percentage);
   printf("Enter grade status of 1st student : ");
   scanf("%s",s1.grade);
   //Printing O/p//
   printf("The name of 1st student is : %s\n",s1.name);
   printf("The roll number of 1st student is : %d\n",s1.roll);
   printf("The average of 1st student is : %f\n",s1.percentage);
   printf("The student 1 grade is : %s and percentage of %f\n",s1.grade,s1.percentage);
}
When the above program is executed, it produces the following result −
enter Name of 1st student: Bhanu
enter Roll number of 1st student: 2
Enter the average of 1st student: 68
Enter grade status of 1st student: A
The name of 1st student is: Bhanu
The roll number of 1st student is: 2
The average of 1st student is: 68.000000
The student 1 grade is: A and percentage of 68.000000
Python | Ways to convert list of ASCII value to string - GeeksforGeeks

29 Jun, 2019
Given a list of ASCII values, write a Python program to convert those values to their character and make a string. Given below are a few methods to solve the problem.
Method #1: Using Naive Method
# Python code to demonstrate # conversion of list of ascii values# to string  # Initialising listini_list = [71, 101, 101, 107, 115, 102,            111, 114, 71, 101, 101, 107, 115]   # Printing initial listprint ("Initial list", ini_list)  # Using Naive Methodres = ""for val in ini_list:    res = res + chr(val)  # Printing resultant stringprint ("Resultant string", str(res))
Output:
Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks
Method #2: Using map()
# Python code to demonstrate # conversion of list of ascii values# to string  # Initialising listini_list = [71, 101, 101, 107, 115, 102,            111, 114, 71, 101, 101, 107, 115]   # Printing initial listprint ("Initial list", ini_list)  # Using map and joinres = ''.join(map(chr, ini_list))  # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks
Method #3: Using join and list comprehension
# Python code to demonstrate # conversion of a list of ascii values# to string  # Initialising listini_list = [71, 101, 101, 107, 115, 102,            111, 114, 71, 101, 101, 107, 115]   # Printing initial listprint ("Initial list", ini_list)  # Using list comprehension and joinres = ''.join(chr(val) for val in ini_list)  # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to limit the number of results returned from grep in Linux?

In order to be able to grep limit the number of results returned from grep command in Linux, we must first understand what a grep command is and how to use it on Linux.
The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search.
Normally, the pattern that we are trying to search in the file is referred to as the regular expression.
grep [options] pattern [files]
While there are plenty of different options available to us, some of the most used are −
-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern
grep -rni "word" *
In the above command replace the “word” placeholder with
For that we make use of the command shown below −
grep -rni "func main()" *
The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well.
main.go:120:func main() {}

In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −
grep -s "func main()" *
In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command.
main.go:120:func main() {}
Now, consider that I have a .txt file and the content of the file looks something like this.
immukul@192 d2 % cat 2.txt
orange apple is great together
apple not great
is apple good
orange good apple not
Now I want to use the grep command for all the lines that contain both the words ‘apple’ and ‘orange’.
grep 'orange' 2.txt | grep 'apple'
immukul@192 d2 % grep 'orange' 2.txt | grep 'apple'
orange apple is great together
orange good apple not
Now that we can notice that two strings matched with our grep query, we can limit the result with the help of the command shown below
grep -m 1 'orange' 2.txt | grep 'apple
immukul@192 d2 % grep -m 1 'orange' 2.txt | grep 'apple'

orange apple is great together