code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.figure.Figure.get_size_inches() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The get_size_inches() method figure module of matplotlib library is used to get the current size of the figure in inches.
Syntax: get_size_inches(self)
Parameters: This method does not accept any parameters.
Returns: This method return size (width, height) of the figure in inches.
Below examples illustrate the matplotlib.figure.Figure.get_size_inches() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np      fig = plt.figure()       ax = Subplot(fig, 111) fig.add_subplot(ax)    w = fig.get_size_inches()ax.text(0.2, 0.5,        "Value Return by get_size_inches() : "        + str(w),        fontweight ="bold")    fig.canvas.draw()  fig.suptitle('matplotlib.figure.Figure.get_size_inches()\ function Example', fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np        fig = plt.figure(edgecolor = "red", figsize =(7, 6))        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])     xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))    w = fig.get_size_inches()ax.text(1.5, 0,        "Value Return by get_size_inches() : "         + str(w),        fontweight ="bold")     fig.canvas.draw()  fig.suptitle('matplotlib.figure.Figure.get_size_inches() \function Example', fontweight ="bold")   plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Beep() function in C with Examples - GeeksforGeeks

22 Nov, 2020
The Beep function in C is used to make a Beep sound. It generates a tone on the speaker. The function is synchronous, i.e. it waits and doesn’t return to its caller function until the sound is finished. It can be very useful during the Debugging process for finding errors.Header File:  
#include <windows.h>

Syntax:  
BEEP(x, y)

Parameters: This method accepts two parameters:  
x: which is the frequency of sound
y: which is the duration in ms till sound is ON.
Return Type:  
If the function produces the sound then it return any nonzero value.
If the function doesn’t produces the sound then it returns zero.
Below is the illustration of the BEEP() function:Program 1: 
C
// C program to illustrate BEEP() function #include <stdio.h>#include <windows.h> // Driver Codeint main(){     // Function that beeps a sound of    // frequency 750 for 0.8 sec    BEEP(750, 800);     getch();    return 0;}
Note: The program won’t produce the sound in online IDE. Please try to run it in offline compilers.Program 2: 
C
// C program to play song Jingle Bell// using the BEEP() function #include <stdio.h>#include <windows.h> // Driver Codeint main(){    int x;     // Loop for sound Jingle    for (x = 0; x < 2; x++) {        Beep(523, 500);    }     // sound Bell    Beep(523, 800);     Sleep(200);     // Loop for sound Jingle    for (x = 0; x < 2; x++) {        Beep(523, 500);    }     // sound Bell    Beep(523, 800);     // Sound for rest of the tone    Sleep(200);     Beep(523, 500);     Sleep(50);     Beep(659, 400);     Sleep(50);     Beep(440, 400);     Sleep(50);     Beep(494, 400);     Sleep(50);     Beep(523, 750);     Sleep(400);     Beep(600, 400);     Sleep(100);     Beep(600, 350);     Sleep(200);     Beep(600, 300);     Sleep(150);     Beep(600, 250);     Sleep(150);     Beep(600, 150);     Sleep(150);     Beep(550, 250);     Sleep(150);     Beep(555, 350);     Sleep(50);     Beep(555, 200);    Sleep(150);     Beep(555, 200);     Sleep(150);     Beep(690, 200);     Sleep(150);     Beep(690, 200);     Sleep(150);     Beep(610, 200);     Sleep(150);     Beep(535, 160);     Sleep(100);     Beep(500, 150);         Beep(500, 50);     Sleep(200);     Beep(700, 200);     return 0;}
jake1924
Advanced Computer Subject
C Language
C Programs
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
Principal Component Analysis with Python
Arrays in C/C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Substring in C++
Shift() vs pop() Method in JavaScript - GeeksforGeeks

18 Jan, 2021
JavaScript shift() and pop() methods are used to remove an element from an array. But there is a little difference between them. Shift() method removes the first element and whereas the pop() method removes the last element from an array. 
The Shift() returns the removed first element of the array. If the array is empty then this function returns undefined whereas the pop() method turns the removed element array. If the array is empty, then this function returns undefined.
Both the method is used for reducing the length of the array by 1.
Both shift() and pop() are the in-built methods of the object array.
Both methods will change the original array.
Example: Below is an example of the array shift() method. 
Javascript
<script> function func() {           // Original array     var array = ["GFG", "Geeks", "for", "Geeks"];       // Checking for condition in array     var value = array.shift();       document.write(value);     document.write("<br />");     document.write(array); }   func(); </script> 
Output: 
GFG
Geeks, for, Geeks
Example 2: Below is the example of the array pop() method.
Javascript
<script>     function func() {         var arr = ['GFG', 'gfg', 'g4g', 'GeeksforGeeks'];               // Popping the last element from the array         document.write(arr.pop());    }     func(); </script>                 
Output:  
GeeksforGeeks
Supported browsers:
Google Chrome
Microsoft Edge
Mozilla Firefox
Safari
Opera
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Lodash or Underscore - pick, pickBy, omit, omitBy - GeeksforGeeks

30 Jun, 2020
Javascript is Everywhere. The Javascript is used widely and it’s not limited to just only in your web browser but also widely used in the server-side as well. JavaScript is used by 95% of all the websites.
Lodash or Underscore makes coding in Javascript much easier & also makes our code minimal, it works with arrays, numbers, objects, strings, etc.
We can use Lodash basically with any JS based library or framework, for instance w/ Angular, React, VueJs, Node.Js, Vanilla JS, etc.
Lodash’s modular methods are great for:
Iterating arrays, objects, & stringsManipulating & testing valuesCreating composite functions
Iterating arrays, objects, & strings
Manipulating & testing values
Creating composite functions
Let’s go through very basic and most used Lodash methods which makes our day to day life easier & increase readability of our code.
1. pickBy
2. pick
3. omitBy
4. omit and so on..
Pick and Omit are contrary of each other, as the name describes omit is used to omit/exclude parameters from the object as per our needs on the other hand pick is used to pick/include elements defined.
Examples:
let geeksforgeeks = {
   "name" : "geeksforgeeks",
   "location" : "NCR",
   "vacancies" : null,
   "amenities" : ['free_breakfast','health_insurance'],
   "interview_process" : ["DSA","Technical","HR"]
};




Now, to get only valid values from your object i.e., except null & undefined
/* now validGFG object contains only 
valid (!null & !undefined) key-value pairs. */
let validGFG = _.pickBy(geeksforgeeks, 
   v => !_.isUndefined(v) && !_.isNull(v));




To get all key value pairs from our validGFG object except some, we can simply do this :
// this object contains all key-value pairs except amenities.
let geeksInfoExceptAmenities = _.omit(validGFG, ['amenities']);




We can do one step further to eliminate all the arrays/string(s)/number/etc. from our object,
/* this object will contain only name & location just
because we omitted all the array type from our object. */
let geeksInfoExceptInsideArrays = _.omitBy(validGFG, _.isArray);




To get some specific key-value pairs,
// this object contains name & location only.
let geeksNameAndLocation = _.pick(validGFG, ['name','location']);




We can use many combinations of above stated functions & handle our arrays, objects and much more quite easily.
For much more, you can go through docs of Lodash.
JavaScript - Underscore.js
JavaScript-Lodash
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
How to Use the JavaScript Fetch API to Get Data?
Node.js | fs.writeFileSync() Method
JavaScript | Promises
Set the value of an input field in JavaScript
Form validation using HTML and JavaScript
Python open() Function

13 Sep, 2021
The python open() function is used to open() internally stored files. It returns the contents of the file as python objects.
Syntax: open(file_name, mode) 
Parameters:
file_name: This parameter as the name suggests, is the name of the file that we want to open.
mode: This parameter is a string that is used to specify the mode in which the file is to be opened. The following strings can be used to activate a specific mode:
“r”: This string is used to read(only) the file. It is passed as default if no parameter is supplied and returns an error if no such file exists.
“w”: This string is used for writing on/over the file. If the file with the supplied name doesn’t exist, it creates one for you.
“a”: This string is used to add(append) content to an existing file. If no such file exists, it creates one for you.
“x”: This string is used to create a specific file.
“b”: This string is used when the user wants to handle the file in binary mode. This is generally used to handle image files.
“t”: This string is used to handle files in text mode. By default, the open() function uses the text mode.
The following code can be used to create a file. Here we will be creating a text file named”geeksforgeeks.txt”.
Python3
created_file = open("geeksforgeeks.txt","x")  # Check the fileprint(open("geeksforgeeks.txt","r").read() == False)
Output:
True
Here we will write the following string to the geeksforgeeks.txt file that we just created and read the same file again.
Geeksforgeeks is best for DSA
The below code can be used for the same:
Python3
my_file = open("geeksforgeeks.txt", "w")my_file.write("Geeksforgeeks is best for DSA")my_file.close()  #let's read the contents of the file nowmy_file = open("geeksforgeeks.txt","r")print(my_file.read())
Output:
Geeksforgeeks is best for DSA
Here we will append the following text to the geeksforgeeks.txt file and again read the same:
Python3
my_file = open("geeksforgeeks.txt","a")my_file.write("..>>Visit geeksforgeeks.org for more!!<<..")my_file.close()  # reading the filemy_file = open("geeksforgeeks.txt","r")print(my_file.read())
Output:
Geeksforgeeks is best for DSA..>>Visit geeksforgeeks.org for more!!<<..
Note: The difference between “w” and “r” is that one overrides over the existing content whereas the latter adds content to the existing file keeping the content intact.
Picked
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to refresh entire application when date is changed in angular 9 ?

17 Dec, 2020
In this example, we will see how to refresh the application when the date is changed in angularJS.
Approach:
First, we need to write the code for displaying the date picker in an HTML file.
We can achieve this by giving the input type as the date.
After completing the input type, we need to declare a function on the ‘onchange’ event so that whenever the date is changed or modified the application will be reloaded.
After declaring the function in the HTML file we need to write the function implementation in the ts file.
In the function implementation, we can use the window property of DOM, and we can call the reload function so that the application is reloaded.
After completing the above steps, serve or start the project.
Code Implementation:
app.component.ts:
Javascript
import { Component } from '@angular/core';  @Component({    selector: 'my-app',    templateUrl: './app.component.html',    styleUrls: ['./app.component.css']})export class AppComponent {    constructor() { }      // Function to reload the application    refreshPage() {        window.location.reload();    }}
app.component.html:
HTML
<h1>Hello User !</h1>  <p>Change the date to refresh the application.</p>  <input type="date" (change)="refreshPage()">
app.module.ts:
Javascript
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { AppComponent } from './app.component';  @NgModule({    imports:        [            BrowserModule,            FormsModule        ],    declarations:        [            AppComponent        ],    bootstrap:        [            AppComponent        ]})  export class AppModule { }
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to setup 404 page in angular routing ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
C++ Vector Library - insert() Function

The C++ function std::vector::insert() extends vector by inserting new element at position in container. Reallocation happens if there is need of more space.
This function increases container size by one.
Following is the declaration for std::vector::insert() function form std::vector header.
iterator insert (iterator position, const value_type& val);

iterator insert (const_iterator position, const value_type& val);

position − Index in the vector where new element to be inserted.
position − Index in the vector where new element to be inserted.
val − Value to be assigned to newly inserted element.
val − Value to be assigned to newly inserted element.
Returns an iterator which points to the newly inserted element.
Linear i.e. O(n)
The following example shows the usage of std::vector::insert() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v = {3, 4, 5};

   auto it = v.insert(v.begin(), 2);
   v.insert(it, 1);

   for (auto it = v.begin(); it != v.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
How to find the first Monday of a given month using NumPy?

02 Dec, 2020
To find the first Monday of a given month, we are going to use the numpy module i.e the numpy.busday_offset() method in numpy module.
Syntax: np.busday_offset(‘date’, 0, roll=’forward’, weekmask=’Mon’)
Parameters:
date: The array of dates to process.
offsets: The array of offsets, which is broadcast with dates.
roll:It takes the below values:
raise means to raise an exception for an invalid day.
nat means to return a NaT (not-a-time) for an invalid day.
forward and following mean to take the first valid day later in time.
backward and preceding mean to take the first valid day earlier in time.
modifiedfollowing means to take the first valid day later in time unless it is across a Month boundary, in which case to take the first valid day earlier in time.
modifiedpreceding means to take the first valid day earlier in time unless it is across a Month boundary, in which case to take the first valid day later in time.
weekmask: array indicating which of Monday through Sunday are valid days.
Returns (outarray of datetime64): An array with a shape from broadcasting dates and offsets together, containing the dates with offsets applied.
Example #1:
In this example, we will find the first Monday of the month of May 2017.
Python3
# import moduleimport numpy  # input year and monthyearMonth = '2017-05'  # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0,                            roll='forward',                            weekmask='Mon')  # display dateprint(date)
Output:
2017-05-01
Example #2:
Here, we will find the first Monday of the month of February 2001.
Python3
# import moduleimport numpy  # input year and monthyearMonth = '2001-02'  # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0,                           roll='forward',                           weekmask='Mon')  # display dateprint(date)
Output:
2001-02-05
Example #3:
Here, we will find the first Monday of the month of November 2020.
Python3
# import moduleimport numpy  # input year and monthyearMonth = '2020-11'  # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0,                           roll='forward',                           weekmask='Mon')  # display dateprint(date)
Output:
2001-11-02
Python numpy-DataType
Python-numpy
Python
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
CloudFail - Unmask/Bypass CloudFlare Security in Kali Linux - GeeksforGeeks

20 Apr, 2021
CloudFail is a free and open-source tool available on GitHub. CloudFail is a tactical reconnaissance tool. There are some websites that are protected by Cloudflare security. It’s hard to find information about such websites but now impossible. By using CloudFail tool we can get enough information about the target domain which is protected by Cloudflare security. CloudFail is a tool that helps to unmask CloudFlare by providing the actual IP of the server. According to the developers, CloudFail has 3 phases.
Features of CloudFail tool :
CloudFail check in Crimeflare.com to perform tactical reconnaissance.
CloudFail check in DNSDumpster.com to lookup for IP-address.
CloudFail Performs a brute force with more than 2500 subdomains for reconnaissance.
Step 1. Open your Kali Linux and move to the Desktop directory using the following command.
command : cd Desktop
Step 2. Create a new directory here and name it cloudfail.  
command : mkdir cloudfail
Step 3. Move to the directory that you have created using the following command.
command : cd cloudfail 
Step 4. Now you are in the cloudfail directory. You have to clone the tool here in this directory using the following command.
command : git clone https://github.com/m0rtem/CloudFail
Step 5. The tool has been downloaded in the cloudfail directory. To list out the content of the tool use following command.
command : ls
Step 6. You can see that a new directory is found after listing out the contents. Now move to this directory using the following command.
command : cd CloudFail
Step 7. Now you are under CloudFail directory. You have to list out the contents of the tool using the following command.
command : ls
Step 8. Give permission to the python files of the tools using the following command.
command : chmod +x cloudfail.py
Step 9. Now you have to install all the requirements that are used by the tool using the following command.
command : pip3 install -r requirements.txt
Step 10. All the requirements have been downloaded into the tool. Now, this is the time to run the tool. To run the tool use the following command. First, we will check for help by the tool. 
command : python3 cloudfail.py --help
Step 11. The tool is running and now uses the following command to update dependencies of the CloudFail tool.
command : python3 cloudfail.py -u
All the dependencies has been updated. Now you can set the target and run the tool. Now lets see some examples how you can bypass cloudflare security.
Example. By using CloudFail tool scan techchip.com
command : python3 cloudfail.py -t techchip.com 
Cyber-security
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Named Pipe or FIFO with example C program
Thread functions in C/C++
SED command in Linux | Set 2
Array Basics in Shell Scripting | Set 1
Introduction to Linux Shell and Shell Scripting
Linux system call in Detail
chown command in Linux with Examples
Looping Statements | Shell Script
mv command in Linux with examples
PING Command in Linux with examples
Exporting Pandas DataFrame to JSON File - GeeksforGeeks

31 Aug, 2021
Let us see how to export a Pandas DataFrame as a JSON file. To perform this task we will be using the DataFrame.to_json() and the pandas.read_json() function.
Example 1 :
Python3
# importing the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']],                  index =['row 1', 'row 2', 'row3'],                  columns =['col 1', 'col 2', 'col3']) # storing the data in JSON formatdf.to_json('file.json', orient = 'split', compression = 'infer', index = 'true') # reading the JSON filedf = pd.read_json('file.json', orient ='split', compression = 'infer') # displaying the DataFrameprint(df)
Output : 
We can see that the DataFrame has been exported as a JSON file.
Example 2 :
Python3
# importing the moduleimport pandas as pd  # creating a DataFramedf = pd.DataFrame(data = [['15135', 'Alex', '25 / 4/2014'],                   ['23515', 'Bob', '26 / 8/2018'],                   ['31313', 'Martha', '18 / 1/2019'],                   ['55665', 'Alen', '5 / 5/2020'],                   ['63513', 'Maria', '9 / 12 / 2020']],                  columns =['ID', 'NAME', 'DATE OF JOINING']) # storing data in JSON formatdf.to_json('file1.json', orient = 'split', compression = 'infer') # reading the JSON filedf = pd.read_json('file1.json', orient ='split', compression = 'infer')print(df)
Output : 
We can see that this DataFrame has also been exported as a JSON file.
 
sooda367
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
Clojure - Variadic Functions

Variadic functions are functions that take varying number of arguments (some arguments are optional). Function can also specify the ‘&’ ampersand symbol to take in an arbitrary number of arguments.
Following example shows how this can be achieved.
(defn demo 
   [message & others]
   (str message (clojure.string/join " " others)))
The above function declaration has the ‘&’ symbol next to the argument others, which means that it can take an arbitrary number of arguments.
If you invoke the above function as
(demo "Hello" "This" "is" "the" "message")
Following will be the output.
“HelloThis is the message”

The ‘clojure.string/join’ is used to combine each individual string argument, which is passed to the function.
 Print
 Add Notes
 Bookmark this page
File Handling in Java using FileReader and FileWriter

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
Following example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file −
import java.io.*;
public class CopyFile {

   public static void main(String args[]) throws IOException {

      FileReader in = null;
      FileWriter out = null;

      try {
         in = new FileReader("input.txt");
         out = new FileWriter("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      } finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Binary search in Java.

Following is the required program.
Live Demo
public class Tester {
   public static int binarySearch(int arr[], int first, int last, int element){
      int mid = (first + last)/2;
      while( first <= last ){
         if ( arr[mid] < element ){
            first = mid + 1;    
         }else if ( arr[mid] == element ){  
            return mid;
         }else{
            last = mid - 1;
         }
         mid = (first + last)/2;
      }
      return -1;                    
   }
                         
   public static void main(String a[]) {
      int[] array = { 10, 20, 30, 40, 50, 60 };
      int element = 50;
      int last=array.length-1;
      int index = binarySearch(array,0,last,element);
      if (index != -1) {
         System.out.println(element + " present at index: " + index);
      } else {
         System.out.println(element + " is not present.");
      }
   }
}
50 is present at index: 4
How to use SELF JOIN in MySQL?

To use SELF JOIN, let us create a table. The query to create a table is as follows −
mysql> create table SelfJoinDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> CountryName varchar(20),
   -> CountryRank int,
   -> `Year` varchar(10)
   -> );
Query OK, 0 rows affected (1.02 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('US',1,'2016');
Query OK, 1 row affected (0.12 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('UK',5,'2013');
Query OK, 1 row affected (0.16 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('France',45,'2010');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Turkey',3,'2000');
Query OK, 1 row affected (0.17 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Japan',78,'1995');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Romania',110,'2007');
Query OK, 1 row affected (0.22 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('UK',3,'2000');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from SelfJoinDemo;
The following is the output −
+----+-------------+-------------+------+
| Id | CountryName | CountryRank | Year |
+----+-------------+-------------+------+
|  1 | US          |           1 | 2016 |
|  2 | UK          |           5 | 2013 |
|  3 | France      |          45 | 2010 |
|  4 | Turkey      |           3 | 2000 |
|  5 | Japan       |          78 | 1995 |
|  6 | Romania     |         110 | 2007 |
|  7 | UK          |           3 | 2000 |
+----+-------------+-------------+------+
7 rows in set (0.00 sec)
Here is the query of SELF JOIN −
mysql> SELECT DISTINCT t1.CountryName, t2.Year
   -> FROM SelfJoinDemo AS t1,
   -> SelfJoinDemo AS t2
   -> WHERE t1.Year=t2.Year
   -> and t1.CountryName='US';
The following is the output −
+-------------+------+
| CountryName | Year |
+-------------+------+
| US          | 2016 |
+-------------+------+
1 row in set (0.00 sec
Change figure size in Pandas – Python

11 Dec, 2020
Prerequisites: Pandas
The size of a plot can be modified by passing required dimensions as a tuple to the figsize parameter of the plot() method. it is used to determine the size of a figure object.
Syntax:
figsize=(width, height)
Where dimensions should be given in inches.
Import pandas.
Create or load data
Call the plot() function with a figsize parameter along with dimensions.
Example 1
Python3
import pandas as pd  # import the pandas module  # python list of numbersdata1 = [10, 20, 50, 30, 15]  # convert the list to a pandas seriess1 = pd.Series(data1)    # creates a figure of size 20 inches wide and 10 inches highs1.plot(figsize=(20, 10))
Output:
Example 2
Python3
# import the pandas moduleimport pandas as pd    # Creating a pandas dataframedf = pd.DataFrame({'names': ['A', 'B', 'C', 'D'], 'val': [10, 45, 30, 20]})  # creates a bar graph of size 15 inches wide and 10 inches highdf.plot.bar(x='names', y='val', rot=0, figsize=(15, 10))
Output :
Example 3
Python3
# import the pandas moduleimport pandas as pd  # Creating a pandas dataframe with indexdf = pd.DataFrame({'value': [3.330, 4.87, 5.97]},                  index=['Item 1', 'Item 2', 'Item 3'])  df.plot.pie(y='value', figsize=(5, 5))
Output :
Python pandas-plotting
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
GATE | GATE CS 2019 | Question 15

27 Sep, 2021
Consider Z = X − Y where X, Y and Z are all in sign-magnitude form. X and Y are each represented in n bits. To avoid overflow, the representation of Z would require a minimum of:(A) n bits(B) n−1 bits(C) n+1 bits(D) n+2 bitsAnswer: (C)Explanation: Overflow can occur when two same sign numbers are added or two opposite sign numbers are subtracted.
For example:
let n = 4 bit, X = +6 and Y = -5 (1 bit for sign and 3 bit for magnitude)
Therefore, Z = X - Y = 6 - (-5) = 6+5 = 11
But result (Z) 11 needs 5 (= 4 + 1) bits to store, 
Sin integer 11 needs 1 bit for sign and 4 bit for magnitude. 
Therefore, to avoid overflow, the representation of Z would require a minimum of (n + 1) bits.
Option (C) is correct.
Number Representations GATE PYQs discussion with Rishabh Setiya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersNumber Representations GATE PYQs discussion with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:06 / 28:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=XpFNwoGzBQ8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | Gate IT 2005 | Question 11
GATE | GATE MOCK 2017 | Question 45
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2000 | Question 2
GATE | GATE CS 2013 | Question 50
GATE | GATE CS 2012 | Question 65
GATE | GATE-CS-2003 | Question 64
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 30
Infosys-InfyTQ Archives - GeeksforGeeks

Infosys Interview Experience for Digital Specialist Engineer Through InfyTQ
Infosys InfyTQ Interview Experience 2022
Infosys Infytq Interview Experience for System Engineer
Infosys InfyTQ DSE Interview Experience 2023
Infosys Certification Exam (InfyTQ) 2021
Infosys InfyTq System Engineer Specialist Interview Experience
INFYTQ Interview Experience for System Engineer 2022
Infosys(Infytq) Certification Exam (Systems Engineer Role)
Infosys Certification Exam | InfyTQ
Infosys Infytq Interview Experience for System Engineer 2020
Python – Consecutive identical elements count

12 Nov, 2020
Given the elements list, get all the elements that have an identical element as the next element.
Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] Output : 3 Explanation : 5, 6 and 2 has identical element as their next element.
Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 3, 10] Output : 2 Explanation : 5 and 6 has identical element as their next element. 
Method #1 : Using loop + set()
In this, we iterate and check for the next element, if equal to current, we add in result list, then it is converted to set to get distinct elements.
Python3
# Python3 code to demonstrate working of # Consecutive identical elements count# Using loop + set()  # initializing listtest_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]  # printing original listprint("The original list is : " + str(test_list))  res = []for idx in range(0, len(test_list) - 1):          # getting Consecutive elements     if test_list[idx] == test_list[idx + 1]:        res.append(test_list[idx])          # getting count of unique elements        res = len(list(set(res)))  # printing result print("Consecutive identical elements count : " + str(res))
The original list is : [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
Consecutive identical elements count : 3

Method #2 : Using list comprehension + set() + len()
This method is similar to above method, difference being its shorter way to solve this problem. The len(), and set() are used for task of getting unique elements count.
Python3
# Python3 code to demonstrate working of# Consecutive identical elements count# Using list comprehension + set() + len()  # initializing listtest_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]  # printing original listprint("The original list is : " + str(test_list))  # getting Consecutive elementsres = [test_list[idx] for idx in range(    0, len(test_list) - 1) if test_list[idx] == test_list[idx + 1]]  # getting count of unique elementsres = len(list(set(res)))  # printing resultprint("Consecutive identical elements count : " + str(res))
The original list is : [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10]
Consecutive identical elements count : 3

Python list-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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
PHP | list() Function

03 Jun, 2020
The list() function is an inbuilt function in PHP which is used to assign array values to multiple variables at a time. This function will only work on numerical arrays. When the array is assigned to multiple values, then the first element in the array is assigned to the first variable, second to the second variable, and so on, till the number of variables. The number of variables cannot exceed the length of the numerical array.
Syntax:
list($variable1, $variable2....)
Parameter: It accepts a list of variables separated by spaces. These variables are assigned values. At least one variable must be passed to the function.
Return Value: The function returns the assigned array to the multiple variables passed. If the number of variables passed is greater than the number of elements in the array, an error is thrown.
Below programs illustrate the list() function in PHP:
Program 1: Program to demonstrate the use of list() function.
<?php  // PHP program to demonstrate the // use of list() function $array = array(1, 2, 3, 4);  // Assign array values to variables list($a, $b, $c) = $array;   // print all assigned values echo "a =", ($a), "\n";echo " b =", ($b), "\n";echo " c =", ($c), "\n";   // Perform multiplication of// those assigned numbersecho "a*b*c =", ($a*$b*$c);   ?>
Output:
 a =1
 b =2
 c =3
a*b*c =6
Program 2: Program to demonstrate the runtime error of list() function.
<?php  // PHP program to demonstrate the // runtime error of list() function $array = array(1, 2, 3, 4);  // assign array values to variables list($a, $b, $c, $d, $e) = $array;   ?>
Output:
PHP Notice:  Undefined offset: 4 in 
/home/619f1441636b952bbd400f1e9e8e3d0c.php on line 6

Program 3: Program to demonstrate assignment of particular index values in the array to variables.
<?php  // PHP program to demonstrate assignment of // particular index values in the array to // variables. $array = array(1, 2, 3, 4);  // Assign array values to variables list(, , $a) = $array;   // Print all assigned values echo " a = ", ($a), "\n";    ?>
Output:
a = 3

Reference:http://php.net/manual/en/function.list.php
ArkadyutiBanerjee
PHP-array
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python String center() Method

Python string method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space.
str.center(width[, fillchar])

width − This is the total width of the string.
width − This is the total width of the string.
fillchar − This is the filler character.
fillchar − This is the filler character.
This method returns centered in a string of length width.
The following example shows the usage of center() method.
#!/usr/bin/python

str = "this is string example....wow!!!"
print "str.center(40, 'a') : ", str.center(40, 'a')
str.center(40, 'a') :  aaaathis is string example....wow!!!aaaa
Dart – Symbols

09 May, 2021
In Dart, Symbols are basically an object representation of either an identifier or operator.  The symbols in dart are opaque and dynamic string names that cannot be changed and remains constant throughout the compile time. It can be used for reflecting the metadata on a type, such as a library or class. They are generally used for creating APIs and establish a relationship between a string that is understandable to humans and a string that can be used by computers.
Symbols can be used to get various information about a type (library, class, etc) such as a list of instance methods, constructors, etc.
Symbols can be created in 2 different ways –
1. Adding a Hash (#) symbol to an identifier would convert it into a Symbol
print(#mysymbol);
Output:
Symbol("mysymbol")
2. Otherwise, a symbol can be created explicitly using the Class constructor.
Symbol mySymbol = Symbol('mysymbol');
print(mySymbol);
Output:
Symbol("mysymbol")
Example:
In this example, we’ll be creating a Custom Library and then show its metadata using Symbols.
Here, we have first created a Dart File Custom.dart containing a  library custom_lib, which consists of a class called CustomClass having methods customFunction1 and customFunction2.
Dart
library custom_lib;  class CustomClass {  void customFunction1() {    print("Custom Function 1");  }    void customFunction2() {    print("Custom Function 2");  }}
Next, we’ll create the main.dart file, which will import the Custom. dart file along with a couple of other libraries such as dart:core and dart:mirror
First, we’ll create 2 symbols. One for the custom library and the other for the custom class.
Next, we’ve to initialize the mirror system, and create a mirror reference to our custom_lib library, and then using that, to our CustomClass class.
Using classMirror, we can now extract some data i.e. a list of methods present in our class. That includes –User created methods such as customFunction1In-build methods such as toString
User created methods such as customFunction1
In-build methods such as toString
Dart
import 'dart:core';import 'dart:mirrors';import 'Custom.dart';  void main() {      // Create symbols for library and class  Symbol libraryName = Symbol('custom_lib');  Symbol className = Symbol('CustomClass');    // Init mirror system  MirrorSystem mirrorSystem = currentMirrorSystem();  LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName);  ClassMirror classMirror = libMirror.declarations[className];    // Get and print methods  final methods = classMirror.instanceMembers;  print('Total number of methods = ${methods.length}');  methods.forEach((symbol, method) {    print(symbol);  });}
Output:
Total number of methods = 7
Symbol("==")
Symbol("hashCode")
Symbol("toString")
Symbol("noSuchMethod")
Symbol("runtimeType")
Symbol("customFunction1")
Symbol("customFunction2")
Dart-basics
Picked
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65

28 Jun, 2021
Which one of the following correctly determines the solution of the recurrence relation with T(1) = 1?
T(n) = 2T(n/2) + Logn 
(A) Θ(n)(B) Θ(nLogn)(C) Θ(n*n)(D) Θ(log n)Answer: (A)Explanation:
 T(n) = 2T(n/2) + log n
 T(1) = 1
Substitute n = 2^k

T(2^k)  = k + 2T(2^(k-1))
T(2^k)  = k + 2(k-1) + 4T(2^(k-2))
        = k + 2(k-1) + 4(K-2) + 8T(2^(k-3))
        = k + 2(k-1) + 4(K-2) + 8(k-3) + 16T(2^(k-4))
        = k + 2(k-1) + 4(K-2) + 8(k-3) + ...... + 2^kT(2^(k-k))
        = k + 2(k-1) + 4(K-2) + 8(k-3) + .......+ 2^kT(1)
        = k + 2(k-1) + 4(K-2) + 8(k-3) + .......+ 2^k  --------(1)

2T(2^k) =     2k     + 4(k-1) + 8(K-2) + ...... + 2*2^k + 2^(k+1) --------(2)

Subtracting 1 from 2, we get below
T(2^k) = - k + 2 + 4 ......    2^(k-2) + 2^(k-1) + 2^k + 2^(k+1)
           = - k + 2 * (1 + 2 + 4 + ..... 2^k)
           = -k + [2*(2^k - 1)] / [2-1]
           = -k + [2*(2^k - 1)]

T(n) = -Logn + 2*(n - 1)

T(n)  = Θ(n) 
Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TreeMap descendingMap() Method in Java with Examples

15 Oct, 2020
The descendingMap() method is used to return a reverse order view of the mappings contained in this map. The reverse order or descending order of mappings are according to the descending order of keys. The descending map is backed by this map, so changes to the map are reflected in the descending map, and vice-versa. 
Declaration Syntax:
public NavigableMap<K,V> descendingMap()

K : It is the type of keys maintained by this map.
V : It is the type of mapped values.
Parameters: Not Available
Return Value: A reverse order or descending order view of this map.
Example 1: 
Java
// Java program to demonstrate descendingMap() method  import java.util.*;  public class Example1 {    public static void main(String[] args)    {          // Declaring the tree map of Integer and String        TreeMap<Integer, String> treemap            = new TreeMap<Integer, String>();          // Add the mappings to the tree map using put()        treemap.put(2, "Two");        treemap.put(16, "Sixteen");        treemap.put(8, "Eight");        treemap.put(6, "Six");        treemap.put(10, "Ten");          // store the descending order of mappings in dmap        NavigableMap dmap = treemap.descendingMap();          System.out.println("Reverse navigable map values: "                           + dmap);    }}
Reverse navigable map values: {16=Sixteen, 10=Ten, 8=Eight, 6=Six, 2=Two}



Example 2 :
Java
// Java Program to demonstrate descendingMap() method  import java.util.*;  public class Example2 {    public static void main(String[] args)    {          // Declaring the tree map of Integer and String        TreeMap<Integer, String> treemap            = new TreeMap<Integer, String>();          // Add the mappings to the tree map using put()        treemap.put(11, "Abhishek Rout");        treemap.put(9, "Akash Salvi");        treemap.put(2, "Hemant Koul");        treemap.put(8, "Vaibhav Kamble");        treemap.put(6, "Sagar Joshi");        treemap.put(10, "Onkar Dherange");        treemap.put(7, "Rajwardhan Shinde");        treemap.put(1, "Rahul Gavhane");        treemap.put(4, "Abhishek Gadge");        treemap.put(3, "Pratik Kulkarni");        treemap.put(5, "Raviraj Bugge");          // store the descending order of mappings in dmap        NavigableMap dmap = treemap.descendingMap();          // print the mappings        System.out.println(            "List of students in reverse order: " + dmap);    }}
List of students in reverse order: {11=Abhishek Rout, 10=Onkar Dherange, 9=Akash Salvi, 8=Vaibhav Kamble, 7=Rajwardhan Shinde, 6=Sagar Joshi, 5=Raviraj Bugge, 4=Abhishek Gadge, 3=Pratik Kulkarni, 2=Hemant Koul, 1=Rahul Gavhane}


Java-Collections
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java