code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas dataframe.add_prefix()

16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Dataframe.add_prefix() function can be used with both series as well as dataframes.
For Series, the row labels are prefixed.
For DataFrame, the column labels are prefixed.
Syntax:  DataFrame.add_prefix(prefix)

Parameters:
prefix : string

Returns: with_prefix: type of caller

For link to CSV file Used in Code, click here
Example #1: Prefix col_ in each columns in the dataframe
# importing pandas as pdimport pandas as pd  # Making data frame from the csv filedf = pd.read_csv("nba.csv")  # Printing the first 10 rows of the# dataframe for visualizationdf[:10]
# Using add_prefix() function # to add 'col_' in each column labeldf = df.add_prefix('col_')  # Print the dataframedf 
Output:
 
Example #2: Using add_prefix() with Series in pandas
add_prefix() alters the row index labels in the case of series.
# importing pandas as pdimport pandas as pd  # Creating a Series df = pd.Series([1, 2, 3, 4, 5, 10, 11, 21, 4])  # This will prefix 'Row_' in # each row of the seriesdf = df.add_prefix('Row_')  # Print the Seriesdf
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python pandas-general-functions
Python pandas-series
Python-pandas
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
SQL USE Database Statement

06 Sep, 2021
SQL(Structured Query Language) is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. It is flexible and user-friendly. In SQL, to interact with the database, the users have to type queries that have certain syntax, and use command is one of them. The use command is used when there are multiple databases in the SQL and the user or programmer specifically wants to use a particular database. Thus, in simple terms, the use statement selects a specific database and then performs operations on it using the inbuilt commands of SQL.
Syntax:
USE database_name;
Example 1:
The user wants to works on the databases named “GEEKS”. So the user will write:
USE candy;
Example 2:
Before using any database using the use command, it’s necessary to first create it. In order to create a database in SQL, the following command is used. Here, we create a database named “GFG1”:
CREATE DATABASE GFG1
Now, after the user has created a database named candy, we can use this database to perform the database operations. So, for that, the user has to type the USE command as follows:
USE GFG1
After performing desired operations on the database, if we do not want the database, We can drop the database using the DROP command:
DROP DATABASE  GFG1
Remember, once a database is dropped, it’s removed permanently from the list of available databases, there is no way to retrieve the data of the table or the complete database in any possible way.
After using the drop command, if the user types –
USE GFG1
The SQL database will throw an error as the GFG1 database has been removed permanently from the database using the drop command. 
abhijithoyur
Picked
Class 12
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting Algorithms in Python
Querying Data from a Database using fetchone() and fetchall()
Cardinality in DBMS
Intrinsic Semiconductors and Extrinsic Semiconductors
Different Types of Wireless Communication Media
How to Align Text in HTML?
What are Different Output Devices?
Generations of Computers - Computer Fundamentals
What is a Storage Device? Definition, Types, Examples
Types of Internet Protocols
Create a User-Defined Data Type Alias in SQL Server

17 Mar, 2021
SQL Server has multiple data types e.g. integers, char, varchar, doubles, strings, etc. which are used for keeping specific values. Although built-in data types could store specific values, sometimes SQL DBA may need to store more specific values and create customized data types.
We can create a user-defined data type using below two methods –
Using T-SQL
Using SQL Server Management Studio
Create a User-Defined Data Type using T-SQL :
Syntax –
use DatabaseName
Create Type UserDefineDataTypeName    
from datatype NOT NULL
Example –Creating a User-Defined Data Type named “Code” which stores only 4 letters.
use Database name
Create Type Code    
from varchar(4) NOT NULL
Create a User-Defined Data Type using SQL Server Management Studio :
Connect to SQL Server
Expand Database
Expand Programmability
Expand Types
Select User Defined Data Types
ight-click on it and select “New User-Defined Data Type“
Fill in the required information to create data type, Click OK.
Use custom datatype in a table or SQL query –
Note: User-Defined Data Types standalone does not have an advantage over built-in. But if rules are created to bind them with the custom data type you have recently created.
1. Create a rule –
Syntax –
Create Rule RuleName  
as @UserDefineDataTypeName not like ruletype
Example –
Create Rule Code_Rule  
as @Code not like '%D%'
In the above example, a rule that accepts every input except word with ‘D’ letter. 
2. Bind the Rule and User-Defined Data Type –To combine or bind the Rule and User-Defined Data Type: we could use the stored procedure “sp_bindrule”:
Syntax –
sp_bindrule RuleName,'UserDefineDataTypeName'
Example –
sp_bindrule Code_Rule,'Code'
In the above example, Code_Rule will bind the rule to user-defined data type ‘Code’.
3. Unbind the rule from User-Defined Data Type –
To unbind the rule from User-Defined Data Type use “sp_unbindrule”.
Syntax –
sp_unbindrule 'UserDefineDataTypeName'
Example –
sp_unbindrule 'Code'
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window functions in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
RANK() Function in SQL Server
What is Temporary Table in SQL?
SQL | DROP, TRUNCATE
SQL indexes
SQL using Python
SQL | MINUS Operator
Union and Union All in MS SQL Server
SQL | Query Processing
Can Virtual Functions be Inlined in C++?

01 Dec, 2021
Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. 
Inline functions are used to replace the function calling location with the definition of the inline function at compile time. They are used for efficiency. The whole idea behind the inline functions is that whenever an inline function is called code of the inline function gets inserted or substituted at the point of the inline function call at compile time. Inline functions are very useful when small functions are frequently used and called in a program many times. 
By default, all the functions defined inside the class are implicitly or automatically considered as inline except virtual functions. 
Note: inline is a request to the compiler and its compilers choice to do inlining or not.
Can virtual functions be inlined?
Whenever a virtual function is called using a base class reference or pointer it cannot be inlined because the call is resolved at runtime, but whenever called using the object (without reference or pointer) of that class, can be inlined because the compiler knows the exact class of the object at compile time. 
C++
// CPP program to demonstrate that// virtual functions can be inlined#include <iostream>using namespace std; class Base {public:    virtual void who() { cout << "I am Base\n"; }};class Derived : public Base {public:    void who() { cout << "I am Derived\n"; }}; int main(){    // Part 1    Base b;    b.who();     // Part 2    Base* ptr = new Derived();    ptr->who();     return 0;}
I am Base
I am Derived
Explanation: In Part 1, the virtual function who() is called through the object of the class. Since it will be resolved at compile-time, so it can be inlined. In Part 2, the virtual function is called through a pointer, so it cannot be inlined.
This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
CPP-Functions
cpp-virtual
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
std::string class in C++
Unordered Sets in C++ Standard Template Library
Memory Layout of C Programs
What is the purpose of a function prototype?
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
C# Example for MultiLevel Inheritance

Multilevel Inheritance occurs when a derived class is formed from another derived class.
Grandfather, father, and son are the perfect example to represent Multilevel Inheritance in C# −
The following is an example stating the usage of multilevel inheritance in C#.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class Son : Father {
      public void DisplayTwo() {
         Console.WriteLine("Son.. ");
      }
      static void Main(string[] args) {
         Son s = new Son();
         s.Display();
         s.DisplayOne();
         s.DisplayTwo();
         Console.Read();
      }
   }
   class Grandfather {
      public void Display() {
         Console.WriteLine("Grandfather...");
      }
   }
   class Father : Grandfather {
      public void DisplayOne() {
         Console.WriteLine("Father...");
      }
   }
}
Grandfather...
Father...
Son..
How to remove outline around text input boxes in chrome using CSS?

16 Oct, 2021
Generally in the case of Google Chrome Browser, when the input field gets focus then the blue outline occurred on the border of the Input fields. The Task can be done by using the CSS outline property.  
Example:  
html
<html><head>   <title>        How to remove outline around text    input boxes in chrome using CSS?   </title><style>textarea:focus{        outline: none;    }     </style>  <body>      <h2>          GeeksFprGeeks      </h2>      <h2>          How to remove outline around text    input boxes in chrome using CSS?       </h2><br>      <h4><b> Before using the outline Property</b></h4>                       <input type="text">          <h4><b>After using the Outline Property</b></h4>    <textarea rows="4"></textarea>  </body></head></html>
Output 
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
surindertarika1234
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Dynamically Resize Buttons When Resizing a Window using Tkinter

04 Sep, 2021
Prerequisite: Python GUI – tkinter
Button size is static, which means the size of a button cannot be changed once it is defined by the user. The problem here is while resizing the window size, it can affect the button size problem. So the solution here is, make a dynamic button, which means the button size will change as per window size.
Let’s understand with step-by-step implementation:
Step 1#: Create Normal Tkinter Window
Python3
# Import modulefrom tkinter import *   # Create objectroot = Tk()   # Adjust sizeroot.geometry("400x400")   # Execute tkinterroot.mainloop()
Output:-
Step 2#: Add Buttons and set the grid.
Syntax:
Button(Object Name,text="Enter Text")
What is grid?
The grid() geometry manager organizes widgets in a table-like structure in the parent widget. The master widget is split into rows and columns, and each part of the table can hold a widget. It uses column, column span, ipadx, ipady, padx, pady, row, row span, and sticky.
Syntax:
Object_name.grid(row=row value,column=column value,**attributes)
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("500x500") # Create Buttonsbutton_1 = Button(root,text="Button 1")button_2 = Button(root,text="Button 2") # Set gridbutton_1.grid(row=0,column=0)button_2.grid(row=1,column=0) # Execute tkinterroot.mainloop()
Output:
Add Two Buttons
Step 3#: Set Columnconfigure & Rowconfigure for resize.
For the user interface to resize then, we’ll need to specify a positive weight to the columns that we’d like to expand. This is done using the Columnconfigure and Rowconfigure methods of the grid. This weight is relative. If two columns have the same weight, they’ll expand at the same rate.
What to do if the cell is larger than widget. By default, with sticky=”, widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks. 
“NSEW” means N+S+E+W
Code:- 
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("500x500") # Specify GridGrid.rowconfigure(root,0,weight=1)Grid.columnconfigure(root,0,weight=1) Grid.rowconfigure(root,1,weight=1) # Create Buttonsbutton_1 = Button(root,text="Button 1")button_2 = Button(root,text="Button 2") # Set gridbutton_1.grid(row=0,column=0,sticky="NSEW")button_2.grid(row=1,column=0,sticky="NSEW") # Execute tkinterroot.mainloop()
Output:
 
saurabh1990aror
akshaysingh98088
Python-tkinter
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
get_attribute() element method – Selenium Python

17 Nov, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating StrategiesThis article revolves around how to use get_attribute method in Selenium. get_attribute method is used to get attributes of an element, such as getting href attribute of anchor tag. This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the attribute with the same name. If there’s no attribute with that name, None is returned.Syntax –  
element.get_attribute("attribute name")
Example –  
html
<a href="https://www.geeksforgeeks.org/" id="link" />
To find an element one needs to use one of the locating strategies, For example, 
element = driver.find_element_by_id("link")
element = driver.find_element_by_xpath("//a[@id='link']")
Also, to find multiple elements, we can use –  
elements = driver.find_elements_by_id("link")
Now one can get attribute of this field with  
element.get_attribute('href')
 
Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we get href attribute of courses tab in navigation bar at geeksforgeeks. Program –  
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_link_text("Courses") # get href attributeprint(element.get_attribute('href'))
Output-  
Terminal Output –  
 
kashishsoda
Python-selenium
selenium
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
Python OOPs Concepts
isNAN() function in JavaScript

The isNaN() function accepts a value and determines whether the given value is a number or not.If so, this method returns true else it returns false. You can also call this method using Number object.
Its Syntax is as follows
isNAN(5655);
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var result1 = parseFloat("Ef00A.D3");
      document.write(isNaN(result1));
      document.write('<br>');
      var result2 = Math.log("welcome");
      document.write(isNaN(result2));
      document.write('<br>');
      var result3 = Math.log(1254);
      document.write(isNaN(result3));
   </script>
</body>
</html>
true
true
false
Node.js process.cpuUsage() Method - GeeksforGeeks

12 Oct, 2021
The process.cpuUsage() method is an inbuilt application programming interface of the Process module which is used to get the user, system CPU time usage of the current process. It is returned as an object with property user and system, values are in microseconds. Return values may differ from the actual time elapsed especially for multi-core CPUs.
Syntax: 
process.cpuUsage( previous_value )
Parameters: This method accepts a single parameter as mentioned above and described below:  
previous_value: It is an optional parameter, an object returned by the calling process.cpuUsage() previously. If it is passed then the difference is returned.
Return: This method returns an object on success, which contains properties like user and system, with some integer value that signifies time elapsed by the process, measured in microseconds. 
user: It is an integer that represents the time elapsed by user
system: It is an integer represents the time elapsed by system
Below examples illustrate the use of process.cpuUsage() method in Node.js:
Example 1:  
Javascript
// Allocating process moduleconst process = require('process');  // Calling process.cpuUsage() methodconst usage = process.cpuUsage();  // Printing returned valueconsole.log(usage);
Output: 
{ user: 78000, system: 15000 }
Example 2: 
Javascript
// Allocating process moduleconst process = require('process');  // Calling process.cpuUsage() methodvar usage = process.cpuUsage();// Printing returned valueconsole.log("cpu usage before: ", usage);  // Current timeconst now = Date.now();  // Loop to delay almost 100 millisecondswhile (Date.now() - now < 100);  // After using the cpu for nearly equal to // 100 milliseconds// Calling process.cpuUsage() methodusage = process.cpuUsage(usage);  // Printing returned valueconsole.log("Cpu usage by this process: ", usage);
Output: 
cpu usage before:  { user: 62000, system: 15000 }
Cpu usage by this process:  { user: 109000, system: 0 }
Reference: https://nodejs.org/api/process.html#process_process_cpuusage_previousvalue 
arorakashish0911
Node.js-process-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
How to update NPM ?
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
FormatException in C#

FomatException is thrown when the format of an argument is invalid.
Let us see an example.
When we set a value other than int to int.Parse() method, then FormatException is thrown as shown below −
 Live Demo
using System;
class Demo {
   static void Main() {
      string str = "3.5";
      int res = int.Parse(str);
   }
}
The following error is thrown when the above program is compiled since we have passed a value other than integer.
Unhandled Exception:
System.FormatException: Input string was not in a correct format.
Google Summer Trainee Engineering Program(STEP) Interview Experience - GeeksforGeeks

04 Jun, 2019
Telephonic Interview 1. (Telephonic + Google Docs Shared)
Q1. Given an array of integers, you need to find the local maxima.
Example : [1 3 5 4 7 10 6]

Output: 5 or 10

Explanation: Any of the local maxima can be the output. 
Here 5 is greater than 3 and 4, 10 is greater than 7 and 6. 

Hint : Refer this article.
Q2. Given a sequence of brackets, how will you identify if its valid or not.
Example : ({[][]})

Output: Valid

Explanation: Every opening bracket has a closing bracket.

Example: ({[]]}) 

Output: Invalid 

Explanation : Every opening bracket does not have a closing bracket.

Hint : Refer this article.Telephonic Interview 2. (Telephonic + Google Docs Shared)
Q1. There are 2 arrays. Smaller is of size m and has m elements in sorted order. The bigger array isof size m+n, where there are only n elements in initial n positions in sorted order. So, last mpositions are empty in the bigger array. Insert smaller array’s m elements in m + n array has all numbers in sorted order.
Example : 
Input Array    N[]={5, 9, 15, 20,,,,,, }  n=4
               M[]={1, 3, 6, 8, 19, 35}  m=6
Output array   N[]={1, 3, 5, 6, 8, 9, 15, 19, 20, 35}

Hint : Refer this article.
Q2. Given a binary tree with integer values, find the sub-path with the maximum value in it
   
Example : 
       1
     /   \ 
    2      3
  /   \  /   \
 4     5 6    7

Output : Max path is 5, 2, 1, 3, 7
Explanation : 5+2+1+3+7=18 is the maximum value that can spanned.

      -100
     /     \
    2        3
   /  \     /  \
  4    5   6    7

Output : Max path is 6, 3, 7
Explanation : 6+3+7=16 is the maximum value that can spanned.

Hint : Refer this article.
Google
Internship
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
OLX Interview Experience (On-Campus)
Zoho Interview Experience (Off-Campus ) 2022
Zoho Corporation (Internship cum Offer Experience )
Difference Between ON Page and OFF Page SEO
Amazon Interview Questions
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (On-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1
How to Create a Spinner in JavaFX?

A spinner is a UI element that displays a number with an up and down arrow with it. You can increase or, decrease the value of the spinner using those arrows. You can create a spinner by instantiating the javafx.scene.control.Spinner class.
The following Example demonstrates the creation of a Spinner.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class SpinnerExample extends Application {
   public void start(Stage stage) {
      //Setting the label
      Label label = new Label("Select Date:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //Creating a spinner
      Spinner month = new Spinner(1, 12, 4);
      //Setting the spinner editable
      month.setEditable(true);
      //Setting the size
      month.setPrefSize(75, 25);
      Label label1 = new Label("Month: ");
      //Creating a spinner
      Spinner day = new Spinner(1, 31, 4);
      //Setting the spinner editable
      day.setEditable(true);
      //Setting the size
      day.setPrefSize(75, 25);
      Label label2 = new Label("Day: ");
      //Creating a spinner
      Spinner year = new Spinner(1947, 2999, 2009);
      //Setting the spinner editable
      year.setEditable(true);
      //Setting the size
      year.setPrefSize(75, 25);
      Label label3 = new Label("Year: ");
      HBox hbox = new HBox(5);
      hbox.setPadding(new Insets(10, 10, 10, 25));
      hbox.getChildren().addAll(label1, month, label2, day, label3, year);
      //Creating a vbox to hold the pagination
      VBox vbox = new VBox();
      vbox.setSpacing(5);
      vbox.setPadding(new Insets(10, 10, 10, 25));
      vbox.getChildren().addAll(label, hbox);
      //Setting the stage
      Group root = new Group(vbox);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Spinner");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Java program to implement insertion sort

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be inserted in this sorted sub-list has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).
1.If it is the first element, it is already sorted. return 1;
2.Pick next element
3.Compare with all elements in the sorted sub-list
4.Shift all the elements in the sorted sub-list that is greater than the value to be sorted
5.Insert the value
6.Repeat until the list is sorted
Live Demo
public class InsertionSort {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;

      for (int i=1 ;i< size; i++){
         int val = array[i];
         int pos = i;

         while(array[pos-1]>val &amp;&amp; pos>0){
            array[pos] = array[pos-1];
            pos = pos-1;
         }
         array[pos] = val;
      }

      for (int i=0 ;i< size; i++){
         System.out.print(" "+array[i]);
      }
   }
}
10 20 25 57 63 96
What is the difference between root.destroy() and root.quit() in Tkinter(Python)?

When we invoke the destroy() method with the tkinter window object, it terminates the mainloop process and destroys all the widgets inside the window. Tkinter destroy() method is mainly used to kill and terminate the interpreter running in the background.
However, quit() method can be invoked in order to stop the process after the mainloop() function. We can demonstrate the functionalities of both methods by creating a button Object.
#Import the required libraries
from tkinter import *

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

#Set the geometry of frame
win.geometry("650x450")

#Define a function for Button Object
def quit_win():
   win.quit()
def destroy_win():
   win.destroy()

#Button for Quit Method
Button(win,text="Quit", command=quit_win, font=('Helvetica
bold',20)).pack(pady=5)

#Button for Destroy Method
Button(win, text= "Destroy", command=destroy_win, font=('Helvetica
bold',20)).pack(pady=5)
win.mainloop()
Running the code will display a window with two buttons “Quit” and “Destroy” respectively.
Warning − quit() will terminate the application abruptly, hence it is recommended that you close the application from the manager after execution.
Instruction type RAL in 8085 Microprocessor

In 8085 Instruction set, there is another mnemonic RAL,which stands or Rotate Accumulator Left and also involving Cy flag in rotation. It rotates the Accumulator contents to the left by 1-bit position. The following Fig. is depicting the execution logic of the instruction.
From the Fig. we can see that the due to left rotation the bit which is coming out from the most significant place will be copied to the Cy flag bit. And the previous Cy bit will be moved to least significant bit place of the Accumulator. Thus it is a 9-bit rotation of Accumulator and Cy contents. Only Cy flag is affected by this instruction execution.
The instruction can be used for multiple purposes.
To find the most significant bit of the Accumulator, performing rotate left.
To find the most significant bit of the Accumulator, performing rotate left.
To perform multiplication by 2. We know that if we multiply a number by 2n then the number will have n-bit left rotation.
To perform multiplication by 2. We know that if we multiply a number by 2n then the number will have n-bit left rotation.
As during rotation, an empty space will get created. So to put a new bit at that least significant space we can use this mnemonic as well.
As during rotation, an empty space will get created. So to put a new bit at that least significant space we can use this mnemonic as well.
Let us consider the following examples for the better understanding.
35H ---> 0011 0101
0 0110 1010 ---> 6AH (Prev. Cy bit as the Last bit)
Note that Accumulator value has been doubled compared with the previous value.
35H ---> 0011 0101
0 0110 1011 ---> 6BH(Prev. Cy bit as the Last bit)
Here the current Accumulator content is not doubled compared to the initial content of the Accumulator. As in this case because most significant bit of Accumulator was a 1 before rotation.
The timing diagram against this instruction RAL execution is as follows −
Summary − So this instruction RAL requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
SAS - Fishers Exact Tests

Fisher's exact test is a statistical test used to determine if there are nonrandom associations between two categorical variables.In SAS this is carried out using PROC FREQ. We use the Tables option to use the two variables subjected to Fisher Exact test.
The basic syntax for applying Fisher Exact test in SAS is −
PROC FREQ DATA = dataset ;
TABLES Variable_1*Variable_2 / fisher;
Following is the description of the parameters used −
dataset is the name of the dataset.
dataset is the name of the dataset.
Variable_1*Variable_2 are the variables form the dataset .
Variable_1*Variable_2 are the variables form the dataset .
To apply Fisher's Exact Test, we choose two categorical variables named Test1 and Test2 and their result.We use PROC FREQ to apply the test shown below.
data temp;
input  Test1 Test2 Result @@;
datalines;
1 1 3 1 2 1 2 1 1 2 2 3
;
proc freq; 
tables Test1*Test2 / fisher;
run;

When the above code is executed, we get the following result −

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
Program to encrypt a string using Vigenere cipher in Python

Suppose we have a lowercase alphabet string text, and have another string called key. We have to find a new string where every letter in text[i] is moved to the right side with offset key[i]. Here the offset represented by key[i]'s position in the alphabet (A=0, B=1 etc.) If the letter overflows, it gets wrapped around the other side.
So, if the input is like text = "code", key = "team", then the output will be "vsdq"
To solve this, we will follow these steps −
cip := a new list
start := ASCII of 'a'
for each l from text and k from key, doshift := (ASCII of k) - startpos := start +((ASCII of l) - start + shift) mod 26insert character of pos at the end of cip
shift := (ASCII of k) - start
pos := start +((ASCII of l) - start + shift) mod 26
insert character of pos at the end of cip
join strings of cip and return
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, text, key):
      cip = []
      start = ord('a')
      for l, k in zip(text, key):
         shift = ord(k) - start
         pos = start + (ord(l) - start + shift) % 26
         cip.append(chr(pos))
      return ''.join([l for l in cip])
ob = Solution()
text = "code"
key = "team"
print(ob.solve(text, key))
"code", "team"
vsdq
Python - Construct dictionary Key-Value pairs separated by delimiter - GeeksforGeeks

01 Jul, 2021
Given a String with key-value pairs separated by delim, construct a dictionary.
Input : test_str = ‘gfg#3, is#9, best#10’, delim = ‘#’ Output : {‘gfg’: ‘3’, ‘is’: ‘9’, ‘best’: ’10’} Explanation : gfg paired with 3, as separated with # delim.Input : test_str = ‘gfg.10’, delim = ‘.’ Output : {‘gfg’: ’10’} Explanation : gfg paired with 10, as separated with . delim.  
Method #1 : Using split() + loop
In this, we perform a split on comma, to get key value pairs, and again a split on custom delim to get key value pairs separated. Then assigned to dictionary using loop.
Python3
# Python3 code to demonstrate working of# Contruct dictionary Key-Value pairs separated by delim# Using split() + loop # initializing stringstest_str = 'gfg$3, is$9, best$10' # printing original stringprint("The original string is : " + str(test_str)) # initializing delimdelim = "$" # split by comma for getting different dict valuesdicts = test_str.split(', ') res = dict()for sub in dicts:     # 2nd split for forming Key-Values for dictionary    res[sub.split(delim)[0]]  = sub.split(delim)[1] # printing resultprint("The constructed dictionary : " + str(res))
The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}
Method #2 : Using dictionary comprehension + split()
Similar to above method, just the difference being that dictionary comprehension is used for performing task of dictionary construction.
Python3
# Python3 code to demonstrate working of# Contruct dictionary Key-Value pairs separated by delim# Using split() + dictionary comprehension # initializing stringstest_str = 'gfg$3, is$9, best$10' # printing original stringprint("The original string is : " + str(test_str)) # initializing delimdelim = "$" # split by comma for getting different dict valuesdicts = test_str.split(', ') # dictionary comprehension to form dictionaryres = {sub.split(delim)[0] : sub.split(delim)[1] for sub in dicts} # printing resultprint("The constructed dictionary : " + str(res))
The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}
surinderdawra388
Python dictionary-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks

29 Sep, 2021
Consider a machine with a byte addressable main memory of 220 bytes, block size of 16 bytes and a direct mapped cache having 212 cache lines. Let the addresses of two consecutive bytes in main memory be (E201F)16 and (E2020)16. What are the tag and cache line address (in hex) for main memory address (E201F)16?(A) E, 201(B) F, 201(C) E, E20(D) 2, 01FAnswer: (A)Explanation:
Block Size = 16 bytes
Block Offset = 4 

No. of sets or cache lines = 212
Number of index bits = 12

Size of main memory = 220
Number of tag bits = 20 - 12 - 4 = 4 

Let us consider the hex address E201F
Tag lines = First 4 bits = E (in hex)
Cache lines = Next 12 bits  = 201 (In Hex) 
Refer http://virtual-labs.ac.in/labs/cse10/dmc.html
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersQuestions on Cache Mapping Techniques with Ashish Verma | 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:0037:09 / 58:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=lz3J33WzNOo" 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-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65
Plotting Correlation Matrix using Python

26 Nov, 2020
Correlation means an association, It is a measure of the extent to which two variables are related. 
1. Positive Correlation: When two variables increase together and decrease together. They are positively correlated. ‘1’ is a perfect positive correlation. For example – demand and profit are positively correlated the more the demand for the product, the more profit hence positive correlation.
2. Negative Correlation: When one variable increases and the other variable decreases together and vice-versa. They are negatively correlated. For example, If the distance between magnet increases their attraction decreases, and vice-versa. Hence, a negative correlation. ‘-1’  is no correlation
3. Zero Correlation( No Correlation): When two variables don’t seem to be linked at all. ‘0’ is a perfect negative correlation. For Example, the amount of tea you take and level of intelligence.
Step 1: Importing the libraries.
Python3
import sklearnimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd
Step 2: Finding the Correlation between two variables.
Python3
y = pd.Series([1, 2, 3, 4, 3, 5, 4])x = pd.Series([1, 2, 3, 4, 5, 6, 7])correlation = y.corr(x)correlation 
Output:
Step 3: Plotting the graph. Here we are using scatter plots. A scatter plot is a diagram where each value in the data set is represented by a dot. Also, it shows a relationship between two variables.
Python3
# plotting the dataplt.scatter(x, y)  # This will fit the best line into the graphplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))         (np.unique(x)), color='red')
Output:
Remember the points that were explained above. Observe both the images you will find similarity Also, observe the value of the correlation is near to 1, hence the positive correlation is reflected.
Python3
# adds the titleplt.title('Correlation')  # plot the dataplt.scatter(x, y)  # fits the best fitting line to the dataplt.plot(np.unique(x),          np.poly1d(np.polyfit(x, y, 1))         (np.unique(x)), color='red')  # Labelling axesplt.xlabel('x axis')plt.ylabel('y axis')
Output:
There are many ways you can plot correlation matrices one efficient way is using the heatmap. It is very easy to understand the correlation using heatmaps it tells the correlation of one feature(variable) to every other feature(variable). In other words, A correlation matrix is a tabular data representing the ‘correlations’ between pairs of variables in a given data.
Python3
import seaborn as sns  # checking correlation using heatmap#Loading datasetflights = sns.load_dataset("flights")  #ploting the heatmap for correlationax = sns.heatmap(flights.corr(), annot=True)
Output:
Python-matplotlib
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PIL | ImageDraw.Draw.rectangle()

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.rectangle() Draws an rectangle.
Syntax: PIL.ImageDraw.Draw.rectangle(xy, fill=None, outline=None)Parameters:
xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1]. The second point is just outside the drawn rectangle.outline – Color to use for the outline.fill – Color to use for the fill.
Returns: An Image object in rectangle shape.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw  w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]  # creating new Image objectimg = Image.new("RGB", (w, h))  # create rectangle imageimg1 = ImageDraw.Draw(img)  img1.rectangle(shape, fill ="# ffff33", outline ="red")img.show()
Output:
Another Example: Here we use different colour for filling.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw  w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]  # creating new Image objectimg = Image.new("RGB", (w, h))  # create  rectangleimageimg1 = ImageDraw.Draw(img)  img1.rectangle(shape, fill ="# 800080", outline ="green")img.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js process.argv Property

12 Oct, 2021
The process.argv property is an inbuilt application programming interface of the process module which is used to get the arguments passed to the node.js process when run in the command line.
Syntax:
process.argv
Return Value: This property returns an array containing the arguments passed to the process when run it in the command line. The first element is the process execution path and the second element is the path for the js file.
Below examples illustrate the use of process.argv property in Node.js:
Example 1:
// Node.js program to demonstrate the// process.argv Property   // Include process moduleconst process = require('process');  // Printing process.argv property valueconsole.log(process.argv);
Command to run the code:
node index.js extra_argument1 extra_argument2 3
Output:
[ 'C:\\Program Files\\nodejs\\node.exe',
  'C:\\nodejs\\g\\process\\argv_1.js',
  'extra_argument1',
  'extra_argument2',
  '3' 
]

Example 2:
// Node.js program to demonstrate the// process.argv Property   // Include process moduleconst process = require('process');  // Printing process.argv property valuevar args = process.argv;  console.log("number of arguments is "+args.length);  args.forEach((val, index) => {    console.log(`${index}: ${val}`);});
Command to run the code:
node index.js extra_argument1 extra_argument2 3
Output:
number of arguments is 5
0: C:\Program Files\nodejs\node.exe
1: C:\nodejs\g\process\argv_2.js
2: extra_argument1
3: extra_argument2
4: 3

Note: The above program will compile and run by using the node filename.js command followed by arguments.
Reference: https://nodejs.org/api/process.html#process_process_argv
Node.js-process-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Securing Django Admin login with OTP (2 Factor Authentication)

01 Nov, 2020
Multi factor authentication is one of the most basic principle when adding security for our applications. In this tutorial, we will be adding multi factor authentication using OTP Method. This article is in continuation of Blog CMS Project in Django. Check this out here – Building Blog CMS (Content Management System) with Django
We will install TOTP package for our blog CMS which will add OTP security for our admin login. First install django-otp package
pip install django-otp
 and add ‘django_otp, django_otp.plugins.otp_totp‘ in our installed apps and django_otp.middleware.OTPMiddleware in middleware section of our settings file. 
Python3
INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'django_otp',    'django_otp.plugins.otp_totp'  ]  MIDDLEWARE = [    'django.middleware.security.SecurityMiddleware',    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.common.CommonMiddleware',    'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.clickjacking.XFrameOptionsMiddleware',    'django_otp.middleware.OTPMiddleware']
Now run,
# migrate our app
python3 manage.py migrate
Now log into django admin to create an TOTP device. You can see it after logging in
login page
Click add and fill the details to create a new TOTP qrcode
add TOTP devices
 Now again go into totp device section and open the QRcode and scan it with your TOTP apps like Authy, Google Authenticator apps.
scan the qrcode
Now go into django urls.py file in gfgblog, not in blog urls.py and add the lines
Python3
from django_otp.admin import OTPAdminSite  admin.site.__class__ = OTPAdminSite
Now logout and login into django admin you have enter OTP everytime you need to login into django admin.
django admin with OTP
Keep Debug = False in Production
Limit Allowed hosted to our Server IP, localhost, and hostnames
Keep Secret key strong and safe
All ways use HTTPS  in Production
Keep a check on user uploads if being managed by multiple users
Keep your database secure and don’t use SQLite in Production
Try to use Security and content headers in production, a few headers are given below add these in Settings.py
Python3
SECURE_SSL_REDIRECT = TrueSESSION_COOKIE_SECURE = TrueSESSION_COOKIE_SECURE = TrueSECURE_BROWSER_XSS_FILTER = TrueSECURE_HSTS_SECONDS = 31536000SECURE_HSTS_INCLUDE_SUBDOMAINS = TrueSECURE_HSTS_PRELOAD = TrueSECURE_CONTENT_TYPE_NOSNIFF = TrueCSRF_COOKIE_SECURE = True
Python Django
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Enumerable group_by() function

05 Dec, 2019
The group_by() of enumerable is an inbuilt method in Ruby returns an hash where the groups are collectively kept as the result of the block after grouping them. In case no block is given, then an enumerator is returned.
Syntax: enu.group_by { |obj| block }
Parameters: The function takes an optional block according to which grouping is done.
Return Value: It returns a hash.
Example #1:
# Ruby program for group_by method in Enumerable  # Initialize enu = (1..10)  # Printsenu.group_by { |obj| obj % 4 == 1 }
Output:
{true=>[1, 5, 9], false=>[2, 3, 4, 6, 7, 8, 10]}

Example #2:
# Ruby program for group_by method in Enumerable  # Initialize enu = [2, 8, 9, 10, 23]  # Printsenu.group_by { |obj| obj % 6 }
Output:
{2=>[2, 8], 3=>[9], 4=>[10], 5=>[23]}

Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.