code-rag-bench/online-tutorials huggingface dataset:
LENGTH() Function in MySQL

15 Feb, 2021
LENGTH() :
This function in MySQL is used to find the string length which is of type bytes.
Features :
This function is used to find the string length which is of type bytes.
This function comes under String Functions.
This function accepts only one parameter namely string.
This function returns the length in bytes only.
Syntax :
LENGTH(string)
Parameters :
This method accepts only one parameter.
string – A specified string whose length is to be counted.
Returns :
It returns the string length which is of type bytes.
Example-1 :
Using LENGTH() function and getting the output.
SELECT LENGTH("GEEKSFORGEEKS");
Output :
13
Example-2 :
Using LENGTH() function and finding the length of all the float values.
CREATE TABLE float061
(  
user_id int NOT NULL AUTO_INCREMENT,
float_val float,
PRIMARY KEY(user_id)
);
INSERT float061(float_val)  
VALUES (1.9);

INSERT float061(float_val)  
VALUES (1.1);

INSERT float061(float_val)  
VALUES (3.9);

INSERT float061(float_val)  
VALUES (10.2);

INSERT float061(float_val)  
VALUES (7.9);

SELECT LENGTH(float_val) FROM float061;
Output :
    | LENGTH(float_val)|     
-----------------------------
    |         3        | 
-----------------------------
    |         3        | 
-----------------------------
    |         3        |
-----------------------------
    |         4        |
-----------------------------
    |         3        |
Example-3 :
Using LENGTH() function and getting the length of the item given.
CREATE TABLE package099
(  
user_id int NOT NULL AUTO_INCREMENT,
item VARCHAR(10),
mrp int,
PRIMARY KEY(user_id)
);
INSERT package099(item, mrp)  
VALUES ('books', 350);

SELECT LENGTH(item) FROM package099;
Output :
5
Example-4 :
Using LENGTH() function and getting the length of all the (MRP+sales price) values.
CREATE TABLE package72
(  
user_id int NOT NULL AUTO_INCREMENT,  
item VARCHAR(10),
mrp int,
sp int,
PRIMARY KEY(user_id)
);
INSERT package72(item, mrp, sp)  
VALUES ('book1', 250, 245);

INSERT package72(item, mrp, sp)  
VALUES ('book2', 350, 345);

INSERT package72(item, mrp, sp)  
VALUES ('book3', 400, 350);

SELECT LENGTH(mrp+sp) FROM package72;
Output :
    |  LENGTH(mrp+sp) |      
-----------------------------
    |         3       | 
-----------------------------
    |         3       | 
-----------------------------
    |         3       |
Application :
This function is used to find the string length which is of type bytes.
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window functions in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
RANK() Function in SQL Server
What is Temporary Table in SQL?
SQL | DROP, TRUNCATE
SQL indexes
SQL using Python
SQL | MINUS Operator
Union and Union All in MS SQL Server
SQL | Query Processing
How to remove column names from an R data frame?

There are situations when we might want to remove column names such as we want to manually replace the existing column names by new names or we simply don’t want to use them if we are very much familiar with the column characteristics. To remove the columns names we can simply set them to NULL as shown in the below examples.
Consider the below data frame −
 Live Demo
set.seed(357)
x1<−LETTERS[1:20]
x2<−rnorm(20)
x3<−rpois(20,5)
df1<−data.frame(x1,x2,x3)
df1
   x1    x2     x3
1 A −1.24111731  3
2 B −0.58320499  1
3 C 0.39474705   6
4 D 1.50421107   4
5 E 0.76679974   5
6 F 0.31746044   4
7 G −0.09997594  5
8 H 0.22703071   9
9 I −0.46901506  2
10 J 0.47652129  5
11 K −0.91164798 7
12 L −0.34177516 4
13 M 0.54674134  4
14 N −0.32720797 4
15 O 0.04108975  3
16 P −0.27603366 2
17 Q −0.59349654 2
18 R 0.17646182  6
19 S 0.50575975  4
20 T 1.00851578  3
Removing column names from df1 −
names(df1)<−NULL
df1
1 A −1.24111731  3
2 B −0.58320499  1
3 C 0.39474705   6
4 D 1.50421107   4
5 E 0.76679974   5
6 F 0.31746044   4
7 G −0.09997594  5
8 H 0.22703071   9
9 I −0.46901506  2
10 J 0.47652129  5
11 K −0.91164798 7
12 L −0.34177516 4
13 M 0.54674134  4
14 N −0.32720797 4
15 O 0.04108975  3
16 P −0.27603366 2
17 Q −0.59349654 2
18 R 0.17646182  6
19 S 0.50575975  4
20 T 1.00851578  3
 Live Demo
y1<−rexp(20,2.24)
y2<−runif(20,2,10)
y3<−rpois(20,2)
df2<−data.frame(y1,y2,y3)
df2
   y1       y2         y3
1 0.407887709  2.213538  1
2 1.740076315  8.314833  3
3 0.192889321  2.085092  1
4 0.166686518  2.295179  3
5 0.057761320  3.117768  5
6 0.001199064  8.917747  3
7 0.212810013  5.560138  1
8 0.295809473  6.418326  0
9 0.198128409  6.662312  3
10 0.711248734 4.899675  2
11 0.228512534 5.439995  1
12 0.614415810 7.231990  2
13 0.552638453 6.999130  3
14 1.181955638 2.650087  3
15 0.094478314 4.154438  4
16 0.114416419 2.687630  3
17 0.521020383 4.552469  2
18 0.145134708 3.100630  1
19 0.189475950 3.741155  1
20 0.055434073 7.268179 3
Removing column names from df2 −
names(df2)<−NULL
df2
1 0.407887709 2.213538 1
2 1.740076315 8.314833 3
3 0.192889321 2.085092 1
4 0.166686518 2.295179 3
5 0.057761320 3.117768 5
6 0.001199064 8.917747 3
7 0.212810013 5.560138 1
8 0.295809473 6.418326 0
9 0.198128409 6.662312 3
10 0.711248734 4.899675 2
11 0.228512534 5.439995 1
12 0.614415810 7.231990 2
13 0.552638453 6.999130 3
14 1.181955638 2.650087 3
15 0.094478314 4.154438 4
16 0.114416419 2.687630 3
17 0.521020383 4.552469 2
18 0.145134708 3.100630 1
19 0.189475950 3.741155 1
20 0.055434073 7.268179 3
Create pandas dataframe from lists using zip

13 Nov, 2018
One of the way to create Pandas DataFrame is by using zip() function.
You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe.
zip() function creates the objects and that can be used to produce single item at a time. This function can create pandans DataFrames by merging two lists.
Suppose there are two lists of student data, first list holds the name of student and second list holds the age of student. Then we can have,
# List1Name = ['tom', 'krish', 'nick', 'juli']  # List2Age = [25, 30, 26, 22]
Above two lists can be merged by using list(zip()) function. Now, create the pandas DataFrame by calling pd.DataFrame() function.
# Python program to demonstrate creating# pandas Datadaframe from lists using zip.  import pandas as pd  # List1Name = ['tom', 'krish', 'nick', 'juli']  # List2Age = [25, 30, 26, 22]  # get the list of tuples from two lists.# and merge them by using zip().list_of_tuples = list(zip(Name, Age))  # Assign data to tuples.list_of_tuples 
Output: 
# Converting lists of tuples into# pandas Dataframe.df = pd.DataFrame(list_of_tuples, columns = ['Name', 'Age'])   # Print data.df
Output:
Picked
Python pandas-dataFrame
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
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
Drawing a line between two mouse clicks using tkinter

Consider a case for creating a GUI application such that when we click on the window with a mouse button, it stores the coordinates and creates a line between two given points. Tkinter provides events that allow the user to bind the keys or buttons with the functions.
To draw a line between two points, we can follow these general steps,
Create a canvas widget and pack it to display in the window.
Create a canvas widget and pack it to display in the window.
Define a function draw_line() that works as the event when the user does the click event.
Define a function draw_line() that works as the event when the user does the click event.
Create a global variable that counts the number of clicks in the canvas.
Create a global variable that counts the number of clicks in the canvas.
If the count becomes two, then draw a line between the first and second coordinates.
If the count becomes two, then draw a line between the first and second coordinates.
Bind the Mouse button with the callback function to get full control over the function.
Bind the Mouse button with the callback function to get full control over the function.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the window
win.geometry("700x350")

# Define a function to draw the line between two points
def draw_line(event):
   global click_num
   global x1,y1
   if click_num==0:
      x1=event.x
      y1=event.y
      click_num=1
   else:
      x2=event.x
      y2=event.y
   # Draw the line in the given co-ordinates
   canvas.create_line(x1,y1,x2,y2, fill="green", width=10)

# Create a canvas widget
canvas=Canvas(win, width=700, height=350, background="white")
canvas.grid(row=0, column=0)
canvas.bind('<Button-1>', draw_line)
click_num=0

win.mainloop()
Run the above code to display a window. If we click on the canvas widget twice anywhere, it will draw a line in the canvas.
.NET Core - Running Tests in Visual Studio

In this chapter, we will discuss how to run tests in Visual Studio. The .NET Core has been designed with testability in mind, so that creating unit tests for your applications is easier than ever before. In this chapter, we will run and execute our test project in Visual Studio.
Let us open the FirstApp solution in Visual Studio.
You can see that it has only two projects and you will not be able to see the test project because we haven’t added that project in our solution.
Let us add a folder first and call it test.
Right-click on the test folder.
Select project.json file and click Open.
The following screenshot shows the code in Tests.cs file as output.
It is the default implementation and it is just testing that True is equal to true. It is the xUnit testing framework and you will see the Fact attribute that annotates and denotes the test method.
using System; 
using Xunit; 
  
namespace Tests { 
   public class Tests { 
      [Fact] 
      public void Test1() { 
         Assert.True(true); 
      } 
   } 
} 
Following is the implementation of project.json file.
{ 
   "version": "1.0.0-*", 
   "buildOptions": { 
      "debugType": "portable" 
   }, 
   "dependencies": { 
      "System.Runtime.Serialization.Primitives": "4.1.1", 
      "xunit": "2.1.0", 
      "dotnet-test-xunit": "1.0.0-rc2-192208-24" 
   }, 
   "testRunner": "xunit", 
   "frameworks": { 
      "netcoreapp1.0": { 
         "dependencies": { 
            "Microsoft.NETCore.App": { 
               "type": "platform", 
               "version": "1.0.1" 
            }
         }, 
         "imports": [ 
            "dotnet5.4", 
            "portable-net451+win8" 
         ] 
      } 
   } 
}
In project.json file, the most important dependency to the testing framework is the xunit, which brings in the Fact attribute. It brings in the testing framework and APIs for testing with xunit.
We also have the dotnet-test-xunit, this is an adopter so that xunit can work with .NET Core, specifically with dotnet test command line utility. Then you will see the testRunner which will run xunit and you can also see the netcoreapp1.0 framework.
You will see the .NETCore.App dependeny below.
To run test in Visual Studio, let us open Test Explorer from the Test → Window → Test Explorer menu option.
And you can see that Visual Studio automatically detects the test. The name of the test consists of namespace.className.TestMethodName. Let us now click on Run All button in Test Explorer.
It will first build the code and the run the test and you will see the total time taken by the test. Let us change the test method so that we can see the output when the test fails.
using System; 
using Xunit; 
  
namespace Tests { 
   public class Tests { 
      [Fact] 
      public void Test1() { 
         Assert.True(false); 
      } 
   } 
} 
Let us execute the test again by clicking on the Run All button link.
You can now see the test failure.
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7 - Show Java

public class Main {
  public static void main(String[] args) {
Foundation - Centered Pagination

Including the class .text-center or text-align: center in CSS, you can make the pagination list at the center of the page.
The following example demonstrates the use of pagination in Foundation −
<!doctype html>
   <head>
      <meta charset = "utf-8" />
      <meta http-equiv = "x-ua-compatible" content = "ie = edge" />
      <meta name = "viewport" content = "width = device-width, initial-scale = 1.0" />

      <title>Pagination</title>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous">

      <!-- Compressed JavaScript -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script>
   </head>

   <body>
      <h3>Pagination Centered Example</h3>
      <ul class = "pagination text-center">
         <li class = "disabled">Previous</li>
         <li class = "current">1</li>
         <li><a href = "#">2</a></li>
         <li><a href = "#">3</a></li>
         <li><a href = "#">4</a></li>
         <li class = "ellipsis"></li>
         <li><a href = "#">12</a></li>
         <li><a href = "#">13</a></li>
         <li><a href = "#">Next</a></li>
      </ul>
   </body>
</html>
Let us carry out the following steps to see how the above given code works −
Save the above given html code pagination_centered.html file.
Save the above given html code pagination_centered.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.
Previous
1
2
3
4
12
13
Next

    117 Lectures 
     5.5 hours 

 Shakthi Swaroop

    61 Lectures 
     1.5 hours 

 Hans Weemaes

    17 Lectures 
     4 hours 

 Stephen Kahuria

    8 Lectures 
     50 mins

 Zenva

    28 Lectures 
     2 hours 

 Sandra L

    16 Lectures 
     2.5 hours 

 GreyCampus Inc.
 Print
 Add Notes
 Bookmark this page
A Simplex Stop-and-Wait Protocol for an Error-Free Channel

Stop – and – Wait protocol is data link layer protocol for transmission of frames over noiseless channels. It provides unidirectional data transmission with flow control facilities but without error control facilities.
This protocol takes into account the fact that the receiver has a finite processing speed. If data frames arrive at the receiver’s end at a rate which is greater than its rate of processing, frames be dropped out. In order to avoid this, the receiver sends an acknowledgement for each frame upon its arrival. The sender sends the next frame only when it has received a positive acknowledgement from the receiver that it is available for further data processing.
Sender Site: The data link layer in the sender site waits for the network layer for a data packet. It then checks whether it can send the frame. If it receives a positive notification from the physical layer, it makes frames out of the data and sends it. It then waits for an acknowledgement before sending the next frame.
Sender Site: The data link layer in the sender site waits for the network layer for a data packet. It then checks whether it can send the frame. If it receives a positive notification from the physical layer, it makes frames out of the data and sends it. It then waits for an acknowledgement before sending the next frame.
Receiver Site: The data link layer in the receiver site waits for a frame to arrive. When it arrives, the receiver processes it and delivers it to the network layer. It then sends an acknowledgement back to the sender.
Receiver Site: The data link layer in the receiver site waits for a frame to arrive. When it arrives, the receiver processes it and delivers it to the network layer. It then sends an acknowledgement back to the sender.
begin
   canSend = True;        //Allow the first frame to be sent
   while (true)           //check repeatedly
   do
      Wait_For_Event();   //wait for availability of packet
      if ( Event(Request_For_Transfer) AND canSend) then
         Get_Data_From_Network_Layer();
         Make_Frame();
         Send_Frame_To_Physical_Layer();
         canSend = False;
      else if ( Event(Acknowledgement_Arrival)) then
         Receive_ACK();
         canSend = True;
      end if
   end while
end
begin
   while (true)      //check repeatedly
   do
      Wait_For_Event();     //wait for arrival of frame
      if ( Event(Frame_Arrival) then
         Receive_Frame_From_Physical_Layer();
         Extract_Data();
         Deliver_Data_To_Network_Layer();
         Send_ACK();
      end if
   end while
end
The following flow diagram depicts communication via simplex stop – and – wait protocol for noiseless channel:
How to Switch between Window using Selenium in Python?

04 Jan, 2021
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python.
It’s miles fantastically viable that we open a massive range of windows. Each window might also additionally require us to carry out a few moves for finishing a stop-to-stop flow. For this, we need to be capable of transfer among them. We want to interchange over the manage additionally after which do the desired operation, because, with the aid of using the default, the point of interest stays at the figure window.
Requirement:
You need to install chromedriver and set path. Click here to download for more information follows this link. WebDriver supports moving between these windows using the “switch_to_window()” method.
driver.switch_to_window(“”)
Step-by-step approach:
If we open multiple windows then we want the print the title of every window page, but we print only a parent window of the title not an all window page title. This problem will solve through the driver.switch_to_window(“). Using this method we are capable of printing every page of the title.
Taking any URL.
We want the child window of this web page then click on any button using the find_element_by_xpath() method to find XPath.
Create a handles variable who store of all handles value of open browser window
handles=driver.window_handles
Then using loop print all the titles of webpages.
Implementation:
Python3
# import selenium modulefrom selenium import webdriver  # import select classfrom selenium.webdriver.support.ui import Select  # using chrome driverdriver = webdriver.Chrome()  # web page url and open first window pagedriver.get("http://demo.automationtesting.in/Windows.html")  # find xpath of button for child window page# this page no. 2driver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click()  # return all handles value of open browser windowhandles = driver.window_handlesfor i in handles:    driver.switch_to.window(i)      # print every open window page title    print(driver.title)
Output:
Python Selenium-Exercises
Python-selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
How to completely remove node.js from Windows ?

19 May, 2022
We can completely remove Node.js from windows using the following simple steps:
Step 1: Whenever we install a package with command npm install <package name>, npm stores the cache inside the user file system. The default directory where the cache data is stored on Windows is %AppData%/npm-cache. So, we need to clean the cache first. The cache can be cleaned by using the following command.
npm cache clean --force 
Step 2: After that, you can verify the cache by using the below command:
npm cache verify
Step 3: Now open control panel in the computer. Search for Program and features. Under the program and features click on Uninstall a program. Now search for Node.js and uninstall it.
Step 4: Restart your computer or kill all node-related processes from Task Manager.
Step 5: Look for folder in your computer and if they are present remove them. The folders and files may or may not exist in your computer depending on various factors like installed version or CPU architecture.
C:\Program Files (x86)\Nodejs
C:\Program Files\Nodejs
C:\Users\{User}\AppData\Roaming\npm or open run and type appdata and click ok and open roaming there you will find npm.
C:\Users\{User}\AppData\Roaming\npm-cache or open run and type appdata and click ok and open roaming there you will find npm-cache.
C:\Users\{User}\.npmrc
C:\Users\{User}\package.json
C:\Users\{User}\package-lock.json
C:\Users\{User}\AppData\Local\Temp\npm-*                       
Step 6: After that check the environment path variables and make sure no references to npm or Node.js exist.
Step 7: If Node.js is still not uninstalled then open the command prompt and type the below command:
where node
Step 8: If Node.js is not uninstalled the command will output the location of Node.js. Go to that location and uninstall the directory.
Step 9: Restart the computer. Node.js is now completely uninstalled.
rajatnagarkar223
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Highlight the maximum value in each column in Pandas

28 Jul, 2020
Let’s discuss how to highlight the maximum values in Pandas Dataframe. Lets first make a dataframe:
Example:
Python3
# Import Required Librariesimport pandas as pdimport numpy as np  # Create a dictionary for the dataframedict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel',                 'Sanskriti', 'Abhishek Jain'],         'Age': [22, 20, 45, 21, 22],        'Marks': [90, 84, 33, 87, 82]}  # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict)  # Print Dataframedf
Output:  
Now, come to the highlighting part. Our objective is to highlight cells with maximum values in each column.
Method 1: Highlighting Cell with maximum value in each column
We will do this by using the highlight_max() method of DataFrame property. highlight_max() method takes 3 arguments, subset = name of the columns of which you want to find the maximum, color = name of the color with which you want to highlight the cell and axis = (0/1) based on which axis you want find the maximum. 
Python3
# Highlighting the maximum values of# last 2 columnsdf.style.highlight_max(color = 'lightgreen', axis = 0)
Output: 
Method 2: Highlighting the text instead of cell 
Python3
# Defining custom function which returns # the list for df.style.apply() methoddef highlight_max(s):    is_max = s == s.max()    return ['color: green' if cell else '' for cell in is_max]  df.style.apply(highlight_max)
Output: 
Method 3: Highlighting cell with maximum values 
Python3
# Defining custom function which returns # the list for df.style.apply() methoddef highlight_max(s):    is_max = s == s.max()    return ['background: lightgreen' if cell else '' for cell in is_max]  df.style.apply(highlight_max)
Output: 
Method 4: Highlighting cell with maximum values but not highlighting the string values 
Python3
# Defining custom function which returns# the list for df.style.apply() methoddef highlight_max(s):    if s.dtype == np.object:        is_max = [False for _ in range(s.shape[0])]    else:        is_max = s == s.max()    return ['background: lightgreen' if cell else '' for cell in is_max]  df.style.apply(highlight_max)
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.
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Stack in Python
Queue in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Check if element exists in list in Python
How to add two complex numbers by passing structure to a function in C language?

In order to add two complex numbers in C programming language, the user has to take two complex numbers as structure members and perform addition operation on those two numbers by creating a user-defined function.
Refer an algorithm given below for addition of two complex numbers.
Step 1: Declare struct complex with data members.
Step 2: Declare name for structure and variables.
Step 3: Enter real and imaginary part for first complex number at run time.
Step 4: Enter real and imaginary part for second complex number at runtime
Step 5: Compute addition of number1 and number2 by calling function. Go to step 7.
Step 6: Print the result.
Step 7: Compute addition
Declare temp variabletemp.real = num1.real + num2.real;temp.imag = num1.imag + num2.imag;return (temp);
Declare temp variable
temp.real = num1.real + num2.real;
temp.imag = num1.imag + num2.imag;
return (temp);
Following is the C program for adding two complex numbers by passing structure to a function −
 Live Demo
#include <stdio.h>
typedef struct complex{
   float real;
   float imag;
} complex;
complex addition(complex num1, complex num2);
int main(){
   complex num1, num2, value;
   printf("entering real and imag parts of first complex no:\n ");
   scanf("%f %f", &num1.real, &num1.imag);
   printf("entering real and imag parts of second complex no:\n ");
   scanf("%f %f", &num2.real, &num2.imag);
   value= addition(num1, num2);
   printf("result = %.1f + %.1fi", value.real, value.imag);
   return 0;
}
complex addition(complex num1, complex num2){
   complex temp;
   temp.real = num1.real + num2.real;
   temp.imag = num1.imag + num2.imag;
   return (temp);
}
When the above program is executed, it produces the following result −
entering real and imag parts of first complex no:
entering real and imag parts of second complex no:
result = 0.0 + 0.0i
C program to calculate distance between two points

Given with the two points coordinates and the task is to find the distance between two points and display the result.
In a two dimension plane there are two points let’s say A and B with the respective coordinates as (x1, y1) and (x2, y2) and to calculate the distance between them there is a direct formula which is given below
⟮x2−x1⟯2+⟮y2−y1⟯2Given below is the diagram representing two points and their differences(x2−x1)(x1,y1)(y2−y1)(x2,y2)Approach used below is as follows −Input the coordinates as x1, x2, y1 and y2Apply the formula to compute the difference between two pointsPrint the distanceAlgorithmStart
Step 1-> declare function to calculate distance between two point
   void three_dis(float x1, float y1, float x2, float y2)
      set float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0)
      print dis
step 2-> In main()
   Set float x1 = 4
   Set float y1 = 9
   Set float x2 = 5
   Set float y2 = 10
   Call two_dis(x1, y1, x2, y2)
StopExample#include <stdio.h>
#include<math.h>
//function to find distance bewteen 2 points
void two_dis(float x1, float y1, float x2, float y2) {
   float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0);
   printf("Distance between 2 points are : %f", dis);
   return;
}
int main() {
   float x1 = 4;
   float y1 = 9;
   float x2 = 5;
   float y2 = 10;
   two_dis(x1, y1, x2, y2);
   return 0;
}OutputIF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUTDistance between 2 points are : 1.414214





Sunidhi Bansal


Updated on 18-Oct-2019 11:10:35
Python | os.readlink() method

29 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.readlink() method in Python is used to resolve a symbolic link. This method returns the path to which symbolic link points.
Syntax: os.readlink(path, *, dir_fd = None)
Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method return a string object if the specified path is also a string object and a byte object if the specified path is a byte object. The returned value represents the path to which symbolic link points.
# Python program to explain os.readlink() method     # importing os module import os  # Original file pathpath = "/home/ihritik/Documents/file.txt"  # Create a symbolic link# of above path # using os.symlink() methodlink = "/home/ihritik/Desktop/file(symlink).txt"os.symlink(path, link)    # So, link is a symbolic link# Now using os.readlink() method# resolve the symbolic linkoriginalPath = os.readlink(link)    # print the path to which# symbolic link pointsprint("Symbolic link points to", originalPath)    # If the given path is not a# symbolic link then # os.readlink() method will# raise an OSError
Symbolic link points to /home/ihritik/Documents/file.txt

Reference: https://docs.python.org/3/library/os.html
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
map key_comp() function in C++ STL

22 Jun, 2022
The map::key_comp() is a function in STL in C++ that returns a copy of comparison object used by container that compare keys. Syntax:
map.key_comp()
Return value: This method returns the comparison object used by container that compare keys. Below examples illustrate the working of key_comp() method: Example: 
CPP
// C++ program to demonstrate map::key_comp(). #include <iostream>#include <map>using namespace std; int main(){    // Declare the map    map<char, int> mymap;     // Compare the key.    map<char, int>::key_compare        mycomp        = mymap.key_comp();     // Populate the map    mymap['x'] = 50;    mymap['y'] = 100;    mymap['z'] = 150;     // Print the map    cout << "mymap contain:\n";     char highest = mymap.rbegin()->first;     // key value of last element    map<char, int>::iterator        it        = mymap.begin();     do {        cout << it->first            << " => " << it->second            << "\n";    } while (mycomp((*it++).first, highest));     cout << "\n";     return 0;}
mymap contain:
x => 50
y => 100
z => 150
Example 2: 
CPP
// C++ program to demonstrate map::key_comp(). #include <iostream>#include <map>using namespace std; int main(){    // Declare the map    map<char, int> mymap;     // Compare the key.    map<char, int>::key_compare        mycomp        = mymap.key_comp();     mymap['a'] = 100;    mymap['b'] = 200;    mymap['c'] = 300;     cout << "mymap contain:\n";     char highest = mymap.rbegin()->first;     // key value of last element     map<char, int>::iterator        it        = mymap.begin();     do {        cout << it->first            << " => "            << it->second            << '\n';    } while (mycomp((*it++).first, highest));     cout << '\n';     return 0;}
mymap contain:
a => 100
b => 200
c => 300
Time complexity: O(1)
utkarshgupta110092
CPP-Functions
cpp-map
Picked
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Substring in C++
Object Oriented Programming in C++
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
How can we align the JRadioButtons horizontally in Java?


A JRadioButton is a subclass of JToggleButton and it is a two-state button that can either selected or deselected. Unlike checkboxes, the radio buttons are associated with a group and only one radio button in a group can be selected and it can be implemented by using the ButtonGroup class. When the radio button in the group is selected, any other previously selected radio button in the group is deselected. We can align the radio buttons either horizontally or vertically by using BoxLayout.
import java.awt.*;
import javax.swing.*;
public class HorizontalRadioButtonsTest extends JPanel {
   public HorizontalRadioButtonsTest(){
      JRadioButton jrb1 = new JRadioButton(" RB1");
      JRadioButton jrb2 = new JRadioButton(" RB2");
      JRadioButton jrb3 = new JRadioButton(" RB3");
      JRadioButton jrb4 = new JRadioButton(" RB4");
      JRadioButton jrb5 = new JRadioButton(" RB5");
      Box box1 = Box.createHorizontalBox();
      box1.add(jrb1);
      box1.add(jrb2);
      box1.add(jrb3);
      box1.add(jrb4);
      box1.add(jrb5);
      JRadioButton jrb6 = new JRadioButton(" RB6");
      JRadioButton jrb7 = new JRadioButton(" RB7");
      JRadioButton jrb8 = new JRadioButton(" RB8");
      JRadioButton jrb9 = new JRadioButton(" RB9");
      JRadioButton jrb10 = new JRadioButton(" RB10");
      Box box2 = Box.createHorizontalBox();
      box2.add(jrb6);
      box2.add(jrb7);
      box2.add(jrb8);
      box2.add(jrb9);
      box2.add(jrb10);
      JRadioButton jrb11 = new JRadioButton(" RB11");
      JRadioButton jrb12 = new JRadioButton(" RB12");
      JRadioButton jrb13 = new JRadioButton(" RB13");
      JRadioButton jrb14 = new JRadioButton(" RB14");
      JRadioButton jrb15 = new JRadioButton(" RB15");
      Box box3 = Box.createHorizontalBox();
      box3.add(jrb11);
      box3.add(jrb12);
      box3.add(jrb13);
      box3.add(jrb14);
      box3.add(jrb15);
      JRadioButton jrb16 = new JRadioButton(" RB16");
      JRadioButton jrb17 = new JRadioButton(" RB17");
      JRadioButton jrb18 = new JRadioButton(" RB18");
      JRadioButton jrb19 = new JRadioButton(" RB19");
      JRadioButton jrb20 = new JRadioButton(" RB20");
      Box box4 = Box.createHorizontalBox();
      box4.add(jrb16);
      box4.add(jrb17);
      box4.add(jrb18);
      box4.add(jrb19);
      box4.add(jrb20);
      setLayout(new GridLayout(5, 1));
      add(box1);
      add(box2);
      add(box3);
      add(box4);
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("HorizontalRadioButtons Test");
      frame.add(new HorizontalRadioButtonsTest());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setSize(375, 250);
      frame.setVisible(true);
   }
}
How to remove lines in a Matplotlib plot?

We will create two lines, i.e., line1 and line2. After that, we will pop the second line and will remove it.
Create lists for line1 and line2.
Create lists for line1 and line2.
Plot line1 and line 2 using plot() method, line 2 with style =’dashed’.
Plot line1 and line 2 using plot() method, line 2 with style =’dashed’.
Set or retrieve auto-scaling margins(0.2).
Set or retrieve auto-scaling margins(0.2).
Pop line 2, and remove it using remove() method.
Pop line 2, and remove it using remove() method.
The final figure will have only one line, so use plt.show() method.
The final figure will have only one line, so use plt.show() method.
import matplotlib.pyplot as plt

line1 = [2, 4, 8]
line2 = [3, 6, 12]

plt.plot(line1)
line_2 = plt.plot(line2, linestyle='dashed')
plt.margins(0.2)
plt.title("With extra lines")
plt.show()

plt.plot(line1)
l = line_2.pop(0)
l.remove()
plt.margins(0.2)
plt.title("Removed extra lines")

plt.show()
How can we sort a string without using predefined methods in Java?

A String is an object that represents an immutable sequence of characters and cannot be changed once created. The java.lang.String class can be used to create a string object.
In the below program, we can sort the characters of a string without using any predefined methods of String class in Java.
public class SortStringWithoutPredefinedMethodsTest {
   public static void main(String[] args) {
      String str = "jdkoepacmbtr";
      System.out.println("Before Sorting:" + str);
      int j = 0;
      char temp = 0;
      char[] chars = str.toCharArray();
      for(int i=0; i < chars.length; i++) {
         for(j=0; j < chars.length; j++) {
            if(chars[j] > chars[i]) {
               temp = chars[i];
               chars[i] = chars[j];
               chars[j] = temp;
            }
         }
      }
      System.out.println("After Sorting:");
      for(int k=0; k < chars.length; k++) {
         System.out.println(chars[k]);
      }
   }
}
Before Sorting: jdkoepacmbtr
After Sorting:
a
b
c
d
e
j
k
m
o
p
r
t
C# int.TryParse Method

Convert a string representation of number to an integer, using the int.TryParse method in C#. If the string cannot be converted, then the int.TryParse method returns false i.e. a Boolean value.
Let’s say you have a string representation of a number.
string myStr = "12";
Now to convert it to an integer, use the int.TryParse(). It will get converted and will return True.
int.TryParse(myStr, out a);
 Live Demo
using System.IO;
using System;
class Program {
   static void Main() {
      bool res;
      int a;
      string myStr = "12";
      res = int.TryParse(myStr, out a);
      Console.WriteLine("String is a numeric representation: "+res);
   }
}
String is a numeric representation: True
DAX Text - FIXED function

Rounds a number and returns the result as text. You can specify the number of digits to the right of the decimal points. You can also specify whether the result be returned with or without commas.
FIXED (<number>, [<decimals>, [<no_commas>]]) 

number
The number you want to round and convert to text, or
A column containing a number.
decimals
Optional.
The number of digits to the right of the decimal point.
If omitted, 2.
no_commas
Optional.
Can be specified only if decimals are specified. Otherwise, should be omitted.
True () or 1: Does not display the commas in the returned text.
False () or 0 or omitted: Displays the commas in the returned text.
A number represented as text.
If no_commas is FALSE or 0 or is omitted, then the returned text includes commas.
You have two options to format a column containing numbers −
By using a formatting command from the Ribbon.
Using the DAX FIXED function.
The difference between the two options is that the FIXED function converts its result to text, whereas with the formatting command the result is still a number.
Numbers can never have more than 15 significant digits, but decimals can be as large as 127.
= FIXED ([Sales Amount],2) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Cordova - Back Button

You will usually want to use Android back button for some app functionality like returning to previous screen. To be able to implement your own functionality, you first need to disable exiting the app when the back button is pressed.
document.addEventListener("backbutton", onBackKeyDown, false);  
function onBackKeyDown(e) { 
   e.preventDefault(); 
   alert('Back Button is Pressed!'); 
}
Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using e.preventDefault().

    45 Lectures 
     2 hours 

 Skillbakerystudios

    16 Lectures 
     1 hours 

 Nilay Mehta
 Print
 Add Notes
 Bookmark this page
How to adjust transparency (alpha) in Seaborn pairplot using Matplotlib?

To adjust transparency, i.e., aplha in Seaborn pairplot, we can change the value of alpha.
Create a dataframe using Pandas with two keys, col1 and col2.
Create a dataframe using Pandas with two keys, col1 and col2.
Initialize the variable, alpha, for transparency.
Initialize the variable, alpha, for transparency.
Use pairplot() method to plot pairwise relationships in a dataset. Use df (from step 1), kind="scatter", and set the plot size, edgecolor, facecolor, linewidth and alpha vaues in the arguments.
Use pairplot() method to plot pairwise relationships in a dataset. Use df (from step 1), kind="scatter", and set the plot size, edgecolor, facecolor, linewidth and alpha vaues in the arguments.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({"col1": [1, 3, 5, 7, 1], "col2": [1, 5, 7, 9, 1]})
alpha = 0.75
sns.pairplot(df, kind="scatter", plot_kws=dict(s=100, edgecolor="red",
   fc='green', linewidth=2.5, alpha=alpha))
plt.show()
PHP mysqli_field_count() Function

The mysqli_field_count() function is used to get the number of fields (columns) in the result set of the recently executed MySQL query .
mysqli_field_count($con)

con(Mandatory)
This is an object representing a connection to MySQL Server.
PHP mysqli_field_count() function returns an integer value indicating the number of columns in the result set of the last query. If the last query is not a SELECT query (no result set) this function returns 0.
This function was first introduced in PHP Version 5 and works works in all the later versions.
Following example demonstrates the usage of the mysqli_field_count() function (in procedural style) −
<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   //Query to retrieve all the records of the employee table
   mysqli_query($con, "Select * from employee");

   //Field Count
   $count = mysqli_field_count($con);
   print("Field Count: ".$count);

   //Closing the connection
   mysqli_close($con);
?>
This will produce following result −
Field Count: 6

In object oriented style the syntax of this function is $con -> field_count;, Where, $con is the connection object −
<?php
   //Creating a connection
   $con = new mysqli("localhost", "root", "password", "mydb");

   //Query to retrieve all the records of the employee table
   $con -> query("Select FIRST_NAME, LAST_NAME, AGE from employee");

   //Field Count
   $count = $con->field_count;
   print("Field Count: ".$count);

   //Closing the connection
   $con -> close();
?>
This will produce following result −
Field Count: 3

Following is another example of the mysqli_field_count() function
<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   print("Field Count: ".mysqli_field_count($con)."\n");

   //INSERT Query
   mysqli_query($con, "INSERT INTO employee (FIRST_NAME, AGE) VALUES (Archana, 25), (Bhuvan, 29)");
   print("Field Count: ".mysqli_field_count($con));
  
   //Closing the connection
   mysqli_close($con);
?>
This will produce following result −
Field Count: 0
Field Count: 0

<?php
   $connection_mysql = mysqli_connect("localhost","root", "password", "mydb");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
   
   mysqli_query($connection_mysql,"SELECT * FROM employee");
   print(mysqli_field_count($connection_mysql));
   
   mysqli_close($connection_mysql);
?>
This will produce following result −
6


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Get number from user input and display in console with JavaScript

You can use # to get the value when user clicks the button using document.querySelector(“”);
Following is the JavaScript code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="container container-fluid">
<p><strong> Example:</strong> choose a number between 1 to 100</p>
<form>
<div class="form-group">
<label for="number">Give a number:</label>
<input id="inputNumber" value="" type="text" name="number" />
</form>
<p id="output"></p>
</div>
<button class="btn btn-dark" id="choose" type="submit">Click Me</button>
</body>
<script>
   function example() {
      let btn = document.querySelector("#choose");
      let randomNumber = Math.ceil(Math.random() * 100);
      btn.onclick = function() {
         let givenNumber = document.querySelector("#inputNumber").value;
         let valueInt = parseInt(givenNumber, 100);
         console.log(randomNumber, givenNumber);
      };
   }
   example();
</script>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.
Add a value −
On clicking the button Click Me, the same is visible in Console −