code-rag-bench/online-tutorials huggingface dataset:
Database - Second Normal Form (2NF)

The Second Normal Form states that it should meet all the rules for 1NF and there must be no partial dependences of any of the columns on the primary key −
Consider a customer-order relation and you want to store customer ID, customer name, order ID and order detail and the date of purchase −
CREATE TABLE CUSTOMERS(
   CUST_ID    INT              NOT NULL,
   CUST_NAME VARCHAR (20)      NOT NULL,
   ORDER_ID   INT              NOT NULL,
   ORDER_DETAIL VARCHAR (20)  NOT NULL,
   SALE_DATE  DATETIME,
   PRIMARY KEY (CUST_ID, ORDER_ID)
);
This table is in the first normal form; in that it obeys all the rules of the first normal form. In this table, the primary key consists of the CUST_ID and the ORDER_ID. Combined, they are unique assuming the same customer would hardly order the same thing.
However, the table is not in the second normal form because there are partial dependencies of primary keys and columns. CUST_NAME is dependent on CUST_ID and there's no real link between a customer's name and what he purchased. The order detail and purchase date are also dependent on the ORDER_ID, but they are not dependent on the CUST_ID, because there is no link between a CUST_ID and an ORDER_DETAIL or their SALE_DATE.
To make this table comply with the second normal form, you need to separate the columns into three tables.
First, create a table to store the customer details as shown in the code block below −
CREATE TABLE CUSTOMERS(
   CUST_ID    INT              NOT NULL,
   CUST_NAME VARCHAR (20)      NOT NULL,
   PRIMARY KEY (CUST_ID)
);
The next step is to create a table to store the details of each order −
CREATE TABLE ORDERS(
   ORDER_ID   INT              NOT NULL,
   ORDER_DETAIL VARCHAR (20)  NOT NULL,
   PRIMARY KEY (ORDER_ID)
);
Finally, create a third table storing just the CUST_ID and the ORDER_ID to keep a track of all the orders for a customer −
CREATE TABLE CUSTMERORDERS(
   CUST_ID    INT              NOT NULL,
   ORDER_ID   INT              NOT NULL,
   SALE_DATE  DATETIME,
   PRIMARY KEY (CUST_ID, ORDER_ID)
);

    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Aurelia - Event Aggregator

Event aggregator should be used when your events need to be attached to more listeners or when you need to observe some functionality of your app and wait for the data update.
Aurelia event aggregator has three methods. The publish method will fire off events and can be used by multiple subscribers. For subscribing to an event, we can use the subscribe method. And finally, we can use the dispose method to detach the subscribers. The following example demonstrates this.
Our view will just have three buttons for each of the three functionalities.
<template>
   <button click.delegate = "publish()">PUBLISH</button><br/>
   <button click.delegate = "subscribe()">SUBSCRIBE</button><br/>
   <button click.delegate = "dispose()">DISPOSE</button>
</template>
We need to import eventAggregator and inject it before we are able to use it.
import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class App {
   constructor(eventAggregator) {
      this.eventAggregator = eventAggregator;
   }
   publish() {
      var payload = 'This is some data...';
      this.eventAggregator.publish('myEventName', payload);
   }
   subscribe() {
      this.subscriber = this.eventAggregator.subscribe('myEventName', payload => {
         console.log(payload);
      });
   }
   dispose() {
      this.subscriber.dispose();
      console.log('Disposed!!!');
   }
}
We need to click the SUBSCRIBE button to listen for data that will be published in future. Once the subscriber is attached, whenever new data is sent, the console will log it. If we click the PUBLISH button five times, we will see that it is logged every time.
We can also detach our subscriber by clicking the DISPOSE button.
 Print
 Add Notes
 Bookmark this page
Check for string rotation in Java - GeeksforGeeks

11 Dec, 2018
Given two strings s1 and s2, write a snippet to check whether s2 is a rotation of s1. Strings may contain duplicates.
Examples:
Input :  s1 = "ABCD", s2 = "CDAB"
Output : True
String s1 is rotation of s2.

Input :  s1 = "ABAD", s2 = "ADAB"
Output : True

Input : s1 = ABCD, and s2 = ACBD 
Output : False

One simple solution is to search first occurrence of s1 in s2. For every match, check if remaining string matches circularly.
An efficient solution is to concatenate s1 with itself. s2 is a rotation of s1 if and only if it is a substring of the rotated string. In java we can either use string contains or indexOf to check for substring.
// Java program to check if two given strings are//  rotations of each other  class StringRotation {      /* Function checks if passed strings (str1 and str2)       are rotations of each other */    static boolean areRotations(String str1, String str2)    {        // There lengths must be same and str2 must be        // a substring of str1 concatenated with str1.        return (str1.length() == str2.length()) &&                ((str1 + str1).contains(str2));    }      // Driver method    public static void main(String[] args)    {        String str1 = "AACD";        String str2 = "ACDA";          if (areRotations(str1, str2))            System.out.println("Yes");        else            System.out.printf("No");    }}
Yes

Java-String-Programs
Java-Strings
Java
Java Programs
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
PyQt5 - Adding action to the ComboBox - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can add action to the combo box. Action is basically a method called by the combo box when it gets changes these changes can be new item get inserted by user or any item get selected by the user.
In order to do this we will use activated.connect method.
Syntax : combo_box.activated.connect(self.do_something)
Argument : It takes method name which should get called as argument
Return : None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 150, 30)          # geek list        geek_list = ["Sayian", "Super Sayian"]          # making it editable        self.combo_box.setEditable(True)          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # adding action to combo box        self.combo_box.activated.connect(self.do_something)      # method called by combo box    def do_something(self):                  # printing something        print("Something Something")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
When we select any item this get printed
Something Something
Something Something

Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Get emotions of images using Microsoft emotion API in Python - GeeksforGeeks

16 Jul, 2020
The emotions of images like happy, sad, neutral, surprise, etc. can be extracted using Microsoft emotion API for any development purpose.
It is very simple to use and can be called via API through terminal or any of languages like Python or PHP. Microsoft provides free subscription of 30 days for making total of 30,000 requests.The details of the end points and parameters can be found in the documentation.
# Python script to analyze# emotion of imageimport http.client, urllib.requestimport urllib.parse, urllib.errorimport base64, sysimport simplejson as json  # replace with subscription_key# you obtained after registrationsubscription_key = '12f29133caf4406493e81b6a31c47c1a'  headers = {      # Request headers. Replace    # the placeholder key    # below with your    # subscription key.    'Content-Type': 'application/json',    'Ocp-Apim-Subscription-Key': subscription_key,}  params = urllib.parse.urlencode({})  # Replace the URL# below with the# URL of the image# you want to analyze.url1 = 'IMAGE URL TO BE ADDED HERE'body = { 'url': url1 }newbody =str(body)  try:    # NOTE: You must use the same region in your REST call as you used to obtain your subscription keys.    # For example, if you obtained your subscription keys from westcentralus, replace "westus" in the    # URL below with "westcentralus".    conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')    conn.request("POST", "/emotion/v1.0/recognize?%s" % params, newbody, headers)    response = conn.getresponse()    data = response.read()      parsed = json.loads(data)    print ("Response:")    print (json.dumps(parsed, sort_keys=True, indent=2))      # the emotion of image    # will the max value of    # any emotion obtained    # from the different    # scores of each emotion    val = parsed[0]["scores"]    res = max(val, key = val.get)    print ("\nEmotion :: ",res)      conn.close()except Exception as e:    print(e.args)
The sample project using this api is available on SnapLook
Python-projects
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Supervised and Unsupervised learning
Differences between Procedural and Object Oriented Programming
Introduction to Recurrent Neural Network
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Pair plots using Scatter matrix in Pandas - GeeksforGeeks

25 Aug, 2020
Checking for collinearity among attributes of a dataset, is one of the most important steps in data preprocessing. A good way to understand the correlation among the features, is to create scatter plots for each pair of attributes. Pandas has a function scatter_matrix(), for this purpose. scatter_matrix() can be used to easily generate a group of scatter plots between all pairs of numerical features. It creates a plot for each numerical feature against every other numerical feature and also a histogram for each of them.
Syntax : pandas.plotting.scatter_matrix(frame)Parameters :frame : the dataframe to be plotted.
In the example below, we will create scatter plots on this dataset.
The dataset contains prices and other statistics about the houses in the California district.
import pandas as pd  # loading the datasetdata = pd.read_csv('housing.csv')  # inspecting the datadata.info()

RangeIndex: 20640 entries, 0 to 20639
Data columns (total 10 columns):
 #   Column              Non-Null Count  Dtype  
---  ------              --------------  -----  
 0   longitude           20640 non-null  float64
 1   latitude            20640 non-null  float64
 2   housing_median_age  20640 non-null  float64
 3   total_rooms         20640 non-null  float64
 4   total_bedrooms      20433 non-null  float64
 5   population          20640 non-null  float64
 6   households          20640 non-null  float64
 7   median_income       20640 non-null  float64
 8   median_house_value  20640 non-null  float64
 9   ocean_proximity     20640 non-null  object 
dtypes: float64(9), object(1)
memory usage: 1.6+ MB

Let us select three numeric columns; median_house_value, housing_median_age and median_income, for plotting. Note that Pandas plots depend on Matplotlib, so it needs to be imported first.
import matplotlib.pyplot as pltfrom pandas.plotting import scatter_matrix  # selecting three numerical featuresfeatures = ['median_house_value', 'housing_median_age',            'median_income']   # plotting the scatter matrix# with the featuresscatter_matrix(data[features])plt.show()
Each scatter plot in the matrix helps us understand the correlation between the corresponding pair of attributes. As we can see, median_income and median_house_value are quite strongly correlated. The main diagonal contains the histograms for each attribute.
Python pandas-plotting
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to Calculate Mean Absolute Percentage Error in Excel? - GeeksforGeeks

09 Jul, 2021
In statistics, we often use Forecasting Accuracy which denotes the closeness of a quantity to the actual value of that particular quantity. The actual value is also known as the true value. It basically denotes the degree of closeness or a verification process that is highly used by business professionals to keep track records of their sales and exchanges to maintain the demand and supply mapping every year. There are various methods to calculate Forecasting Accuracy.
So, one of the most common methods used to calculate the Forecasting Accuracy is MAPE which is abbreviated as Mean Absolute Percentage Error. It is an effective and more convenient method because it becomes easier to interpret the accuracy just by seeing the MAPE value.
In this article, we are going to see how to calculate Mean Absolute Percentage Error, MAPE in Excel.
The formula to calculate MAPE is :
The above formula can be interpreted as the average value of Absolute Percentage Error (APE) of all the observations in the data set.
Note: The actual value can’t be zero. We can observe from the above formula that if the Actual value becomes zero, it will be undefined.
Example:
Consider the dataset shown below :
The functions needed for formulas in Excel are-
ABS : To calculate the absolute value.
AVERAGE : To calculate the mean.
The steps are :
1. Insert the data set in the Excel sheet.
2. Calculate APE for each individual observation using Excel Formula. The formula will be :
=ABS(Cell_No_Act-Cell_No_Fore)/Cell_No_Act*100

where
ABS : Used to calculate the absolute value
Cell_No_Act : Cell number where Actual value is present
Cell_No_Fore : Cell number where Forecast value is present
Similarly, you can write the formulas for the other entries and get the APE for all the records.
APE
3. Now, simply we need to find the average or the mean value for all these values in order to calculate MAPE.
 The formula to find average value in Excel is :
=AVERAGE(Cell_Range)
The value of MAPE for the given data set is 9.478% approximately. Therefore, we can say that  the average difference between the actual value and forecasted value is 9.478%.
MAPE
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Using CHOOSE Function along with VLOOKUP in Excel
Macros in Excel
Introduction to Excel Spreadsheet
How to Extract the Last Word From a Cell in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
Image Resizing using OpenCV | Python - GeeksforGeeks

15 Mar, 2021
Image resizing refers to the scaling of images. Scaling comes in handy in many image processing as well as machine learning applications. It helps in reducing the number of pixels from an image and that has several advantages e.g. It can reduce the time of training of a neural network as more is the number of pixels in an image more is the number of input nodes that in turn increases the complexity of the model.It also helps in zooming in images. Many times we need to resize the image i.e. either shrink it or scale up to meet the size requirements. OpenCV provides us several interpolation methods for resizing an image. 
Choice of Interpolation Method for Resizing – 
cv2.INTER_AREA: This is used when we need to shrink an image.
cv2.INTER_CUBIC: This is slow but more efficient.
cv2.INTER_LINEAR: This is primarily used when zooming is required. This is the default interpolation technique in OpenCV.
Below is the code for resizing.  
Python3
import cv2import numpy as npimport matplotlib.pyplot as plt image = cv2.imread("C://gfg//tomatoes.jpg", 1)# Loading the image half = cv2.resize(image, (0, 0), fx = 0.1, fy = 0.1)bigger = cv2.resize(image, (1050, 1610)) stretch_near = cv2.resize(image, (780, 540),               interpolation = cv2.INTER_NEAREST)  Titles =["Original", "Half", "Bigger", "Interpolation Nearest"]images =[image, half, bigger, stretch_near]count = 4 for i in range(count):    plt.subplot(2, 2, i + 1)    plt.title(Titles[i])    plt.imshow(images[i]) plt.show()
Output:  
Note: One thing to keep in mind while using the cv2.resize() function is that the tuple passed for determining the size of the new image ((1050, 1610) in this case) follows the order (width, height) unlike as expected (height, width). 
Sourabh_Sinha
subhamskm52
Captain_JackSparrow
idevesh
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Apply uppercase to a column in Pandas dataframe - GeeksforGeeks

06 Dec, 2018
Analyzing a real world data is some what difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important.
One might encounter a situation where we need to uppercase each letter in any specific column in given dataframe. Let’s see how can we Apply uppercase to a column in Pandas dataframe.
Let’s create a dataframe using nba.csv.
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")     # calling head() method  # storing in new variable data_top = data.head(10)     # display data_top
Output:
There are certain methods we can change/modify the case of column in Pandas dataframe. Let’s see how can we apply uppercase to a column in Pandas dataframe using upper() method.
Method #1:
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")       # display data['Name'] = data['Name'].str.upper()  data.head()
Output: 
Method #2: Using lambda with upper() method
# Import pandas package import pandas as pd     # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")     # removing null values to avoid errors  data.dropna(inplace = True)    # Applying upper() method on 'College' columndata['College'].apply(lambda x: x.upper()).head(10)
Output:
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
Reading specific columns of a CSV file using Pandas - GeeksforGeeks

24 Oct, 2020
Let us see how to read specific columns of a CSV file using Pandas. This can be done with the help of the pandas.read_csv() method. We will pass the first parameter as the CSV file and the second parameter the list of specific columns in the keyword usecols. It will return the data of the CSV file of specific columns.
Example 1: Link of the CSV file used: link
Python3
# importing the moduleimport pandas as pd  # read specific columns of csv file using Pandasdf = pd.read_csv("student_scores2.csv", usecols = ['IQ','Scores'])print(df)
Output  
Example 2: Link of the CSV file used: link 
Python3
# importing the moduleimport pandas as pd  # read specific columns of csv file using Pandas df = pd.read_csv("student.csv", usecols = ['Hours','Scores','Pass'])print(df)
Output  
Example 3: Link of the CSV file used: link
Python3
# importing the moduleimport pandas as pd   # read specific columns of csv file using Pandasdf = pd.read_csv("titanic.csv", usecols = ['Survived','Pclass'])print(df)
Output: 
Python pandas-io
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Tensorflow.js tf.squeeze() Function - GeeksforGeeks

31 May, 2021
Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.
The .squeeze() function is used to discard the dimensions of length one out of the shape of a stated tf.Tensor.
Syntax :  
tf.squeeze(x, axis?)
Parameters:  
x: It is the stated tensor input which is to be squeezed, and it can be of type tf.Tensor, TypedArray, or Array.
axis: It is an elective parameter that holds a list of numbers. It squeezes only the stated dimensions in case its specified. Moreover, the dimension index here begins with zero, and it’s a flaw to compress a dimension whose length is not one.
Return Value: It returns the tf.Tensor object.
Example 1:  
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Defining tensor input elementsconst y = tf.tensor([11, 76, -4, 6], [2, 2, 1]);  // Calling squeeze() method and// Printing outputy.squeeze().print();
Output:
Tensor
    [[11, 76],
     [-4, 6 ]]
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Calling squeeze() method with// all its parametervar res = tf.squeeze(tf.tensor(    [2.1, 5.6, 8.6, 7.6],     [4, 1]), [1]);  // Printing outputres.print();
Output:
Tensor
    [2.0999999, 5.5999999, 8.6000004, 7.5999999]
Reference: https://js.tensorflow.org/api/latest/#squeeze
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
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?
HTML | DOM Location hostname Property - GeeksforGeeks

23 Jul, 2019
The Location hostname property in HTML is used to return the hostname of the current URL. The Location hostname property returns a string which contains the domain name, or the IP address of a URL.
Syntax:
It returns the hostname property.location.hostname
location.hostname
It is used to set the hostname property.location.hostname = hostname
location.hostname = hostname
Below program illustrates the Location hostname property in HTML:
Example:
<!DOCTYPE html><html>  <head>    <title>DOM Location hostname Property</title>    <style>        h1 {            color: green;        }                  h2 {            font-family: Impact;        }                  body {            text-align: center;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>DOM Location hostname Property</h2>    <p>      For returning the hostname of the current      URL, double click the "Return hostname" button:    </p>    <button ondblclick="myhost()">      Return hostname    </button>    <p id="hostname"></p>    <script>         function myhost() {            var h = location.hostname;            document.getElementById("hostname").innerHTML = h;        }    </script></body>  </html>
Output:After click on the button:
Supported Browsers: The browser supported by Location hostname property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
C# | How to get Second Element of the Tuple? - GeeksforGeeks

30 Apr, 2019
Tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. Item2 Property is used to get the second element of the given tuple. It is not applicable on 1-Tuple and applicable on all other remaining tuples.
Syntax:
public T2 Item2 { get; }
Here, T2 is the value of the current Tuple<> object’s second component. This Tuple<> can be 2-tuple, or 3-tuple, or 4-tuple, or 5-tuple, or 6-tuple, or 7-tuple, or 8-tuple.
Example: In the below code, you can see that we are accessing the second element of each tuple.
// C# program to illustrate how to get // the second element of the tupleusing System;  class GFG {      // Main method    static public void Main()    {          // Taking 2-tuple        var st2 = Tuple.Create("Sohan", 20);        Console.WriteLine("Student-2 Age: " + st2.Item2);          // Taking 3-tuple        var st3 = Tuple.Create("Soniya", 30, "CSE");        Console.WriteLine("Student-3 Age: " + st3.Item2);          // Taking 4-tuple        var st4 = Tuple.Create("Rohan", 29, "CSE", 2015);        Console.WriteLine("Student-4 Age: " + st4.Item2);          // Taking 5-tuple        var st5 = Tuple.Create("Siya", 22, "CSE", 2017,                                           "20-Mar-1993");          Console.WriteLine("Student-5 Age: " + st5.Item2);          // Taking 6-tuple        var st6 = Tuple.Create("Riya", 24, "CSE", 2015,                               "30-May-2015", 230134832);          Console.WriteLine("Student-6 Age: " + st6.Item2);          // Taking 7-tuple        var st7 = Tuple.Create("Rohit", 21, "CSE", 2017,                         "21-Apr-1998", 384749829, 20000);          Console.WriteLine("Student-7 Age: " + st7.Item2);          // Taking 8-tuple        var st8 = Tuple.Create("Manita", 24, "CSE", 2016,                    "03-Aug-1991", 235678909, 34000, "C#");          Console.WriteLine("Student-8 Age: " + st8.Item2);    }}
Student-2 Age: 20
Student-3 Age: 30
Student-4 Age: 29
Student-5 Age: 22
Student-6 Age: 24
Student-7 Age: 21
Student-8 Age: 24

CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Data Types
Difference between != and !== operator in JavaScript - GeeksforGeeks

07 Aug, 2019
!= operatorThe inequality operator (!=) is the logical opposite of the equality operator. It means “Not Equal” and returns true where equality would return false and vice versa.Like the equality operator, the inequality operator will convert data types of values while comparing.For example 1 != ‘1’ will return false since data type conversion take place so 1 and ‘1’ are considered equal.
The inequality operator (!=) is the logical opposite of the equality operator. It means “Not Equal” and returns true where equality would return false and vice versa.
Like the equality operator, the inequality operator will convert data types of values while comparing.
For example 1 != ‘1’ will return false since data type conversion take place so 1 and ‘1’ are considered equal.
!== operatorThe strict inequality operator (!==) is the logical opposite of the strict equality operator. It means “Strictly Not Equal” and returns true where strict equality would return false and vice versa.Strict inequality will not convert data types.For example 1 !== ‘1’ will return true since 1 is an integer and ‘1’ is a character and no data type conversion take place.
The strict inequality operator (!==) is the logical opposite of the strict equality operator. It means “Strictly Not Equal” and returns true where strict equality would return false and vice versa.
Strict inequality will not convert data types.
For example 1 !== ‘1’ will return true since 1 is an integer and ‘1’ is a character and no data type conversion take place.
Example:
<script>    function NotEqual(val) {        if (val != 1) {            return "Both are Not Equal i.e. condition is true";        } else {            return "Both are Equal i.e. condition is false";        }    }  function StrictlyNotEqual(val) {    if (val !== 1) {        return "Both are Not Equal i.e. condition is true";    } else {        return "Both are Equal i.e. condition is false";    }}  //Passing integer  console.log("  1 != 1 " + NotEqual(1));console.log("  1 !== 1 " + StrictlyNotEqual(1));  //Passing character  console.log(" '1' != 1 " + NotEqual('1'));console.log(" '1' !== 1 " + StrictlyNotEqual('1'));  //Passing string  console.log(" \"1\" != 1 " + NotEqual("1"));console.log(" \"1\" !== 1 " + StrictlyNotEqual("1"));  //Passing false value i.e. 0  console.log("  0 != 1 " + NotEqual(0));console.log("  0 !== 1 " + StrictlyNotEqual(0)); </script>
Output:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Understanding the Execution of Python Program - GeeksforGeeks

10 Jul, 2020
This article aims at providing a detailed insight into the execution of the Python program. Let’s consider the below example.
Example:
Python3
a = 10b = 10print("Sum ", (a+b))
Output:
Sum  20
Suppose the above python program is saved as first.py. Here first is the name and .py is the extension. The execution of the Python program involves 2 Steps:
Compilation
Interpreter
The program is converted into byte code. Byte code is a fixed set of instructions that represent arithmetic, comparison, memory operations, etc. It can run on any operating system and hardware. The byte code instructions are created in the .pyc file. The .pyc file is not explicitly created as Python handles it internally but it can be viewed with the following command:
-m and py_compile represent module and module name respectively. This module is responsible to generate .pyc file. The compiler creates a directory named  __pycache__ where it stores the first.cpython-38.pyc file. 
The next step involves converting the byte code (.pyc file) into machine code. This step is necessary as the computer can understand only machine code (binary code). Python Virtual Machine (PVM) first understands the operating system and processor in the computer and then converts it into machine code. Further, these machine code instructions are executed by processor and the results are displayed.
Execution of Python Program
However, the interpreter inside the PVM translates the program line by line thereby consuming a lot of time. To overcome this, a compiler known as Just In Time (JIT) is added to PVM. JIT compiler improves the execution speed of the Python program. This compiler is not used in all Python environments like CPython which is standard Python software.
To execute the first.cpython-38.pyc we can use the following command:
To view the byte code of the file – first.py we can type the following command as :
The dis command is known as “disassembler” that displays the byte code in an understandable format. The code represents 5 columns:
Line Numberoffset position of byte codename of byte code instructioninstruction’s argumentconstants or names (in brackets)
Line Number
offset position of byte code
name of byte code instruction
instruction’s argument
constants or names (in brackets)
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Divide and Conquer - GeeksforGeeks

06 May, 2017
Maximum Subarray Sum problem is to find the subarray with maximum sum. For example, given an array {12, -13, -5, 25, -20, 30, 10}, the maximum subarray sum is 45. The naive solution for this problem is to calculate sum of all subarrays starting with every element and return the maximum of all. We can solve this using Divide and Conquer, what will be the worst case time complexity using Divide and Conquer?
O(n)
O(nLogn)
O(Logn)
O(n^2)
See http://www.geeksforgeeks.org/divide-and-conquer-maximum-sum-subarray/
Initialize: xa, xb, ε, N     // ε = convergence indicator
fb = f(xb) i = 0
while (i < N and |fb| > ε) do
   i = i + 1                 // update counter
   xt = ?                    // missing expression for
                             // intermediate value
   xa = xb                   // reset xa
   xb = xt                   // reset xb
   fb = f(xb)                // function value at new xb
end while
if |fb| > ε
  then // loop is terminated with i = N
  write “Non-convergence”
else
  write “return xb”
end if 
   int partition (int a[], int n); 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Python Program for Breadth First Search or BFS for a Graph
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to calculate MOVING AVERAGE in a Pandas DataFrame?
What is "network ID" and "host ID" in IP Addresses?
What is Transmission Control Protocol (TCP)?
How to Calculate Number of Host in a Subnet?
Bash Scripting - How to check If File Exists
Python Raise Keyword
Python OpenCV - Canny() Function
Python | Initialize tuples with parameters - GeeksforGeeks

15 Oct, 2019
This article deals with initializing the tuples with parameters. Namely, default value, size, and specific value at specific index. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple() + * operatorThis task can be performed using combination of above functionalities. In this, we extend the default values using * operator and perform the formation of tuple using tuple()
# Python3 code to demonstrate working of# Initialize tuples with parameters# Using tuple() + * operator  # Initializing size N = 6  # Initializing default value def_val = 2  # Initializing index to add value idx = 3   # Initializing value to be added val = 9  # Initialize tuples with parameters# Using tuple() + * operatorres = [def_val] * Nres[idx] = val res = tuple(res)  # printing resultprint("The formulated tuple is : " + str(res))
The formulated tuple is : (2, 2, 2, 9, 2, 2)

 
Method #2 : Using generator expression + tuple()This task can be performed using generator expression along with tuple() as well. The elements are created one by one on this and specific element is initialized at specific position using comparison.
# Python3 code to demonstrate working of# Initialize tuples with parameters# Using tuple() + generator expression  # Initializing size N = 6  # Initializing default value def_val = 2  # Initializing index to add value idx = 3   # Initializing value to be added val = 9  # Initialize tuples with parameters# Using tuple() + generator expressionres = tuple(val if i == idx else def_val for i in range(N))  # printing resultprint("The formulated tuple is : " + str(res))
The formulated tuple is : (2, 2, 2, 9, 2, 2)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to display the bit(1) fields in MySQL?

Let us first create a table. Here, our columns is of type bit(1) −
mysql> create table DemoTable
(
   isCaptured bit(1)
);
Query OK, 0 rows affected (1.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.47 sec)
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.29 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+
| isCaptured |
+------------+
|            |
|            |
|            |
|            |
+------------+
4 rows in set (0.00 sec)
Here is the query to see bit(1) fields in MySQL to display the fields −
mysql> select isCaptured+0 AS Visible from DemoTable;
This will produce the following output −
+---------+
| Visible |
+---------+
| 0       |
| 1       |
| 0       |
| 1       |
+---------+
4 rows in set (0.05 sec)
Apache Commons CLI - Usage Example

Apache Commons CLI provides HelpFormatter class to print the usage guide of command line arguments. See the example given below −
CLITester.java
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CLITester {
   public static void main(String[] args) throws ParseException {
	
      Options options = new Options();
      options.addOption("p", "print", false, "Send print request to printer.")
         .addOption("g", "gui", false, "Show GUI Application")
         .addOption("n", true, "No. of copies to print");
			
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("CLITester", options);
   }
}
Run the file and see the result.
java CLITester
usage: CLITester
-g,--gui Show GUI Application
-n <arg> No. of copies to print
-p,--print Send print request to printer.

 Print
 Add Notes
 Bookmark this page
How to find the value of a button with JavaScript?

Use the value property to get the value of a button in JavaScript.
You can try to run the following code to find the value of a button −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <form id="myForm">
         <button id="btn" type="button" value="my_button">My Button</button>
      </form>
      <script>
         var str1 = document.getElementById("btn").innerHTML;
         var str2 = document.getElementById("btn").value;

         document.write("Button text: "+str1);
         document.write("<br>Button value: "+str2);
      </script>
   </body>
</html>
C Program for Iterative Merge Sort

Merge sort what is a sorting algorithm based on the divide and conquer technique. the time complexity of merge sort is O(n log n). The algorithm first divides the array into equal halves and then merges them in a certain manner.
In iterative merge sort, we will divide the elements into equal halves using a recursive approach and then merge them back as a sorted array using the iterative approach.
/* Recursive C program for merge sort */
 Live Demo
#include<stdlib.h>
#include<stdio.h>
void merge(int arr[], int l, int m, int r) {
   int i, j, k;
   int n1 = m - l + 1;
   int n2 = r - m;
   int L[n1], R[n2];
   for (i = 0; i < n1; i++)
      L[i] = arr[l + i];
   for (j = 0; j < n2; j++)
      R[j] = arr[m + 1+ j];
   i = 0, j = 0, k = l;
   while (i < n1 && j < n2) {
      if (L[i] <= R[j]) {
         arr[k] = L[i];
         i++;
      } else {
         arr[k] = R[j];
         j++;
      }
      k++;
   }
   while (i < n1) {
      arr[k] = L[i];
      i++;
      k++;
   }
   while (j < n2) {
      arr[k] = R[j];
      j++;
      k++;
   }
}
void iterativeMergeSort(int arr[], int l, int r) {
   if (l < r){
      int mid = l+(r-l)/2;
      iterativeMergeSort(arr, l, mid);
      iterativeMergeSort(arr, mid+1, r);
      merge(arr, l, mid, r);
   }
}
int main(){
   int arr[] = {12, 11, 13, 5, 6, 7};
   int size = sizeof(arr)/sizeof(arr[0]);
   printf("\t\t ITERATIVE MERGE SORT \n");
   printf("Unsorted Array : \t");
   for (int i=0; i < size; i++)
      printf("%d ",arr[i]);
   iterativeMergeSort(arr, 0, size - 1);
   printf("\nSorted array : \t");
   for (int i=0; i < size; i++)
      printf("%d ", arr[i]);
   printf("\n");
   return 0;
}
ITERATIVE MERGE SORT
Unsorted Array : 12 11 13 5 6 7
Sorted array : 5 6 7 11 12 13
How to create a collapsed border in HTML?

To create a collapsed border in HTML, use the border-collapse CSS property. This property can have the following values:
Here’s how you can add,
You can try to run the following code to create collapsed border with property collapse:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         table {border-collapse: collapse; }
         table, td, th { border: 1px solid blue; }
      </style>
   </head>
   <body>
      <h1>Technologies</h1>
      <table>
         <tr>
            <th>IDE</th>
            <th>Database</th>
         </tr>
         <tr>
            <td>NetBeans IDE</td>
            <td>MySQL</td>
         </tr>
      </table>
   </body>
</html>
You can try to run the following code to create a collapsed border with property separate:
<!DOCTYPE html>
<html>
   <head>
      <style>
         table { border-collapse: separate; }
         table, td, th { border: 1px solid blue; }
      </style>
   </head>
   <body>
      <h1>Technologies</h1>
      <table>
         <tr>
            <th>IDE</th>
            <th>Database</th>
         </tr>
         <tr>
            <td>NetBeans IDE</td>
            <td>MySQL</td>
         </tr>
      </table>
   </body>
</html>
How to add custom message handlers to the pipeline in Asp.Net webAPI C#?

To create a custom Server-Side HTTP Message Handler in ASP.NET Web API, we need to create a class that must be derived from the System.Net.Http.DelegatingHandler.
Step 1 −
Create a controller and its corresponding action methods.
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class StudentController : ApiController{
      List<Student> students = new List<Student>{
         new Student{
            Id = 1,
            Name = "Mark"
         },
         new Student{
            Id = 2,
            Name = "John"
         }
      };
      public IEnumerable<Student> Get(){
         return students;
      }
      public Student Get(int id){
         var studentForId = students.FirstOrDefault(x => x.Id == id);
         return studentForId;
      }
   }
}
Step 2 −
Create our own CutomerMessageHandler class.
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DemoWebApplication{
   public class CustomMessageHandler : DelegatingHandler{
      protected async override Task<HttpResponseMessage>
      SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){
         var response = new HttpResponseMessage(HttpStatusCode.OK){
            Content = new StringContent("Result through custom message handler..")
         };
         var taskCompletionSource = new
         TaskCompletionSource<HttpResponseMessage>();
         taskCompletionSource.SetResult(response);
         return await taskCompletionSource.Task;
      }
   }
}
We have declared the CustomMessageHandler class derived from DelegatingHandler
and within that we have overriden the SendAsync() function.
When a HTTP request arrives CustomMessageHandler will execute and it will return
one HTTP message on its own, without processing the HTTP request further. So
ultimately we are preventing each and every HTTP request from reach its higher
level.
Step 3 −
Now register the CustomMessageHandler in Global.asax class.
public class WebApiApplication : System.Web.HttpApplication{
   protected void Application_Start(){
      GlobalConfiguration.Configure(WebApiConfig.Register);
      GlobalConfiguration.Configuration.MessageHandlers.Add(new
      CustomMessageHandler());
   }
}
Step 4 −
Run the application and provide the Url.
From the above output we could see the message that we have set in our
CustomMessageHandler class. So the HTTP message is not reaching the Get() action
and before that it is returning to our CustomMessageHandler class.