code-rag-bench/online-tutorials huggingface dataset:
Cypress - Dropdown

The command select is used to work with static dropdown. In the html code, a dropdown has a select tag and the dropdown elements are represented by option tagname.
The dropdown related Cypress commands are as follows −
The command used to choose the option Cypress is as follows −
The command used to choose the option Cypress is as follows −
cy.get('select').select('Cypress')

The command that chooses options Tutorialspoint and JavaScript is as follows −
The command that chooses options Tutorialspoint and JavaScript is as follows −
cy.get('select').select(['Tutorialspoint', 'JavaScript'])

The command which can choose a value of a dropdown option along with options (to modify default characteristics) is as follows −
The command which can choose a value of a dropdown option along with options (to modify default characteristics) is as follows −
cy.get('select').select('option1', options )

The command that chooses the multiple values with options is as follows −
The command that chooses the multiple values with options is as follows −
cy.get('select').select(['option1', 'option2'], options)

The options which are available for the dropdown in Cypress are as follows −
log – Default value – true− This is used to turn on/off the console log.
log – Default value – true− This is used to turn on/off the console log.
timeout – Default value – defaultCommandTimeout(4000)− This is used to
provide the maximum wait time for the selection prior to throwing an error.
timeout – Default value – defaultCommandTimeout(4000)− This is used to
provide the maximum wait time for the selection prior to throwing an error.
force – Default value – false− This is used to enforce an action.
force – Default value – false− This is used to enforce an action.
Assertion can be applied to the select commands in Cypress.
Let us make an attempt to select the option India from the dropdown having value as 99 in the html code.
The implementation of the dropdown commands to select the option India in Cypress is explained below −
// test suite
describe('Tutorialspoint', function () {
   // it function to identify test
   it('Scenario 1', function (){
      // test step to launch a URL
      cy.visit("https://register.rediff.com/register/register.php")
      //select option India with value then verify with assertion
      cy.get('select[id="country"]').select('99').should('have.value', '99')
   })
})
Execution Results
The output is stated below −
The output shows that the Country dropdown selects the option India (in the html code,
this option is identified with the value as 99).

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
How to update a Python dictionary values?

Python’s in-built dictionary class has update() method. It takes another dictionary object as argument.
D1.update(D2)
D2 object is merged with D1. If D2 contains key that is already present in D1, its value is updated and if it is a new key, a new key-value pair is added. D1 will show updated contents.
>>> D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
>>> D2={"book":200, "scale":10}
>>> D1.update(D2)
>>> D1
{'pen': 25, 'pencil': 10, 'book': 200, 'sharpner': 5, 'eraser': 5, 'scale': 10}
Check for Integer Overflow in C++

The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than either values added. So for example,
unsigned int x, y;
unsigned int value = x + y;
bool overflow = value < x; // Alternatively "value < y" should also work
This is because if x and y are both unsigned ints, if added and they overflow, their values can't be greater than either of them as it would need to be greater than max possible unsigned int to be able to wrap around and get ahead of these values.
Another way is to try and access the Overflow flag in your CPU. Some compilers provide access to it which you could then test but this isn't standard.
Amazing stuff with system() in C / C++ - GeeksforGeeks

29 May, 2017
system() plays a very special role in executing Operating System Commands.By using this library function we can run all those terminal commands that our Operating System allows us to perform, just by using our C program.
Now, we will learn a very simple code to fetch the IP Address – to identify each computer using that very internet Protocol to communicate.Let’s see how.
Windows
Linux
// C program to get the IP Address of your // Windows system.  //<stdlib.h> library has system() library function.#include<stdlib.h>   int main(){   system("C:\\Windows\\System32\\ipconfig");}
// C program to get the IP Address of your// Linux system.  //<stdlib.h> library has system() library function.#include<stdlib.h>  int main(){   system("/sbin/ifconfig");}
Same output as you get on writing ipconfig in Windows or ifconfig in Linux on your terminal.
You are just using ipconfig/ifconfig on terminal but using C code isn't it cool.
Now we are looking at a code to ShutDown your system.
Windows
Linux
// C code to Shut Down your Windows system#include<stdlib.h>using namespace std;   int main(){   // Using the system() library.   system("C:\\WINDOWS\\System32\\shutdown /s");        // For Windows XP   // system("C:\\WINDOWS\\System32\\shutdown -s");}
// C program to get the IP Address of your// Linux system.  //<stdlib.h> library has system() library function.#include<stdlib.h>  int main(){   system("sudo shutdown now");}
An alert box appears telling you that your System will Shut Down.
Run these codes on your System and have fun. 
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Absolute Positioning in CSS

With absolute positioning, an element is positioned relative to the nearest positioned ancestor.
Let us now see an example −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div.demo1 {
   position: relative;
   color: white;
   background-color: orange;
   border: 2px dashed blue;
   width: 600px;
   height: 200px;
}
div.demo2 {
   position: absolute;
   color: white;
   background-color: orange;
   border: 2px dashed blue;
   top: 50px;
   right: 0;
   width: 300px;
   height: 100px;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<div class="demo1">position: relative;
<div class="demo2">
position: absolute;
</div>
</div>
<p>This is another demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
</body>
</html>
Google Charts - Material Line Chart

Following is an example of a material line chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used Line class to show material chart.
//classic chart
var chart = new google.visualization.LineChart(document.getElementById('container'));

//Material chart
var chart = new google.charts.Line(document.getElementById('container'));

googlecharts_line_material.htm
<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"></script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart','line']});  
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Month');
            data.addColumn('number', 'Tokyo');
            data.addColumn('number', 'New York');
            data.addColumn('number', 'Berlin');
            data.addColumn('number', 'London');
            data.addRows([
               ['Jan',  7.0, -0.2, -0.9, 3.9],
               ['Feb',  6.9, 0.8, 0.6, 4.2],
               ['Mar',  9.5,  5.7, 3.5, 5.7],
               ['Apr',  14.5, 11.3, 8.4, 8.5],
               ['May',  18.2, 17.0, 13.5, 11.9],
               ['Jun',  21.5, 22.0, 17.0, 15.2],
               
               ['Jul',  25.2, 24.8, 18.6, 17.0],
               ['Aug',  26.5, 24.1, 17.9, 16.6],
               ['Sep',  23.3, 20.1, 14.3, 14.2],
               ['Oct',  18.3, 14.1, 9.0, 10.3],
               ['Nov',  13.9,  8.6, 3.9, 6.6],
               ['Dec',  9.6,  2.5,  1.0, 4.8]
            ]);
            
            // Set chart options
            var options = {
               chart: {
                  title: 'Average Temperatures of Cities',
                  subtitle: 'Source: worldclimate.com'
               },   
               hAxis: {
                  title: 'Month',         
               },
               vAxis: {
                  title: 'Temperature',        
               }, 
               'width':550,
               'height':400      
            };

            // Instantiate and draw the chart.
            var chart = new google.charts.Line(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Angular 10 NgIf Directive - GeeksforGeeks

03 Jun, 2021
In this article, we are going to see what is NgIf in Angular 10 and how to use it.
The ngIf Directive in Angular10 is used to remove or recreate a portion of HTML element based on an expression. If the expression inside it is false then the element is removed and if it is true then the element is added to the DOM.
Syntax:
<li *ngIf='condition'></li>
NgModule: Module used by NgIf is:
CommonModule
 
Selectors:
[ngIf]
Approach: 
Create an Angular app to be used.
There is no need for any import for the NgIf to be used.
In app.component.ts define the variable for which condition is to be checked with ngIf directive.
In app.component.html use NgIf directive with conditions to be checked.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { Component, Inject } from '@angular/core';import { PLATFORM_ID } from '@angular/core';import { isPlatformWorkerApp } from '@angular/common';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ]})    export class AppComponent  {    myBool = true;  }
app.component.html
<div *ngIf = 'myBool'>Boolean is set to true</div>
Output:
Example 2:
Javascript
import { Component, Inject } from '@angular/core';import { PLATFORM_ID } from '@angular/core';import { isPlatformWorkerApp } from '@angular/common';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ]})export class AppComponent  {  variab = 10;}
app.component.html
<div *ngIf = 'variab==1; else multi'>{{variab}}</div>  <ng-template #multi>    {{variab *2}}  </ng-template>
Output:
Reference: https://angular.io/api/common/NgIf
Angular10
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Minimum Number of Arrows to Burst Balloons in C++

Suppose there are few spherical balloons spread in two-dimensional space. For each balloon, there are the start and end coordinates of the horizontal diameter. Start is always smaller than end. There will be at most 104 balloons. One arrow can be shot up exactly vertically from different points along the x-axis. A balloon whose position is xstart to xend bursts by an arrow shot at x if xstart = x = xend. There is no limit to the number of arrows that can be shot. Assume that an arrow once shot keeps travelling up infinitely. We have to find the minimum number of arrows that must be shot to burst all balloons. So if the input is like [[10,16],[2,8], [1,6], [7,12]], then the output will be 2. So if we shoot from x = 6, then it will burst [2,8] and [1,6], and another balloon from x = 11 to burst the rest.
To solve this, we will follow these steps −
Define a method called intersect() to check whether the positions are intersecting or not
Define a method called intersect() to check whether the positions are intersecting or not
Another method manipulate() to manipulate the range after taking the range of all intersecting balloons
Another method manipulate() to manipulate the range after taking the range of all intersecting balloons
The actual method is taking the balloon positions as pos
The actual method is taking the balloon positions as pos
sort the pos array based on the end positions
sort the pos array based on the end positions
n := number of balloons, if n is 0, then return 0
n := number of balloons, if n is 0, then return 0
currEnd := end position of the first entry of pos after soring
currEnd := end position of the first entry of pos after soring
cnt := 1
cnt := 1
for i in range 1 to n – 1if currEnd < start position of pos[i], then increase count by 1, and currEnd := ending position of pos[i]
for i in range 1 to n – 1
if currEnd < start position of pos[i], then increase count by 1, and currEnd := ending position of pos[i]
if currEnd < start position of pos[i], then increase count by 1, and currEnd := ending position of pos[i]
return count
return count
Let us see the following implementation to get better understanding
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool intersect(vector <int>& a, vector <int>& b){
      return a[1] >= b[0];
   }
   static bool cmp(vector <int>& a, vector <int>& b){
      return a[1] < b[1];
   }
   void manipulate(vector <int>& a, vector <int>& b){
      a[0] = min(a[0], b[0]);
      a[1] = max(a[1], b[1]);
   }
   int findMinArrowShots(vector<vector<int>>& points) {
      sort(points.begin(), points.end(), cmp);
      int n = points.size();
      if(!n) return 0;
      int currEnd = points[0][1];
      int cnt = 1;
      for(int i = 1; i < n; i++){
         if(currEnd < points[i][0]){
            cnt++;
            currEnd = points[i][1];
         }
      }
      return cnt;
   }
};
main(){
   vector<vector<int>> v = {{10,16},{2,8},{1,6},{7,12}};
   Solution ob;
   cout << (ob.findMinArrowShots(v));
}
[[10,16],[2,8],[1,6],[7,12]]
2
Caller ID Lookup using Python - GeeksforGeeks

08 Jul, 2021
Prerequisite : 
Beautiful soup
Requests module
In this article, we are going to see how we get Caller Id information using numverify API. Numverify offers a powerful tool to deliver phone number validation and information lookup in portable JSON format by Just making a request using a simple URL.
For the following program to work you must have an API key and to get one simply Click here.
Module needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install, type the following command in your terminal.
pip install bs4
requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install, type the following command in your terminal.
pip install requests
Approach:
Import module
Make a function for GET request
Pass the URL with existing API key, mobile number, and country code
Now retrieve the caller id information
Program:
Python3
# import moduleimport requestsimport pandas as pdfrom bs4 import BeautifulSoup # link for extract html data# Making a GET request     def getdata(url):    r=requests.get(url)    return r.text# API key# Enter your own API key instead of 'YOUR API KEY'api = 'YOUR API KEY' # number and country codenumber = '9852638787'country = 'IN' # pass Your API, number and country code# in getdata functionhtmldata=getdata('http://apilayer.net/api/validate?access_key='+api+'&number='+number+'&country_code='+country+'&format=1')soup = BeautifulSoup(htmldata, 'html.parser')print(soup)
Output:
{  
“valid”:true, 
 “number”:”919852638787′′,  
“local_format”:”09852638787′′, 
 “international_format”:”+919852638787′′,  
“country_prefix”:”+91′′,  
“country_code”:”IN”,  
“country_name”:”India (Republic of)”,  
“location”:”Bihar”,  
“carrier”:”Aircel Cellular Ltd”,  
“line_type”:”mobile”
 }  
saurabh1990aror
python-utility
Web-scraping
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
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
sum() function in Python
*args and **kwargs in Python
Starting and Stopping MySQL Server

Let us understand how MySQL server can be started and stopped on Linux and Windows −
On Linux, the start and stop can be done from the command line as shown below −
/etc/init.d/mysqld start
/etc/init.d/mysqld stop
/etc/init.d/mysqld restart
Some Linux types offer service command as well −
service mysqld start
service mysqld stop


service mysqld restart
service mysql start
service mysql stop
service mysql restart

Let us understand how it can be done on Windows −
Open ‘Run’ Window by using Win key + R
Open ‘Run’ Window by using Win key + R
Type ‘services.msc’
Type ‘services.msc’
Now search for MySQL service based on the version that is installed.
Now search for MySQL service based on the version that is installed.
Click on ‘stop’, ‘start’ or ‘restart’ the service option.
Click on ‘stop’, ‘start’ or ‘restart’ the service option.
Otherwise, the user can start/stop MySQL from the command prompt. It can be done as shown below −
C:\> "C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld"
C:\> "C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqladmin" −u root shutdown
Perl alarm Function

This function sets the "alarm," causing the current process to receive a SIGALRM signal in EXPR seconds. If EXPR is omitted, the value of $_ is used instead.
The actual time delay is not precise, since different systems implement the alarm functionality differently. The actual time may be up to a second more or less than the requested value. You can only set one alarm timer at any one time. If a timer is already running and you make a new call to the alarm function, the alarm timer is reset to the new value. A running timer can be reset without setting a new timer by specifying a value of 0.
Following is the simple syntax for this function −
alarm EXPR

alarm

This function returns Integer value ie. number of seconds remaining for previous timer.
Following is the example code showing its basic usage −
#!/usr/bin/perl

eval {
   local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
   alarm $timeout;
   $nread = sysread SOCKET, $buffer, $size;
   alarm 0;
};
if ($@) {
   die unless $@ eq "alarm\n";   # propagate unexpected errors
      # timed out
} else {
   # didn't
}

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Go - function closure

Go programming language supports anonymous functions which can acts as function closures. Anonymous functions are used when we want to define a function inline without passing any name to it.
In our example, we created a function getSequence() which returns another function. The purpose of this function is to close over a variable i of upper function to form a closure. For example −
package main

import "fmt"

func getSequence() func() int {
   i:=0
   return func() int {
      i+=1
      return i  
   }
}

func main(){
   /* nextNumber is now a function with i as 0 */
   nextNumber := getSequence()  

   /* invoke nextNumber to increase i by 1 and return the same */
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   
   /* create a new sequence and see the result, i is 0 again*/
   nextNumber1 := getSequence()  
   fmt.Println(nextNumber1())
   fmt.Println(nextNumber1())
}
When the above code is compiled and executed, it produces the following result −
Puzzle 37 | (Maximum run in cricket)

11 May, 2021
Question: In a one day international cricket match, considering no extras(no wides, no ‘no’ balls, etc.) and no overthrows.
What is the maximum number of runs that a batsman can score in an ideal case ?
Note:”Here we assume ideal and little practical scenario. We assume that batsman can not run for more than 3 runs in a ball, as otherwise there is no limit, he can run infinite runs(theoretically) in a ball, as far as opposite team does not catch the ball.”
Answer:
49*(6*5+3)+(6*6)= 1653
From Over 1 to 49:
1st ball:- 6 runs(hit six)
2nd ball:- 6 runs(hit six)
3rd ball:- 6 runs(hit six)
4th ball:- 6 runs(hit six)
5th ball:- 6 runs(hit six)
6th ball:- 3 runs(took 3 runs between the wickets and take back the strike)
= >49*(6*5+3)
50th Over:
Hit six sixes in a row.
= >6*6
This article is contributed by Vikash Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Puzzles
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Top 20 Puzzles Commonly Asked During SDE Interviews
Puzzle 18 | (Torch and Bridge)
Puzzle 8 | (Find the Jar with contaminated pills)
Puzzle 16 | (100 Doors)
Puzzle 11 | (1000 Coins and 10 Bags)
Puzzle 10 | (A Man with Medical Condition and 2 Pills)
Puzzle 13 | (100 Prisoners with Red/Black Hats)
Container with Most Water
Puzzle 19 | (Poison and Rat)
Powershell - Compare-Object Cmdlet

Compare-Object cmdlet can be used to compare two objects.
In these examples, we're see the Compare-Object cmdlet in action.
In this example, first we've a file test.txt in D:\temp\test with content "Welcome to TutorialsPoint.Com" and test1.txt with content "Hello World!" and "Welcome to TutorialsPoint.Com" in two lines.
Compare the files. Type the following command in PowerShell ISE Console. Common line(s) will be displayed.
Compare-Object -ReferenceObject $(Get-Content D:\temp\test\test.txt) -DifferenceObject $(Get-Content D:\temp\test\test1.txt)
You can see following output in PowerShell console.
InputObject                        SideIndicator                                  
-----------                        -------------                                  
Hello World!                       => 

Compare the content of files. Type the following command in PowerShell ISE Console. All line(s) with indicator will be displayed.
Type the following command in PowerShell ISE Console
Compare-Object -ReferenceObject $(Get-Content D:\temp\test\test.txt) -DifferenceObject $(Get-Content D:\temp\test\test1.txt) -IncludeEqual
You can see following output in PowerShell console.
InputObject                                      SideIndicator                                  
-----------                                      -------------                                  
Welcome to TutorialsPoint.Com                    ==                                             
Hello World!                                     =>
How to mount the ISO file using PowerShell?

To mount the ISO file in Windows using PowerShell, we can use the Mount−DiskImage command. The below command will mount the image file stored at the C:\ISO location.
Mount−DiskImage −ImagePath "C:\ISOs\Windows_Server_2016_Datacenter_EVAL_en−us_14393_refresh (1).ISO"
Attached : True
BlockSize : 0
DevicePath : \\.\CDROM0
FileSize : 6972221440
ImagePath : C:\ISOs\Windows_Server_2016_Datacenter_EVAL_en-us_14393_refresh (1).ISO
LogicalSectorSize : 2048
Number : 0
Size : 6972221440
StorageType : 1
PSComputerName :
You can also check from Windows Explorer that the disk is mounted.
To mount on the remote computer, we can use CIMSession as a remote session and mount the disk.
$sess = New−CimSession −ComputerName Labmachine2k12
Mount−DiskImage −CimSession $sess −ImagePath
F:\Windows_Server_2016_Datacenter.iso
In the above example, Disk Image file ISO will be mounted on the remote computer LabMachine2k12 which is available on the same server (LabMachine2k12) on the F: path.
How to include percentage in pivot table in Pandas?

24 Jan, 2021
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas.
Pivot table is used to summarize data which includes various statistical concepts. To calculate the percentage of a category in a pivot table we calculate the ratio of category count to the total count. Below are some examples which depict how to include percentage in a pivot table:
Example 1:
In the figure below, the pivot table has been created for the given dataset where the gender percentage has been calculated.
Python3
# importing pandas libraryimport pandas as pd  # creating dataframedf = pd.DataFrame({'Name': ['John', 'Sammy', 'Stephan', 'Joe', 'Emily', 'Tom'],                   'Gender': ['Male', 'Female', 'Male',                              'Female', 'Female', 'Male'],                   'Age': [45, 6, 4, 36, 12, 43]})print("Dataset")print(df)print("-"*40)  # categorizing in age groupsdef age_bucket(age):    if age <= 18:        return "<18"    else:        return ">18"  df['Age Group'] = df['Age'].apply(age_bucket)  # calculating gender percentagegender = pd.DataFrame(df.Gender.value_counts(normalize=True)*100).reset_index()gender.columns = ['Gender', '%Gender']df = pd.merge(left=df, right=gender, how='inner', on=['Gender'])  # creating pivot tabletable = pd.pivot_table(df, index=['Gender', '%Gender', 'Age Group'],                        values=['Name'], aggfunc={'Name': 'count',})  # display tableprint("Table")print(table)
Output:
Example 2:
Here is another example which depicts how to calculate the percentage of a variable to its sum total in a particular column:
Python3
# importing required librariesimport pandas as pdimport matplotlib.pyplot as plt  # creating dataframedf = pd.DataFrame({    'Name': ['John', 'Emily', 'Smith', 'Joe'],    'Gender': ['Male', 'Female', 'Male', 'Female'],    'Salary(in $)': [20, 40, 35, 28]})  print("Dataset")print(df)print("-"*40)  # creating pivot tabletable = pd.pivot_table(df, index=['Gender', 'Name'])  # calculating percentagetable['% Income'] = (table['Salary(in $)']/table['Salary(in $)'].sum())*100  # display tableprint("Pivot Table")print(table)
Output:
Picked
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
C/C++ Struct vs Class

In C++ the structure and class are basically same. But there are some minor differences. These differences are like below.
The class members are private by default, but members of structures are public. Let us see these two codes to see the differences.
The class members are private by default, but members of structures are public. Let us see these two codes to see the differences.
#include <iostream>
using namespace std;
class my_class {
   int x = 10;
};
int main() {
   my_class my_ob;
   cout << my_ob.x;
}
This program will not be compiled. It will generate compile time error for
the private data member.
#include <iostream>
using namespace std;
struct my_struct {
   int x = 10;
};
int main() {
   my_struct my_ob;
   cout << my_ob.x;
}
10
When we derive a structure from a class or structure, the default access specifier of that base class is public, but when we deriving a class the default access specifier is private.
When we derive a structure from a class or structure, the default access specifier of that base class is public, but when we deriving a class the default access specifier is private.
#include <iostream>
using namespace std;
class my_base_class {
   public:
   int x = 10;
};
class my_derived_class : my_base_class {
};
int main() {
   my_derived_class d;
   cout << d.x;
}
This program will not be compiled. It will generate compile time error that the variable x of the base class is inaccessible
#include <iostream>
using namespace std;
class my_base_class {
   public:
   int x = 10;
};
struct my_derived_struct : my_base_class {
};
int main() {
   my_derived_struct d;
   cout << d.x;
}
10
Program to calculate area and perimeter of Trapezium

Trapezium is a type of quadrilateral that has at least one pair of side parallel to each other. Area and perimeter of a trapezium can be found using the below formula,
Perimeter = sum of all sides
Area = 1⁄2 x (sum of the lengths of the parallel sides) x perpendicular distance between parallel sides
Code logic − The code will use 5 variables in as all sides of trapezium and one for the perpendicular distance between the two parallel side. For the area variable calculation we will take a float variable that will be initialised with the value. To calculate it we will use the formula “ 1⁄2 x (sum of length of parallel sides) x perpendicular distance between parallel sides ”. For the perimeter calculation a variable will be assigned the expression, “(Sum of all sides)”.
Below code displays the program to calculate the area and perimeter of a trapezium,
 Live Demo
#include <stdio.h>
int main() {
   int a = 2 , b = 3 , c = 5 , d = 4, h = 5;
   float area, perimeter;
   printf("The sides of trapezium are %d , %d , %d , %d \n", a,b,c,d);
   printf("Distance between two parallel sides is %d \n", h);
   perimeter = a+b+c+d;
   area = 0.5 * (a + b) * h ;
   printf("Perimeter of the trapezium is %.1f\n", perimeter);
   printf("Area of the trapezium is: %.3f", area);
   return 0;
}
The sides of trapezium are 2 , 3 , 5 , 4
Distance between two parallel sides is 5
Perimeter of the trapezium is 14.0
Area of the trapezium is: 12.500
Check if a path has a file name extension in C# - GeeksforGeeks

04 Apr, 2019
Path.HasExtension Method is used to check whether the specified path has a file name extension or not.This method will start the searching for a period (.) followed by at least one character from the end of the path. If this pattern is found before a DirectorySeparatorChar, AltDirectorySeparatorChar, or VolumeSeparatorChar character is encountered, this method returns true.
Syntax:
public static bool HasExtension (string path);
Here, path is the specified path to search for an extension.
Returns: This method will return true if the characters that follow the last directory separator (\\ or /) or volume separator (:) in the path include a period (.) followed by one or more characters; otherwise, false.
Exception: This method will give ArgumentException if the path contains one or more of the invalid characters defined in GetInvalidPathChars().
Examples:
Input : 
string strPath1 = "C:// myfiles//ref//file1.txt";
string strPath2 = "C:// myfiles//ref//file2";

// checking for the extension
Path.HasExtension(strPath1);
Path.HasExtension(strPath2);

Output :

true
false

// C# program to check whether// a file have an extension or notusing System;using System.IO;  namespace Geeks {  class GFG {      // Main Method    static void Main(string[] args)    {          // taking two paths        string strPath1 = "C:// myfiles// ref// file1.txt";        string strPath2 = "C:// myfiles// ref// file2";          // checking whether the file         // has an extension or not        if (Path.HasExtension(strPath1))            Console.WriteLine("{0} have an extension...", strPath1);        else            Console.WriteLine("{0} don't have an extension...", strPath1);          // checking whether the file         // has an extension or not        if (Path.HasExtension(strPath2))            Console.WriteLine("{0} have an extension...", strPath2);        else            Console.WriteLine("{0} don't have an extension...", strPath2);          Console.ReadLine();    }}}
C:// myfiles// ref// file1.txt have an extension...
C:// myfiles// ref// file2 don't have an extension...

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.hasextension?view=netframework-4.7.2
CSharp-method
CSharp-Path-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
Common Language Runtime (CLR) in C#
C# | Method Overloading
How to get a specific object from array of objects inside specific MongoDB document?

To get specific object from array of objects, use positional operator($). Let us first create a collection with documents −
> db.getASpecificObjectDemo.insertOne(
...   {
...      _id :1,f
...      "CustomerName" : "Larry",
...      "CustomerDetails" : {
...         "CustomerPurchaseDescription": [{
...            id :100,
...            "ProductName" : "Product-1",
...            "Amount":10000
...         },{
...               id :101,
...               "ProductName" : "Product-2",
...               "Amount":10500
...            },
...            {
...               id :102,
...               "ProductName" : "Product-3",
...               "Amount":10200
...            }
...         ]
...      }
...  }
... );
{ "acknowledged" : true, "insertedId" : 1 }
Following is the query to display all documents from a collection with the help of find() method −
> db.getASpecificObjectDemo.find().pretty();
This will produce the following output −
{
   "_id" : 1,
   "CustomerName" : "Larry",
   "CustomerDetails" : {
      "CustomerPurchaseDescription" : [
           {
             "id" : 100,
             "ProductName" : "Product-1",
             "Amount" : 10000
           },
           {
             "id" : 101,
             "ProductName" : "Product-2",
             "Amount" : 10500
           },
           {
             "id" : 102,
             "ProductName" : "Product-3",
             "Amount" : 10200
           }
      ]
   }
}
Following is the query to get a specific object from array of objects inside specific MongoDB document −
> db.getASpecificObjectDemo.find({_id:1, "CustomerDetails.CustomerPurchaseDescription.id":101},{_id:0, "CustomerDetails.CustomerPurchaseDescription.$":1});
This will produce the following output −
{ "CustomerDetails" : { "CustomerPurchaseDescription" : [ { "id" : 101, "ProductName" : "Product-2", "Amount" : 10500 } ] } }
C# Linq First() Method

Use the First() method to get the first element from an array.
Firstly, set an array.
int[] arr = {20, 40, 60, 80 , 100};
Now, use the Queryable First() method to return the first element.
arr.AsQueryable().First();
The following is the entire example.
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
class Program {
   static void Main() {
      int[] arr = {20, 40, 60, 80 , 100};
      // getting the first element
      int res = arr.AsQueryable().First();
      Console.WriteLine(res);
   }
}
20
C++ program for multiplication of array elements

Given with an array of integer elements and the task is to multiply the elements of an array and display it.
Input-: arr[]={1,2,3,4,5,6,7}
Output-: 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5040
Input-: arr[]={3, 4,6, 2, 7, 8, 4}
Output-: 3 x 4 x 6 x 2 x 7 x 8 x 4 = 32256
Approach used in the below program is as follows −
Initialize temporary variable to store the final result with 1
Start loop from 0 to n where n is the size of an array
Keep multiplying the value of temp with arr[i] for final result
Display the value of temp which will be resultant value
Given below is the example of multiplying the inputs and generating required output
Start
Step 1-> Declare function for multiplication of array elements
   int multiply(int arr[], int len)
      set int i,temp=1
         Loop For i=0 and i<len and i++
            Set temp=temp*arr[i]
         End
         return temp
step 2-> In main()
   Declare int arr[]={1,2,3,4,5,6,7}
      Set int len=sizeof(arr)/sizeof(arr[0])
      Set int value = multiply(arr,len)
      Print value
Stop
 Live Demo
#include<stdio.h>
//function for multiplication
int multiply(int arr[], int len) {
   int i,temp=1;
   for(i=0;i<len;i++) {
      temp=temp*arr[i];
   }
   return temp;
}
int main() {
   int arr[]={1,2,3,4,5,6,7};
   int len=sizeof(arr)/sizeof(arr[0]);
   int value = multiply(arr,len);
   printf("value of array elements after multiplication : %d",value);
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
value of array elements after multiplication : 5040
How to perform descending order sort in MongoDB?

To sort in ascending order, the syntax is as follows −
db.yourCollectionName.find().sort({yourField:1});
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.sortingDemo.insertOne({"Value":100});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f8e2ed3c9d04998abf006")
}
> db.sortingDemo.insertOne({"Value":1});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f8e31d3c9d04998abf007")
}
> db.sortingDemo.insertOne({"Value":150});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f8e34d3c9d04998abf008")
}
> db.sortingDemo.insertOne({"Value":250});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f8e37d3c9d04998abf009")
}
> db.sortingDemo.insertOne({"Value":5});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f8e3bd3c9d04998abf00a")
}
> db.sortingDemo.insertOne({"Value":199});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f8e3ed3c9d04998abf00b")
}
> db.sortingDemo.insertOne({"Value":243});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f8e44d3c9d04998abf00c")
}
> db.sortingDemo.insertOne({"Value":290});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8f8e48d3c9d04998abf00d")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.sortingDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8f8e2ed3c9d04998abf006"), "Value" : 100 }
{ "_id" : ObjectId("5c8f8e31d3c9d04998abf007"), "Value" : 1 }
{ "_id" : ObjectId("5c8f8e34d3c9d04998abf008"), "Value" : 150 }
{ "_id" : ObjectId("5c8f8e37d3c9d04998abf009"), "Value" : 250 }
{ "_id" : ObjectId("5c8f8e3bd3c9d04998abf00a"), "Value" : 5 }
{ "_id" : ObjectId("5c8f8e3ed3c9d04998abf00b"), "Value" : 199 }
{ "_id" : ObjectId("5c8f8e44d3c9d04998abf00c"), "Value" : 243 }
{ "_id" : ObjectId("5c8f8e48d3c9d04998abf00d"), "Value" : 290 }
Here is the query to get result in descending order. The query is as follows:
> db.sortingDemo.find().sort({Value:-1});
The following is the output −
{ "_id" : ObjectId("5c8f8e48d3c9d04998abf00d"), "Value" : 290 }
{ "_id" : ObjectId("5c8f8e37d3c9d04998abf009"), "Value" : 250 }
{ "_id" : ObjectId("5c8f8e44d3c9d04998abf00c"), "Value" : 243 }
{ "_id" : ObjectId("5c8f8e3ed3c9d04998abf00b"), "Value" : 199 }
{ "_id" : ObjectId("5c8f8e34d3c9d04998abf008"), "Value" : 150 }
{ "_id" : ObjectId("5c8f8e2ed3c9d04998abf006"), "Value" : 100 }
{ "_id" : ObjectId("5c8f8e3bd3c9d04998abf00a"), "Value" : 5 }
{ "_id" : ObjectId("5c8f8e31d3c9d04998abf007"), "Value" : 1 }
How do you limit an array sub-element in MongoDB?

You can use $slice operator to limit an array. Let us create a collection with documents. Following is the query
> db.limitAnArrayDemo.insertOne(
...    {
...       _id: 101,
...       "PlayerName": "Bob",
...       "PlayerDetails": {Age:23,isStudent:true},
...       "PlayerGameScores": [234,5767,58,67,78,90,1002,576,68,45,23,45,678,89,78 ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method
> db.limitAnArrayDemo.find().pretty();
This will produce the following output
{
   "_id" : 101,
   "PlayerName" : "Bob",
   "PlayerDetails" : {
      "Age" : 23,
      "isStudent" : true
   },
   "PlayerGameScores" : [
      234,
      5767,
      58,
      67,
      78,
      90,
      1002,
      576,
      68,
      45,
      23,
      45,
      678,
      89,
      78
   ]
}
Following is the query to limit an array sub-element in MongoDB. The below query will display only 10 elements from the last
> db.limitAnArrayDemo.find({}, {PlayerName:1, PlayerDetails: 1, PlayerGameScores:{$slice: -10}}).pretty();
Following is the output displaying 10 PlayerGameScores
{
   "_id" : 101,
   "PlayerName" : "Bob",
   "PlayerDetails" : {
      "Age" : 23,
      "isStudent" : true
   },
   "PlayerGameScores" : [
      90,
      1002,
      576,
      68,
      45,
      23,
      45,
      678,
      89,
      78
   ]
}
How to find a file using Python?

To find a file within a directory using python, you can walk the directory tree using os.walk and find the file as follows −
import os
def find_file(file_name, directory_name):
    files_found = []
    for path, subdirs, files in os.walk(directory_name):
        for name in files:
            if(file_name == name):
                file_path = os.path.join(path,name)
                files_found.append(file_path)
    return files_found
find_file('my_file.txt', 'my_folder')
When you run this script and have folder structure like −
my_folder/
    another_folder/
        my_file
        another_file
    hello.py
    my_file
You'll get the output −
['/my_folder/another_folder/my_file', '/my_folder/my_file']
Python Slicing | Extract ‘k’ bits from a given position - GeeksforGeeks

12 Sep, 2018
How to extract ‘k’ bits from a given position ‘p’ in a number?
Examples:
Input : number = 171
             k = 5 
             p = 2
Output : The extracted number is 21
171 is represented as 10101011 in binary,
so, you should get only 10101 i.e. 21.

Input : number = 72
            k = 5 
            p = 1
Output : The extracted number is 8
72 is represented as 1001000 in binary,
so, you should get only 01000 i.e 8.

We have existing solution for this problem please refer Extract ‘k’ bits from a given position in a number link. We can solve this problem quickly in python using slicing. Approach is simple,
Convert given number into it’s binary using bin() function and remove first two characters ‘0b’ from it, because bin function appends ‘0b’ as prefix in output binary string.We need to start extracting k bits from starting position p from right, that means end index of extracted sub-string will be end = (len(binary) – p) and start index will be start = end – k + 1 of original binary string.Convert extracted sub-string into decimal again.
Convert given number into it’s binary using bin() function and remove first two characters ‘0b’ from it, because bin function appends ‘0b’ as prefix in output binary string.
We need to start extracting k bits from starting position p from right, that means end index of extracted sub-string will be end = (len(binary) – p) and start index will be start = end – k + 1 of original binary string.
Convert extracted sub-string into decimal again.
# Function to extract ‘k’ bits from a given# position in a number  def extractKBits(num,k,p):       # convert number into binary first     binary = bin(num)       # remove first two characters     binary = binary[2:]       end = len(binary) - p     start = end - k + 1       # extract k  bit sub-string     kBitSubStr = binary[start : end+1]       # convert extracted sub-string into decimal again     print (int(kBitSubStr,2))  # Driver programif __name__ == "__main__":    num = 171    k = 5    p = 2    extractKBits(num,k,p)        
Output:
21

Bit Magic
Python
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Write an Efficient Method to Check if a Number is Multiple of 3
Reverse actual bits of the given number
Program to find parity
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Java - Encapsulation

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of 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.
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
Provide public setter and getter methods to modify and view the variables values.
Following is an example that demonstrates how to achieve Encapsulation in Java −
/* File name : EncapTest.java */
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;
   }
}
The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters.
The variables of the EncapTest class can be accessed using the following program −
/* File name : RunEncap.java */
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());
   }
}
This will produce the following result −
Name : James Age : 20

The fields of a class can be made read-only or write-only.
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
A class can have total control over what is stored in its fields.

    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page