code-rag-bench/online-tutorials huggingface dataset:
How to delete Tkinter widgets from a window?

Sometimes, we want to remove a widget that is of no use in the application. We can delete widgets from the window or frame using the .destroy method in tkinter. It can be invoked in the widget by defining a function for it.
In this example, we have created a button that will remove the text label widget from the window.
#Import the tkinter library
from tkinter import *

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

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

#Define a function to remove the text from the screen
def delete_text():
   text.destroy()

#Create a text widget
text= Label(win,text="This is a New Line", font=('Aerial bold', 20))
text.pack(pady=20)

#Create a button for Deleting Widget
Button(win, text= "Click Here", font=('bold',20), command=
delete_text).pack(pady=10)

win.mainloop()
Running the above code will produce the following output −
Now, click the "Click Here" button. It will delete the Label Text widget from the window.
Python | Pandas Timestamp.day

08 Jan, 2019
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.
Pandas Timestamp.day attribute return the value of the day in the given Timestamp object.
Syntax : Timestamp.day
Parameters : None
Return : day
Example #1: Use Timestamp.day attribute to find the day value in the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(2017, 1, 15, 12)  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.day attribute to find out the day value in the given Timestamp object.
# return day valuets.day
Output :
As we can see in the output, the Timestamp.day attribute has returned 15 indicating that it is the 15th day of the month in the given Timestamp object. Example #2: Use Timestamp.day attribute to find the day value in the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 10,         day = 21, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.day attribute to find out the day value in the given Timestamp object.
# return day valuets.day
Output :
As we can see in the output, the Timestamp.day attribute has returned 21 indicating that it is the 21st day of the month in the given Timestamp object.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2017 (Set 1) | Question 27

28 Jun, 2021
Consider the following C code:
#include <stdio.h>

int * assignval (int *x, int val)
{
    *x = val;
    return x;
}

int main()
{
    int *x = malloc(sizeof(int));
    if (NULL == x) return;
    x = assignval(x, 0);
    if(x)
    {
        x = (int*) malloc(sizeof (int));
        if (NULL == x) return;
        x = assignval (x, 10);
    }
    printf("%d\n", *x);
    free(x);
}

The code suffers from which one of the following problems:(A) compiler error as the return of malloc is not typecast appropriately.(B) compiler error because the comparison should be made as x==NULL and not as shown.(C) compiles successfully but execution may result in dangling pointer.(D) compiles successfully but execution may result in memory leak.Answer: (D)Explanation: The code will run and give output = 10, so option A and B are discarded.
 int * x= malloc (sizeof(int));
This statement assigns a location to x. Now,
(int*)malloc(sizeof(int));
again assigns a new location to x , previous memory location is lost because now we have no reference to that location resulting in memory leak.
Therefore, option D is correct.
Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.Detailed article on Memory Leak
Running code of the question:
#include<stdio.h>int *assignval (int *x, int val) {    *x = val;    return x;}  void main () {    int *x = malloc(sizeof(int));    if (NULL == x) return;    x = assignval (x,0);    if (x)    {        x = (int *)malloc(sizeof(int));        if (NULL == x) return;        x = assignval (x,10);    }    printf("%d\n", *x);    free(x);}
Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2010 | Question 61

28 Jun, 2021
Hari(H), Gita(G), Irfan(I) and Saira(S) are siblings (i.e., brothers and sisters). All were born on 1st January. The age difference between any two successive siblings (that is born one after another) is less than 3 years. Given the following facts:
i.  Hari's age + Gita's age > Irfan's age + Saira's age 
ii. The age difference between Gita and Saira is 1 year. However Gita is not
    the oldest and Saira is not the youngest. 
iii. There are no twins. 
In what order were they born (oldest first)?(A) HSIG(B) SGHI(C) IGSH(D) IHSGAnswer: (B)Explanation: H + G > I + SG – S = 1 OR S – G = 1
G is not the oldest and S is not the youngest.
We need to try all options one by one.Quiz of this Question
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2004 | Question 31
Python | Pandas DataFrame.loc[]

20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.loc attribute access a group of rows and columns by label(s) or a boolean array in the given DataFrame.
Syntax: DataFrame.loc
Parameter : None
Returns : Scalar, Series, DataFrame
Example #1: Use DataFrame.loc attribute to access a particular cell in the given Dataframe using the index and column labels.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],                   'Age':[14, 25, 55, 8, 21]})  # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.loc attribute to return the value present in the ‘Name’ column corresponding to the ‘Row_2’ label.
# return the valueresult = df.loc['Row_2', 'Name']  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.loc attribute has successfully returned the value present at the desired location in the given DataFrame. Example #2: Use DataFrame.loc attribute to return two of the column in the given Dataframe.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1],                    "B":[7, 2, 54, 3, None],                    "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})   # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.loc attribute to return the values present in the ‘A’ and ‘D’ column of the Dataframe.
# return the values.result = df.loc[:, ['A', 'D']]  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.loc attribute has successfully returned the desired columns of the dataframe.
Python pandas-dataFrame
Python pandas-dataFrame-methods
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
Statistical Functions in Python

Python has ability to solve the mathematical expression,statistical data by importing statistic keyword. Python can do various types of statistical and mathematical operations.
These functions calculate the average value from a sample or population.
This function calculates the arithmetic mean or average value of sample data in sequence or iterator.
list = [1, 2, 3,3,4,5,] 
print ("The mean values is : ",end="") 
print (statistics.mean(list))
The mean value is : 3 

This function calculates a sequential or iterative real- valued numbers (harmonic_ mean).
list = [1,2,3]
print ("The harmonic _mean values is : ",end="") 
print (statistics.harmonic_mean(list))
The harmonic _mean values is :1.6

This function calculates middle value of thearithmetic data in iterative order.
list= [1, 3,5,7] 
print ("The median values is : ",end="")
print (statistics.median(list))
The median values is :4.0

This function calculates the median of data in case of odd number but in case of even number of elements it calculates the lower of two middle elements of the data.
list = [1,2,2,3,3,3]
print ("The median_low values is : ",end="") 
print (statistics.median_low(list))
The median_low values is :2

This function calculates the median of data incase of odd number, but in case of even number of elements, it calculates the higher of two middle elements of the data.
list = [1,2,2,3,3,3]
print ("The median_high values is : ",end="") 
print (statistics.median_high(list))
The median_high values is :3

This function is used to calculate median of the groped data also calculate 50th  percentile of the grouped data
list = [2,2,3,4]
print ("The median_grouped values is : ",end="") 
print (statistics.median_grouped(list))
The median_grouped values is : 2.5

This function return the most common data point from discrete or nominal data or number with maximum number of occurrences.
list = [2,2,3,4,4,1,2]
print ("The mode values is : ",end="") 
print (statistics.mode(list))
The mode values is : 2
Practical Uses of nc(netcat) command in Linux

05 Jun, 2020
Netcat is one of the powerful networking tool, security tool or network monitoring tool. It acts like cat command over a network. It is even considered as a Swiss army knife of networking tools.It is generally used for the following reasons:
Operation related to TCP, UDP or UNIX-domain sockets
Port Scanning
Port listening
Port redirection
open Remote connections
Read/Write data across network
Network debugging
Network daemon testing
Simple TCP proxies
A Socks or HTTP Proxy Command for ssh
It is designed by keeping in mind that it should be a flexible “back-end” tool that can be used directly or driven by any other program.
To install the Netcat tool use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install netcat
In case of CentOS/RHEL
$yum install nc 
In case of Fedora 22+ and RHEL 8
$dnf install nc
1. To start listening on a port, first Open 2 terminal windows.
Terminal 1 for listening
$nc -l -p 1234

Terminal 2 sending request
$nc 127.0.0.1 1234

Note: Here the port number is 1234 and by default host is localhost.
It will not display anything but will start listening to port 1234 at the localhost from terminal 1. And anything entered in terminal 2 will be reflected back in terminal 1 as well which confirms that the connection is established successfully.
2. To transfer data. Open 2 terminal windows.
Terminal 1 for listening
$nc -l -p 1234 >output.txt

Terminal 2 for sending request
$echo "GeeksforGeeks" >input.txt
$nc 127.0.0.1 1234 <input.txt

Note: Here the port number is 1234 and by default host is localhost. It will send the input.txt file’s data from terminal 2 to the output.txt file at terminal 1.
3. To perform Port Scanning. Enter the following command on the terminal.
Scanning a single port
$netcat -z -v 127.0.0.1 1234
Scanning multiple ports
$nc -z -v 127.0.0.1 1234 1235
Scanning a range of ports
$nc -z -v 127.0.0.1 1233-1240
Note: Here the port numbers are 1234, 1235, 1233, and 1240 you may change them as per your need. It will display the port number with the status(open or not).
4. To send an HTTP Request
$printf “GET /nc.1 HTTPs/1.1\r\nHost: www.geeksforgeeks.org\r\n\r\n” | nc www.geeksforgeeks.org 80
Note: Here the website is www.geeksfrogeeks.org, you may choose any. It will send a HTTP Request to www.geeksfrogeeks.org.
5. To delay the interval for lines sent. Open 2 terminal as shown below:
Terminal 1 for listening
$nc -l -p 1234

Terminal 2 sending request
$nc -i 5 127.0.0.1 1234

Note: Here the port number is 1234 and by default host is localhost. The time taken is 5 seconds. Each will be sent after 5 seconds of time.
manav014
linux-command
Linux-networking-commands
Linux-Unix
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# - Multidimensional Arrays

C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. You can declare a 2-dimensional array of strings as −
string [,] names;

or, a 3-dimensional array of int variables as −
int [ , , ] m;

The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional array is a list of one-dimensional arrays.
A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns −
Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in array a.
Multidimensional arrays may be initialized by specifying bracketed values for each row. The Following array is with 3 rows and each row has 4 columns.
int [,] a = new int [3,4] {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};
An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array. For example,
int val = a[2,3];
The above statement takes 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us check the program to handle a two dimensional array −
using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         /* an array with 5 rows and 2 columns*/
         int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
         int i, j;
         
         /* output each array element's value */
         for (i = 0; i < 5; i++) {
            
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
How to hide/show HTML elements in JavaScript?

Using Css style we can hide or show HTML elements in javascript. Css provides properties such as block and none to hide/show the HTML elements.
In the following example when the "Hideme" button has clicked the text in the paragraph tag has been disappeared as shown in the output.
Live Demo
<html>
<body>
   <p id="hide">Using JavaScript to hide HTML elements.</p>
   <input type="button" onclick="document.getElementById('hide').style.display='none' value="Hideme">
</body>
</html>
Once the above code is executed, the following will be displayed
From the above block, If we click on the "Hideme" button, the text present in the block will be disappeared as shown in the output, leaving only the button.
In the following example, the text in the paragraph tag is initially hidden but when the "Showme" is clicked the text has appeared as shown in the output.
Live Demo
<html>
<body>
   <p id="show" style="display:none">JavaScript can show hidden HTML elements</p>
   <input type="button"onclick="document.getElementById('show').style.display='block'"value="ShowMe">
</body>
</html>
Once the above code is executed, the following will be displayed on the screen
If we click the above button the following output will be executed
How to write data into EEPROM with Arduino?

Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data.
We will see how to write data to the EEPROM in this example. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from − File → Examples → EEPROM.
We will look at the eeprom_write example. It is quite straightforward, thanks to the EEPROM library. A word of caution here. Please use the .write() function frugally. Each EEPROM has a limited number of write cycles (~100,000) per address. If you write excessively to the EEPROM, you will reduce the lifespan of the EEPROM.
We begin with the inclusion of the library.
#include <EEPROM.h>
Next, a global variable is defined for the EEPROM address field (the address to which you will write)
int address = 0;
Within the setup, we do nothing.
void setup() {
   /** Empty setup. **/
}
In the loop, we read data from an Analog Input (replace the pin number with the pin to which you have connected some analog sensor). We divide that value by 4, because analogRead values are from 0 to 1023, while one byte can store values from 0 to 255. We write this value to EEPROM using the EEPROM.write() function, which takes in two arguments: address to which to write, and the value to be written. We then increment the address and repeat this. If this address reaches the end of EEPROM memory, we go back to the beginning (addr = 0).
void loop() {
   int val = analogRead(A0) / 4;

   EEPROM.write(addr, val);

   addr = addr + 1;
   if (addr == EEPROM.length()) {
      addr = 0;
   }
   delay(100);
}
If you need to write value to a specific address, you can just provide that address as the argument in EEPROM.write().
Count all Palindrome Sub-Strings in a String in C++

In this tutorial, we will be discussing a program to find the number of palindrome sub strings in a string.
For this we will be given a string. Our task is to count the number of palindrome sub strings in the given string with length greater than 3.
#include<bits/stdc++.h>
using namespace std;
//counting palindrome strings
int count_pstr(char str[], int n){
   int dp[n][n];
   memset(dp, 0, sizeof(dp));
   bool P[n][n];
   memset(P, false , sizeof(P));
   for (int i= 0; i< n; i++)
      P[i][i] = true;
   for (int i=0; i<n-1; i++) {
      if (str[i] == str[i+1]) {
         P[i][i+1] = true;
         dp[i][i+1] = 1 ;
      }
   }
   for (int gap=2 ; gap<n; gap++) {
      for (int i=0; i<n-gap; i++) {
         int j = gap + i;
         //if current string is palindrome
         if (str[i] == str[j] && P[i+1][j-1] )
            P[i][j] = true;
         if (P[i][j] == true)
            dp[i][j] = dp[i][j-1] + dp[i+1][j] + 1 - dp[i+1][j-1];
         else
            dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1];
      }
   }
   return dp[0][n-1];
}
int main(){
   char str[] = "abaab";
   int n = strlen(str);
   cout << count_pstr(str, n) << endl;
   return 0;
}
3
Python dictionary keys() Method

Python dictionary  method keys() returns a list of all the available keys in the dictionary.
Following is the syntax for keys() method −
dict.keys()

NA
NA
This method returns a list of all the available keys in the dictionary.
The following example shows the usage of keys() method.
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %  dict.keys()
When we run above program, it produces following result −
Value : ['Age', 'Name']


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to host a web-service using IIS (windows) and .net

A web service is any piece of software which offers service to other systems. It makes itself available over the internet and uses a standardized XML or, JSON messaging system. A web service enables communication among various applications by using open standards such as HTML, XML, WSDL, and SOAP.
IIS stands for, Internet Information Services, it is a web service software create by Microsoft. It is available with the Windows (NT) operating systems, it supports HTTP, HTTP/2, HTTPS, FTP, FTPS, SMTP and NNTP.
Here we are going to discuss how create and launch a web service locally and send request to it.
If your operating system is Windows NT IIS is available with in the operating system (else you need to download it manually). To install it −
Open Control Panel →(Programs) →Programs and Features and click on Turn Windows features on or off.
In the Windows Features window make sure you turned the .Net Freamework Advanced featured Services and all the features in the Web management tools on. 
 
 
On clicking OK the selected components will be installed.
Once you installed IIS you need to setup, to do so −
Open IIs application, Expand the tree view on the left-hand side of the window.
Right click on the Sites folder and click on Add Website.
In the Add Web site wizard, add required name for the service in the Site name text box, set the Application Pool value to DefaultAppPool, add a four-digit number in the Port text box. Finally create a folder to store the application (with a sample HTML file) and choose the created location under Physical path: and click on
 
This will create the specified website with given details and you can see the created folder under the Sites tree view.
Finally, before sending request to a page in the created server, you need to enable directory browsing, to do so −
Click on the created app (in this case testApp).
On the right side under IIS double click Directory Browsing.
  
Finally, Click Enable under action and save the changes.
If everything goes fine if you send request to the host along with the port you can see the contents of the created as shown below −
Following web service have two methods −
The getAge accepts a year, month and day representing the date of birth of a person and calculates the age (in days).
And a SayHello method displaying a simple message
<%@ WebService language = "C#" class = "SampleService" %>
 using System;
using System.Web.Services;
using System.Xml.Serialization;
 [WebService(Namespace = "http://localhost/SampleWebService/")]
public class SampleService : WebService{
   [WebMethod]
   public int getAge(int year, int month, int day) {
      DateTime dob = new DateTime(year, month, day);        
      DateTime today = DateTime.Now;
       
      //Getting the difference
      TimeSpan span = today.Subtract(dob);
      return span.Days;
   } 
   [WebMethod]
   public String SayHello() {
      return "Hello World";
   }
}
You need to place this file in the created webservice folder.
C++ Valarray Library - pow Function

It returns a valarray containing the results of the power operation on all the elements, in the same order. The results calculated are x raised to the power y (xy).
Following is the declaration for std::pow function.
template<class T> valarray<T> log10 (const valarray<T>& x);
template<class T> valarray<T> log10 (const valarray<T>& x);
x − It is containing elements of a type for which the unary function abs is defined.
x − It is containing elements of a type for which the unary function abs is defined.
y − It is a valarray element with the exponents for the power operations.
y − It is a valarray element with the exponents for the power operations.
It returns a valarray containing the results of the power operation on all the elements, in the same order. The results calculated are x raised to the power y (xy).
Basic guarantee − if any operation performed on the elements throws an exception.
All elements effectively copied are accessed.
In below example explains about std::pow function.
#include <iostream>
#include <cstddef>
#include <cmath>
#include <valarray>

int main () {
   std::valarray<double> val (10);
   std::valarray<double> results;

   for (int i=0; i<10; ++i) val[i]=i+1;
   std::cout << "val:";
   for (std::size_t i=0; i<val.size(); ++i) std::cout << ' ' << val[i];
   std::cout << '\n';

   results = std::pow (val,val);
   std::cout << "val^val:";
   for (std::size_t i=0; i<results.size(); ++i) std::cout << ' ' << results[i];
   std::cout << '\n';

   results = std::pow (val,2.0);
   std::cout << "val^2:";
   for (std::size_t i=0; i<results.size(); ++i) std::cout << ' ' << results[i];
   std::cout << '\n';

   results = std::pow (2.0,val);
   std::cout << "2^val:";
   for (std::size_t i=0; i<results.size(); ++i) std::cout << ' ' << results[i];
   std::cout << '\n';

   return 0;
}
Let us compile and run the above program, this will produce the following result −
val: 1 2 3 4 5 6 7 8 9 10
val^val: 1 4 27 256 3125 46656 823543 1.67772e+07 3.8742e+08 1e+10
val^2: 1 4 9 16 25 36 49 64 81 100
2^val: 2 4 8 16 32 64 128 256 512 1024

 Print
 Add Notes
 Bookmark this page
Binary Insertion Sort in C++

Binary Insertion sort is a special type up of Insertion sort which uses binary search algorithm to find out the correct position of the inserted element in the array.
Insertion sort is sorting technique that works by finding the correct position of the element in the array and then inserting it into its correct position.
Binary search is searching technique that works by finding the middle of the array for finding the element.
As the complexity of binary search is of logarithmic order, the searching algorithm’s time complexity will also decrease to of logarithmic order.
Implementation of binary Insertion sort. this program is a simple Insertion sort program but instead of the standard searching technique binary search is used.
#include <iostream>
using namespace std;
int binarySearch(int arr[], int item, int low, int high) {
   if (high <= low)
      return (item > arr[low])? (low + 1): low;
      int mid = (low + high)/2;
   if(item == arr[mid])
      return mid+1;
   if(item > arr[mid])
      return binarySearch(arr, item, mid+1, high);
      return binarySearch(arr, item, low, mid-1);
}
void BinaryInsertionSort(int arr[], int n) {
   int i, loc, j, k, selected;
   for (i = 1; i < n; ++i) {
      j = i - 1;
      selected = arr[i];
      loc = binarySearch(arr, selected, 0, j);
      while (j >= loc) {
         arr[j+1] = arr[j];
         j--;
      }
      arr[j+1] = selected;
   }
}
int main() {
   int arr[] = {12, 56, 1, 67, 45, 8, 82, 16, 63, 23};
   int n = sizeof(arr)/sizeof(arr[0]), i;
   BinaryInsertionSort(arr, n);
      cout<<"Sorted array is : \n";
   for (i = 0; i < n; i++)
      cout<<arr[i]<<"\t";
   return 0;
}
Sorted array is :
1 8 12 16 23 45 56 63 67 82
How to rotate Matplotlib annotation to match a line?

To rotate matplotlib annotation to match a line, we can take the following steps−
Create a new figure or activate an existing figure using figure() method.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot() method.
Initialize the variables, m (slope) and c (intercept).
Create x and y data points using numpy.
Calculate theta to make text rotation.
Plot the line using plot() method with x and y.
Place text on the line using text() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot()
m = 1
c = 1
x = np.linspace(-2, 2, 10)
y = m*x + c
theta = np.arctan(m)
line, = ax.plot(x, y)
ax.text(x=x[2], y=y[2]+.25, s="y=mx+c", rotation=180.0*(1-theta), fontsize=15, color='green')
plt.show()
How to input multiple values from user in one line in Python? - GeeksforGeeks

19 Nov, 2020
For instance, in C we can do something like this:
// Reads two values in one linescanf("%d %d", &x, &y) 
One solution is to use raw_input() two times.
x, y = input(),  input()
Another solution is to use split()
x, y = input().split()
Note that we don’t have to explicitly specify split(‘ ‘) because split() uses any whitespace characters as a delimiter as default.
One thing to note in the above Python code is, both x and y would be of string. We can convert them to int using another line
x, y = [int(x), int(y)]

# We can also use  list comprehension
x, y = [int(x) for x in [x, y]]

Below is complete one line code to read two integer variables from standard input using split and list comprehension
# Reads two numbers from input and typecasts them to int using # list comprehensionx, y = [int(x) for x in input().split()]  
# Reads two numbers from input and typecasts them to int using # map functionx, y = map(int, input().split())
This article is contributed by Abhishek Shukla. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
dev_aditya
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to add a new field to all the documents in a MongoDB collection

To add a new field, use $addFields in MongoDB. Let us create a collection with documents −
> db.demo712.insertOne({"Name":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85f675d33e20ed1097b82")
}
> db.demo712.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85f6a5d33e20ed1097b83")
}
> db.demo712.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea85f6e5d33e20ed1097b84")
}
Display all documents from a collection with the help of find() method −
> db.demo712.find();
This will produce the following output −
{ "_id" : ObjectId("5ea85f675d33e20ed1097b82"), "Name" : "John" }
{ "_id" : ObjectId("5ea85f6a5d33e20ed1097b83"), "Name" : "Chris" }
{ "_id" : ObjectId("5ea85f6e5d33e20ed1097b84"), "Name" : "Bob" }
Following is the query to add a new field −
> db.demo712.aggregate([
...    {
...       $addFields:
...       {
...          "TeacherName":"Robert"
...       }
...    }
... ]
... );
This will produce the following output −
{ "_id" : ObjectId("5ea85f675d33e20ed1097b82"), "Name" : "John", "TeacherName" : "Robert" }
{ "_id" : ObjectId("5ea85f6a5d33e20ed1097b83"), "Name" : "Chris", "TeacherName" : "Robert" }
{ "_id" : ObjectId("5ea85f6e5d33e20ed1097b84"), "Name" : "Bob", "TeacherName" : "Robert" }
How to create a strikethrough text using JavaScript?

To create a strikethrough text with JavaScript, use the strike() method. This method causes a string to be displayed as struck-out text as if it were in a <strike> tag.
You can try to run the following code to create a strikethrough text −
Live Demo
<html>
   <head>
      <title>JavaScript String strike() Method</title>
   </head>

   <body>
      <script>
         var str = new String("Demo Text");
         document.write(str.strike());
         alert(str.strike());
      </script>
   </body>
</html>
C Program to print “Hello World!” without using a semicolon

Let us see how to write a C program in which we can print the text “Hello World” without using any
semicolon.
We can simply write the text by using the line printf(“Hello World”); in the main() function.
But there is a semicolon at the end of the line. To avoid the semicolon, we can follow some trick. We
can use the same printf() statement inside if condition. As the printf() statement returns the length
of the text, so it is non zero value, so the if statement will be true. Thus the text will be written on
screen.
#include<stdio.h>
main() {
   if(printf("Hello World")) {
   }
}
Hello World
How to get latest set of data from a MongoDB collection based on the date records?

To get the latest set of data from data records, use sort() and -1. For only a single data i.e. document, use LIMIT(1). Let us create a collection with documents −
> db.demo521.insertOne({"PurchaseDate":new ISODate("2019-01-10"),"ProductName":"Product-1"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e89a1acb3fbf26334ef6117")
}
> db.demo521.insertOne({"PurchaseDate":new ISODate("2020-04-05"),"ProductName":"Product-10"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e89a1b9b3fbf26334ef6118")
}
> db.demo521.insertOne({"PurchaseDate":new ISODate("2010-05-08"),"ProductName":"Product-4"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e89a1c8b3fbf26334ef6119")
}
> db.demo521.insertOne({"PurchaseDate":new ISODate("2020-02-21"),"ProductName":"Product-3"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e89a1d7b3fbf26334ef611a")
}
Display all documents from a collection with the help of find() method −
> db.demo521.find();
This will produce the following output −
{ "_id" : ObjectId("5e89a1acb3fbf26334ef6117"), "PurchaseDate" : ISODate("2019-01-10T00:00:00Z"), "ProductName" : "Product-1" }
{ "_id" : ObjectId("5e89a1b9b3fbf26334ef6118"), "PurchaseDate" : ISODate("2020-04-05T00:00:00Z"), "ProductName" : "Product-10" }
{ "_id" : ObjectId("5e89a1c8b3fbf26334ef6119"), "PurchaseDate" : ISODate("2010-05-08T00:00:00Z"), "ProductName" : "Product-4" }
{ "_id" : ObjectId("5e89a1d7b3fbf26334ef611a"), "PurchaseDate" : ISODate("2020-02-21T00:00:00Z"), "ProductName" : "Product-3" }
Following is the query to get the latest set of data based on the date −
> db.demo521.find().sort({"PurchaseDate": -1}).limit(1);
This will produce the following output −
{ "_id" : ObjectId("5e89a1b9b3fbf26334ef6118"), "PurchaseDate" : ISODate("2020-04-05T00:00:00Z"), "ProductName" : "Product-10" }
How to add 30 minutes to a JavaScript Date object?

To add minutes to a JavaScript Date object, use the setMinutes() method. Under that, get the current minutes and 30 minutes to it. JavaScript date setMinutes() method sets the minutes for a specified date according to local time.
You can try to run the following code to add 30 minutes to date.
 Live Demo
<html>
   <head>
      <title>JavaScript setMinutes Method</title>
   </head>
   <body>
      <script>
         var dt = new Date();
         dt.setMinutes( dt.getMinutes() + 30 );
         document.write( dt );
      </script>
   </body>
</html>
Sat Dec 15 2018 12:18:47 GMT+0530 (India Standard Time)
wcscpy() function in C++ with Examples

03 Oct, 2018
The wcscpy() function is defined in cwchar.h header file. The wcscpy() function is used to copy a wide character string from source to destination.
Syntax:
wchar_t *wcscpy(wchar_t *dest, const wchar_t *src);
Parameters: This method accepts the following two parameters:
dest: specifies the pointer to the destination array.
src: specifies the pointer to the source array.
Return Value: The wcscpy() function returns the modified destination.
Below program illustrate the above function:-
Example:-
// C++ program to demonstrate// example of wcscpy() function.  #include <bits/stdc++.h>using namespace std;  int main(){      // maximum length of the destination string    wchar_t dest[40];       // initialize the source string    wchar_t src[]=L"A computer science portal for geeks";  // Print the source string    wcout << L"Source: " << src << endl;  // Print the destination string    wcout << L"Destination: " << dest << endl;  // Copy source to destination    wcscpy(dest, src);  // Print the modified destination    wcout << L"After modification, destination: " << dest;      return 0;}
Source: A computer science portal for geeks
Destination: 
After modification, destination: A computer science portal for geeks

CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Inheritance in C++
Object Oriented Programming in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
SQL Drop Table Statement

27 Sep, 2021
SQL is a programming language used to manipulate data that are stored in the database. It is flexible and user-friendly. In SQL, to interact with the database, the users have to type queries that have certain syntax, e.g., the drop command. The drop command in SQL is used to remove the whole table including data present inside it, indexes, triggers, constraints, and permission specifications for that particular table. It is basically a DDL(data definition language) which is irreversible in nature. It means that once the user drops a table, there is no way to undo the command. Therefore, the drop command must be used with extensive care. It can also delete a whole database or can simply delete a table, it depends on the wish of the user.
Syntax:
To drop table:
DROP TABLE table_name;
To drop database:
DROP DATABASE database_name;
Example 1: Drop the table
In this example, we will discuss how to drop a table named “categories” from a database named “Newcafe”.
Step 1: Create a database
CREATE DATABASE Newcafe;
Step 2: Use a database
USE Newcafe;
Step 3: Create a table
CREATE TABLE [dbo].[categories]
(
    [CategoryID] INT NOT NULL PRIMARY KEY, 
    [CategoryName] NVARCHAR(50) NOT NULL,
    [ItemDescription] NVARCHAR(50) NOT NULL
);
GO
Add data inside a table
INSERT INTO [dbo].[categories]
( 
    [CategoryID], [CategoryName], [ItemDescription]
)
VALUES
( 
    1, 'Beverages', 'SoftDrink'
),
( 
    2, 'Condiments', 'Sweet and Savoury sauces'
), 
( 
    3, 'Confections', 'Sweet bread'
)
GO
View the final table:
SELECT * FROM  categories;
Step 4: Drop the categories table
drop table categories;
Example 2: Drop the database
Now we drop the above create the database using the following command:
drop database Newcafe;
abhijithoyur
Picked
Class 12
School Learning
School Programming
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting Algorithms in Python
Cardinality in DBMS
Querying Data from a Database using fetchone() and fetchall()
Intrinsic Semiconductors and Extrinsic Semiconductors
How to Create a Database Connection?
How to Align Text in HTML?
What are Different Output Devices?
Generations of Computers - Computer Fundamentals
Geometric Series
What is a Storage Device? Definition, Types, Examples
Bootstrap 4 .card-img-overlay class

Use the card-img-overlay class to turn an image into a Bootstrap 4 card background and set the image using the <img> element and the card-img-top class −
<img class="card-img-top" src="Image-Source" alt="Alt-Text" style="width:100%">
After that, use the card-img-overlay class −
<div class="card-img-overlay">
  <h4 class="card-title">Avro</h4>
  <p class="card-text">Tutorial for Apache Avro</p>
  <a href="#" class="btn btn-info">Learn</a>
</div>
You can try to run the following code to implement the card-img-overlay class in Bootstrap 4 −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h2>Apach - Tool for Hadoop</h2>
    <div class="card img-fluid" style="width:500px">
      <img class="card-img-top" src="https://www.tutorialspoint.com/avro/images/apache-avro-mini-logo.jpg" alt="Avro" style="width:100%">
      <div class="card-img-overlay">
        <h4 class="card-title">Avro</h4>
        <p class="card-text">Tutorial for Apache Avro</p>
        <a href="#" class="btn btn-info">Learn</a>
      </div>
    </div>
  </div>
</body>
</html>
How to get the unique elements of an array using NumPy?

31 Aug, 2021
Let’s see How to get the unique elements of an array using NumPy. So for finding unique elements from the array we are using numpy.unique() function of NumPy library.
Syntax: np.unique(Array)Return: Return the unique of an array. 
Now, Let’s see the examples:
Example 1:
Python3
# import libraryimport numpy as np             # create 1d-arrayarr = np.array([3, 3, 4,                5, 6, 5,                6, 4]) # find unique element# from a arrayrslt = np.unique(arr) print(rslt)
Output:
[3 4 5 6]
Example 2:
Python3
# import libraryimport numpy as np # create a numpy 2d-arrayarr = np.array([[9, 9, 7, 7],              [3, 4, 3, 4]]) # find unique element# from a arrayrslt = np.unique(arr) print(rslt)
Output:
[3 4 7 9] 
kalrap615
Python numpy-arrayManipulation
Python numpy-program
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
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
C# | Check if ListDictionary has a fixed size

01 Feb, 2019
ListDictionary.IsFixedSize property is used to get a value indicating whether the ListDictionary has a fixed size or not.
Syntax:
public bool IsFixedSize { get; }

Return Value : This property always returns false.
Example:
// C# code to check if ListDictionary// has a fixed sizeusing System;using System.Collections;using System.Collections.Specialized;  class GFG {      // Driver code    public static void Main()    {          // Creating a ListDictionary named myDict        ListDictionary myDict = new ListDictionary();          myDict.Add("Australia", "Canberra");        myDict.Add("Belgium", "Brussels");        myDict.Add("Netherlands", "Amsterdam");        myDict.Add("China", "Beijing");        myDict.Add("Russia", "Moscow");        myDict.Add("India", "New Delhi");          // Checking if ListDictionary has a fixed size        Console.WriteLine(myDict.IsFixedSize);    }}
Output:
False

Note:
A collection with a fixed size does not allow the addition or removal of elements after the collection is created, but it allows the modification of existing elements.
A collection with a fixed size is simply a collection with a wrapper that prevents adding and removing elements. Therefore, if changes are made to the underlying collection, including the addition or removal of elements, the fixed-size collection reflects those changes.
Retrieving the value of this property is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.listdictionary.isfixedsize?view=netframework-4.7.2
CSharp-Specialized-ListDictionary
CSharp-Specialized-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
How to Remove Nan Values from a Matrix in MATLAB? - GeeksforGeeks

04 Jul, 2021
Removal of Nan Values from a Matrix.There are multiple methods by which we can remove Nan values from a specified matrix:.
This function is used to remove missing entries or Nan values from a specified matrix.
rmmissing(A)
Parameters: This function accepts a parameter which is illustrated below:
A: This is the specified matrix of elements.
Return Value: It returns the matrix without missing entries or Nan values.
Example: 
Matlab
% MATLAB code for remove NaN % values using rmmissing()A = [1, NaN, 2, 3 NaN, 4]; % Initializing% of matrix   % Calling the rmmissing() function over% the above matrixB = rmmissing(A)
Output:
This function is used to return a matrix of 1 i.e. true for the elements like NaN, and 0 i.e. false when they are not. 
isnan(A)
Parameters: This function accepts a parameter.
A: This is the specified matrix of elements.
Return Value: It returns the matrix of logical values.
Example:
Matlab
% MATLAB code for remove NaN values using isnan()A = [1, 2, NaN, 3, 4]; % Initializing of matrix  % Calling isnan() function and getting matrix% boolean values i.e. 1 or 0B = isnan(A)  % Getting a new matrix "C" without NaN values% which was originally "A"C = A(~B)
Output:
MATLAB
MATLAB-programs
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Boundary Extraction of image using MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Classes and Object in MATLAB
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
Adaptive Histogram Equalization in Image Processing Using MATLAB
Double Integral in MATLAB
Convert string (varchar) to double in MySQL

Let us first create a table:
mysql> create table DemoTable731 (Value varchar(100));
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command -
mysql> insert into DemoTable731 values('4.50');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable731 values('7.83');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable731 values('8.91');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable731 values('560.34');
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement -
mysql> select *from DemoTable731;
This will produce the following output -
+--------+
| Value  |
+--------+
| 4.50   |
| 7.83   |
| 8.91   |
| 560.34 |
+--------+
4 rows in set (0.00 sec)
Here is the query to convert string to double -
mysql> select Value+0.0 AS demo from DemoTable731;
This will produce the following output -
+-----------+
| demo      |
+-----------+
| 4.5       |
| 7.83      |
| 8.91      |
| 560.34    |
+-----------+
4 rows in set (0.28 sec)