code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.axes.Axes.get_position() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_position() function in axes module of matplotlib library is used to Get a copy of the axes rectangle as a Bbox..
Syntax: Axes.get_position(self, original=False)
Parameters:
original : This parameter is used to return the original position if true. Otherwise return the active position.
Return value: This method returns a copy of the axes rectangle as a Bbox.
Below examples illustrate the matplotlib.axes.Axes.get_position() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np   x = np.arange(10)y = [2, 4, 6, 14, 15, 16, 17, 16, 18, 20]y2 = [10, 11, 12, 13, 8, 10, 12, 14, 18, 19]   fig, ax1 = plt.subplots()   ax1.plot(x, y, "go-", label ='Line 1', )ax1.plot(x, y2, "o-", label ='Line 2')  chartBox = ax1.get_position()x, y, w, h = chartBox.x0, chartBox.y0, chartBox.width, chartBox.height  ax1.text(0, 20, "Bbox - xmin : "+str(x),          fontweight ="bold")ax1.text(0, 19, "Bbox - ymin : "+str(round(y, 2)),          fontweight ="bold")ax1.text(0, 18, "Bbox - width : "+str(w),          fontweight ="bold")ax1.text(0, 17, "Bbox - height : "+str(h),          fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_position()\function Example\n', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm   Z = np.random.rand(6, 30)   fig, ax1 = plt.subplots()   ax1.pcolor(Z)  chartBox = ax1.get_position()x, y, x1, y1 = chartBox.x0, chartBox.y0, chartBox.x1, chartBox.y1  ax1.text(4, 6.35, "Bbox - xmin : "+str(x),         fontweight ="bold")ax1.text(19, 6.35, "Bbox - ymin : "+str(round(y, 2)),         fontweight ="bold")ax1.text(4, 6.15, "Bbox - xmax : "+str(x1),          fontweight ="bold")ax1.text(19, 6.15, "Bbox - ymax : "+str(y1),          fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_position()\function Example\n', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
whoami command in Linux with example

18 Feb, 2021
whoami command is used both in Unix Operating System and as well as in Windows Operating System.
It is basically the concatenation of the strings “who”,”am”,”i” as whoami.
It displays the username of the current user when this command is invoked.
It is similar as running the id command with the options -un.
The earliest versions were created in 2.9 BSD as a convenience form for who am i, the Berkeley Unix who command’s way of printing just the logged in user’s identity. The GNU version was written by Richard Mlynarik and is part of the GNU Core Utilities (coreutils).
Syntax:
geekforgeeks@HP~: whoami

Output :
geekforgeeks

Example :
Options of Whoami
Syntax:
geekforgeeks@HP~: whoami [OPTION]

1. –help Option :It gives the help message and exit.Syntax :
geekforgeeks@HP~: whoami --help

Example :2. –version Option :It gives the version information and exit.Syntax:
geekforgeeks@HP~: whoami --version

Example :
Commands related to whoami command are as follows :1. w — Show who is logged on and what they are doing.2. who — Report which users are logged in to the system.Linux Tutorials | About the user and the terminal | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLinux Tutorials | About the user and the terminal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:35 / 2:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WnjofnvIIvg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
D3.js axis.tickSize() Function - GeeksforGeeks

18 Aug, 2020
The d3.axis.tickSize() function in D3.js is used to set the inner and outer tick size to the specified value and returns the axis. If size is not specified, returns the current inner tick size, which defaults to 6.
Syntax:
axis.tickSize([size])
Parameters: This function accepts single parameter as mentioned above and described below:
size: This parameter holds the size to set the inner and outer tick size.
Return Value: This function returns the axis.
Below programs illustrate the d3.axis.tickSize() function in D3.js:
Example 1:
HTML
<!DOCTYPE html> <html>     <head>     <title>         D3.js | D3.axis.tickSize() Function     </title>         <script type="text/javascript"         src="https://d3js.org/d3.v4.min.js">     </script>         <style>         svg text {             fill: green;             font: 15px sans-serif;             text-anchor: center;         }     </style> </head>     <body>     <script>         var width = 400, height = 400;         var svg = d3.select("body")             .append("svg")             .attr("width", width)             .attr("height", height);             var xscale = d3.scaleLinear()             .domain([0, 10])             .range([0, width - 60]);             var x_axis = d3.axisBottom()             .scale(xscale).tickSize(15);             var xAxisTranslate = height / 2;             svg.append("g")             .attr("transform", "translate(50, "                 + xAxisTranslate + ")")             .call(x_axis)      </script> </body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html> <html>     <head>     <title>         D3.js | D3.axis.tickSize() Function     </title>         <script type="text/javascript"         src="https://d3js.org/d3.v4.min.js">     </script>         <style>         svg text {             fill: green;             font: 15px sans-serif;             text-anchor: center;         }     </style> </head>     <body>     <script>         var width = 400, height = 400;         var svg = d3.select("body")             .append("svg")             .attr("width", width)             .attr("height", height);             var yscale = d3.scaleLinear()             .domain([0, 1])             .range([height - 50, 0]);             var y_axis = d3.axisRight()             .scale(yscale).tickSize(0);            svg.append("g")             .attr("transform", "translate(100,20)")             .call(y_axis)      </script> </body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create a responsive navigation menu with icons, using CSS?


Following is the code for creating the responsive navigation menu with icons.
 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>
<style>
body{
   margin:0px;
   margin-top:10px;
   padding: 0px;
}
nav{
   width: 100%;
   background-color: rgb(39, 39, 39);
   overflow: auto;
   height: auto;
}
.links {
   display: inline-block;
   text-align: center;
   padding: 14px;
   color: rgb(178, 137, 253);
   text-decoration: none;
   font-size: 17px;
}
.links:hover {
   background-color: rgb(100, 100, 100);
}
.selected{
   background-color: rgb(0, 18, 43);
}
@media screen and (max-width: 600px) {
   .links {
      display: block;
   }
}
</style>
</head>
<body>
<nav>
   <a class="links selected" href="#"><i class="fa fa-fw fa-home"></i> Home</a>
   <a class="links" href="#"><i class="fa fa-fw fa-user"></i> Login</a>
   <a class="links" href="#"><i class="fa fa-user-circle-o" aria-hidden="true"></i> Register</a>
   <a class="links" href="#"><i class="fa fa-fw fa-envelope"></i> Contact Us</a>
   <a class="links" href="#"><i class="fa fa-info-circle" aria-hidden="true"></i> More Info</a>
</nav>
</body>
</html>
The above code will produce the following output −
When the screen will be resized to 600px −
JavaScript: How to loop through all DOM elements on a page and display result on console?

To loop through all DOM elements on a page, use document.getElementsByTagName(‘*’). Loop
through its length and display the result in console as in the below code −
var tags = document.getElementsByTagName("*");
for (var i=0, max=tags.length; i < max; i++) {
   console.log(tags[i]);
}
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=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>
<h1>Demo</h1>
<label>
Enter the name:
<input type="text" id="txtName">
</label>
<button type="submit">Save</button>
<script>
   var tags = document.getElementsByTagName("*");
   for (var i=0, max=tags.length; i < max; i++) {
      console.log(tags[i]);
   }
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Converting Tkinter program to exe file

Let us suppose that we want to create a standalone app (executable application) using tkinter. We can convert any tkinter application to an exe compatible file format using the PyInstaller package in Python.
To work with pyinstaller, first install the package in the environment by using the following command,
pip install pyinstaller
Once installed, we can follow the steps to convert a Python Script File (contains a Tkinter application file) to an Executable file.
Install pyinstaller using pip install pyinstaller in Windows operating system. Now, type pyinstaller --onefile -w filename and press Enter.
Now, check the location of the file (script file) and you will find a dist folder which contains the executable file in it.
When we run the file, it will display the window of the tkinter application.
main.py
In this example, we have created an application that will greet the user with their name by displaying the message on the screen.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")

#Define a function to show a message
def myclick():
   message= "Hello "+ entry.get()
   label= Label(frame, text= message, font= ('Times New Roman', 14, 'italic'))
   entry.delete(0, 'end')
   label.pack(pady=30)

#Creates a Frame
frame = LabelFrame(win, width= 400, height= 180, bd=5)
frame.pack()
#Stop the frame from propagating the widget to be shrink or fit
frame.pack_propagate(False)

#Create an Entry widget in the Frame
entry = ttk.Entry(frame, width= 40)
entry.insert(INSERT, "Enter Your Name")
entry.pack()
#Create a Button
ttk.Button(win, text= "Click", command= myclick).pack(pady=20)
win.mainloop()
Now, run the above command to convert the given code into an executable file. It will affect the directory (dist folder) where all executable file will be placed automatically.
When we run the exe file, it will display a window that contains an entry widget. If we click the "Click" button, it will display a greeting message on the screen.
How can fetch records from specific month and year in a MySQL table?

Use YEAR() and MONTH() to display records from specific month and year respectively. Let us first create a table −
mysql> create table DemoTable
   (
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(20),
   CustomerTotalBill int,
   PurchasingDate date
   );
Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('John',2000,'2019-01-21');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Chris',1000,'2019-01-31');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Robert',4500,'2018-01-01');
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Sam',5500,'2017-02-12');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Carol',500,'2016-01-12');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+--------------+-------------------+----------------+
| CustomerId | CustomerName | CustomerTotalBill | PurchasingDate |
+------------+--------------+-------------------+----------------+
| 1          | John         | 2000              | 2019-01-21     |
| 2          | Chris        | 1000              | 2019-01-31     |
| 3          | Robert       | 4500              | 2018-01-01     |
| 4          | Sam          | 5500              | 2017-02-12     |
| 5          | Carol        | 500               | 2016-01-12     |
+------------+--------------+-------------------+----------------+
5 rows in set (0.00 sec)
Following is the query to display records from specific month and year in MySQL −
mysql> select *from DemoTable WHERE YEAR(DATE(PurchasingDate))=2019 AND MONTH(DATE(PurchasingDate)) = 01;
This will produce the following output −
+------------+--------------+-------------------+----------------+
| CustomerId | CustomerName | CustomerTotalBill | PurchasingDate |
+------------+--------------+-------------------+----------------+
| 1          | John         | 2000              | 2019-01-21     |
| 2          | Chris        | 1000              | 2019-01-31     |
+------------+--------------+-------------------+----------------+
2 rows in set (0.03 sec)
HTML | content Attribute - GeeksforGeeks

25 Aug, 2021
The HTML content Attribute is used to given the values that are related to the http-equiv or name attribute. The content attribute can associated with the <meta> element. 
Supported Tags: 
<meta>
Syntax:  
<meta content="text">
Attribute Values: It contains the values the text which specify the content of the meta information.Example: This Example illustrates the use of content attribute.  
html
<!DOCTYPE html><html> <head>    <title>      content attribute in HTMLs  </title>    <meta name="keywords"          content="content attribute                   in Meta Tag, Metadata" /></head> <body style="text-align:center;">    <h1> GeeksforGeeks</h1>    <h2>Content Attribute In HTML</h2></body> </html>
Output:  
Supported Browsers: The browser supported by HTML content Attribute 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.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Convert an array of binary numbers to corresponding integer in JavaScript

Let’s say, we have an array of Numbers that contains 0 and 1 −
const arr = [0, 1, 0, 1];
We are required to write an Array function, toBinary() that returns the corresponding binary for
the array it is used with.
For example − If the array is −
const arr = [1, 0, 1, 1];
Then the output should be 11 because the decimal representation of binary 1011 is 11.
Therefore, let’s write the code for this function.
In JavaScript, there exists a method parseInt(), that takes in two arguments first one is a string
and second a number that represents a particular base, like 10 for decimal base, 2 for binary.
This function parses the string argument and returns an integer of the specified radix ( base).
In our case, to convert the array of binary to decimal, we can use the parseInt() function like
this −
const arr = [1, 0, 1, 1];
const parseArray = arr => {
   const binaryString = arr.join("");
   return parseInt(binaryString, 2);
};
console.log(parseArray(arr));
In this method we iterate over the binary array and construct a decimal based on the
corresponding binary numbers. We will use the left shift operator (<<) to shift the accumulated
value to left by one bit every time and return the bitwise OR (|) of the shifted accumulated value
and current value.
The code for this using Bitwise Operator −
const arr = [1, 0, 1, 1];
const parseArray = arr => {
   return arr.reduce((acc, val) => {
      return (acc << 1) | val;
   });
};
console.log(parseArray(arr));
The output in the console will be −
11
Python Pandas - Get the number of days from TimeDelta

To get the number of days from TimeDelta, use the timedelta.days property in Pandas. At first, import the required libraries −
import pandas as pd
TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s. Create a Timedelta object
timedelta = pd.Timedelta('5 days 1 min 45 s')

Return the number of days
timedelta.days
Following is the code
import pandas as pd

# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('5 days 1 min 45 s')

# display the Timedelta
print("Timedelta...\n", timedelta)

# return the number of days
res = timedelta.days

# display the days
print("\nDays...\n", res)
This will produce the following code
Timedelta...
 5 days 00:01:45

Days...
 5
Python | Django Admin Interface

05 Jun, 2018
Prerequisites : django-introduction-and-installation | django-introduction-set-2-creating-a-project
Django provides a default admin interface which can be used to perform create, read, update and delete operations on the model directly. It reads set of data that explain and gives information about data from the model, to provide an instant interface where the user can adjust contents of the application . This is an in-built module and design to execute admin related work to the user.
Activating and Using the Admin InterfaceThe admin app(django.contrib.admin) is enabled by default and already added into the INSTALLED_APPS list present in the settings.py file.
To access this admin interface on browser write ‘/admin/’ at ‘localhost:8000/admin/’ and it shows the output as given below:
It prompts for login details, if no login id is created before, then a new superuser can be created by using the command given below:
python manage.py createsuperuser

Now, access the admin login page after starting the Development Server which can be done by using the command given below.
python manage.py runserver

Enter username and password, then hit login .
After logging in successfully, it shows the interface as shown below: .
This is what is called a Django Admin Dashboard where one can add, delete and update data belonging to any registered model.
Python Django
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
Python OOPs Concepts
Iterate over a list in Python
numpy.logspace() in Python

05 Apr, 2022
The numpy.logspace() function returns number spaces evenly w.r.t interval on a log scale. Syntax :  
numpy.logspace(start,
               stop,
               num = 50,
               endpoint = True,
               base = 10.0,
               dtype = None)
Parameters : 
-> start    : [float] start(base ** start) of interval range.
-> stop     : [float] end(base ** stop) of interval range
-> endpoint : [boolean, optional]If True, stop is the last sample. By default, True
-> num      : [int, optional] No. of samples to generate
-> base     : [float, optional] Base of log scale. By default, equals 10.0
-> dtype    : type of output array
Return :  
-> ndarray
Code 1 : Explaining the use of logspace()  
Python
# Python Programming illustrating# numpy.logspace method import numpy as geek # base = 11print("B\n", geek.logspace(2.0, 3.0, num=5, base = 11)) # base = 10print("B\n", geek.logspace(2.0, 3.0, num=5)) # base = 10, dtype = intprint("B\n", geek.logspace(2.0, 3.0, num=5, dtype = int))
Output :  
B
 [  121.           220.36039471   401.31159963   730.8527479   1331.        ]
B
 [  100.           177.827941     316.22776602   562.34132519  1000.        ]
B
 [ 100  177  316  562 1000]
Code 2 : Graphical Representation of numpy.logspace() using matplotlib module – pylab  
Python
# Graphical Representation of numpy.logspace()import numpy as geekimport pylab as p # Start = 0# End = 2# Samples to generate = 10x1 = geek.logspace(0, 1, 10)y1 = geek.zeros(10) # Start = 0.1# End = 1.5# Samples to generate = 12x2 = geek.logspace(0.1, 1.5, 12)y2 = geek.zeros(12) p.plot(x1, y1+0.05, 'o')p.xlim(-0.2, 18)p.ylim(-0.5, 1)p.plot(x2, y2, 'x')
Output :  
Note : These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore themSimilar methods :  
arange
linspace
saurabh1990aror
kothavvsaakash
surinderdawra388
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery UI Dialog close Event

02 Dec, 2021
jQuery UI Close event is triggered when the dialog box is closed.
Learn more about jQuery selectors and events here.
Syntax:
$(".selector").dialog (
   close: function( event, ui ) {
       console.log('closed')
   },
Approach:
First, add jQuery Mobile scripts needed for your project.
<link href = 
"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
    rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js">
</script>
‘Open Dialog’ button will trigger the click function (#gfg) that will further open the <textarea> in a dialog (#gfg2).
close( event, ui ) : Triggers when we click on close button in the dialog. There is callback function attached to this close.event :  Type -> Eventui : Type -> Objectcallback function : function( event, ui ) { console.log(‘closed’)}
event :  Type -> Event
ui : Type -> Object
callback function : function( event, ui ) { console.log(‘closed’)}
Example 1:
HTML
<!doctype html><html lang = "en">   <head>      <meta charset = "utf-8">      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"         rel = "stylesheet">      <script src = "https://code.jquery.com/jquery-1.10.2.js">         </script>      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js">        </script>                <script type = "text/javascript">         $(function() {            $( "#gfg2" ).dialog({          autoOpen: false,                close: function( event, ui ) {                  console.log('closed')               },            });            $( "#gfg" ).click(function() {               $( "#gfg2" ).dialog( "open" );            });         });      </script>   </head>        <body>      <div id = "gfg2" title="GeeksforGeeks">         <textarea>jQuery UI | close(event, ui) Event</textarea>      </div>      <button id = "gfg">Open Dialog</button>   </body></html>
Output:
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Merge two lists alternatively

09 May, 2019
Given two lists, write a Python program to merge the given lists in an alternative fashion, provided that the two lists are of equal length.
Examples:
Input : lst1 = [1, 2, 3]
        lst2 = ['a', 'b', 'c']
Output : [1, 'a', 2, 'b', 3, 'c']

Input : lst1 = ['name', 'alice', 'bob']
        lst2 = ['marks', 87, 56]
Output : ['name', 'marks', 'alice', 87, 'bob', 56]

 Method #1 : List comprehension
# Python3 program to merge two lists # alternatively  def countList(lst1, lst2):    return [sub[item] for item in range(len(lst2))                      for sub in [lst1, lst2]]      # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))
[1, 'a', 2, 'b', 3, 'c']

There is an alternative to use list comprehension with zip() as given below –
def countList(lst1, lst2):    return [item for pair in zip(lst1, lst2 + [0])                                 for item in pair]
 Method #2 : Using itertools.cycle()
# Python3 program to merge two lists # alternativelyfrom itertools import cycle  def countList(lst1, lst2):    iters = [iter(lst1), iter(lst2)]    return list(iter.__next__() for iter in cycle(iters))      # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))
[1, 'a', 2, 'b', 3, 'c']

 Method #3 : Using reduce()
# Python3 program to merge two lists # alternativelyimport operatorfrom functools import reduce  def countList(lst1, lst2):    return reduce(operator.add, zip(lst1, lst2))      # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))
(1, 'a', 2, 'b', 3, 'c')

 Method #4 : Using numpy module
# Python3 program to merge two lists # alternativelyimport numpy as np  def countList(lst1, lst2):    return np.array([[i, j] for i, j in zip(lst1, lst2)]).ravel()      # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))
['1' 'a' '2' 'b' '3' 'c']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Map() Function in Golang With Examples

22 Dec, 2021
strings.Map() Function in Golang is used to return a copy of the string given string with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.
So whenever the user wants to make changes in a certain string, he can make use of the strings.Map() function. It replaces the character of a string with a user-desired character. If we need to mask certain characters including digits and spaces, this function can be used.
Syntax:
func Map(mapping func(rune) rune, s string) string
The mapping func(rune) rune parameter defines the character with which the original character needs to be replaced while the s parameter defines the original string inputted by the user.
Example 1:
// Golang program to illustrate // the strings.Map() Functionpackage main   import (    "fmt";    "strings")   func main() {    modified := func(r rune) rune {        if r == 'e' {            return '@'        }        return r    }       input:= "Hello, Welcome to GeeksforGeeks"    fmt.Println(input)       // using the function    result := strings.Map(modified, input)    fmt.Println(result)}
Output:
Hello, Welcome to GeeksforGeeks
H@llo, W@lcom@ to G@@ksforG@@ks

Explanation: In the above example, we have used strings.Map() function to modify a string. We have defined a variable named “modified” that replaces character ‘e’ in the string with the symbol ‘@’. Another variable named “input” takes an input string that needs transformation.
Example 2: The strings.Map() function can also be used to remove the spaces between the words of a string.
// Golang program to illustrate // the strings.Map() Functionpackage main   import (    "fmt";    "strings")   func main() {    transformed := func(r rune) rune {                   if r == ' ' {            return 0        }        return r    }       input:= "GeeksforGeeks is a computer science portal."    fmt.Println(input)       // using the function    output := strings.Map(transformed, input)    fmt.Println(output)}
Output:
GeeksforGeeks is a computer science portal.
GeeksforGeeksisacomputerscienceportal.

Explanation: In the above example, we have used strings.Map() function to remove the spaces in between a string. We have defined a variable named “transformed” that eliminates space ‘ ‘ in the string. This is done by returning 0 at the place of spaces. Another variable named “input” takes an input string whose in-between spaces need to be removed.
fakharanyhussein
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Interfaces in Golang
Golang Maps
How to Split a String in Golang?
Different Ways to Find the Type of Variable in Golang
Slices in Golang
Anonymous function in Go Language
Channel in Golang
Go Programming Language (Introduction)
Strings in Golang
Objdump Command in Linux with Examples

25 Aug, 2020
When we have an object file and we don’t have the source code with us and we have to find out the maximum information from the file. To do so objdump plays a very vital role. The main purpose of the objdump command is to help in debugging the object file. It is used for the following listed purposes:
To retrieve archive header
To get the offset of the file
To get the bfdname
To get the demangle
To debug the file
To disassemble the file
To retrieve the file headers
Syntax :
objdump <option(s)> <file(s)>

1. To get the File headers of an Object File. This command will print all the File headers related information of the file.
objdump -f khushi

Here, Khushi is the name of the object file which you want to get the file headers of.
2. To print the object-specific file header content. This command will print the object-specific file header content of the file.
objdump -p khushi

Here, Khushi is the name of the object file which you want to get the file headers of.
3. To print the section header content of the file. This command will print all the section header related information of the file.
objdump -h khushiKhushi

Here, Khushi is the name of the object file which you want to get the file headers of.
4. To print the all header content of the file. This command will print all the content header related information of the file.
objdump -x khushi

Here, Khushi is the name of the object file which you want to get the file headers of.
5. To print the assembler content of the sections capable of execution. This command will print the content of the assembler of sections that are executable.
objdump -d khushi

Here, Khushi is the name of the object file which you want to get the file headers of.
6. To print the assembler content of all the sections of the file. This command will print all the assembler content of all the sections of the file.
objdump -D khushi

Here, Khushi is the name of the object file which you want to get the file headers of.
7. To print the complete content of all the sections of the file. This command will print all the content of all the sections of the file.
objdump -s khushi

Here, Khushi is the name of the object file which you want to get the file headers of.
8. To display the help section of the command. This command will display all the parameters and the values it could receive in order to process the file.
objdump --help

linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Array Basics in Shell Scripting | Set 1
Extract unique objects by attribute from array of objects.

14 Feb, 2019
Given an array of objects and the task is to return the unique object by the attribute.
Examples:
Input: 
[ { name: 'Geeks', id: 10 },
  { name: 'GeeksForGeeks', id: 10 },
  { name: 'Geeks', id: 20 },
  { name: 'Geeks', id: 10 } ]
Output:
[ { name: 'Geeks', id: 10 }, 
  { name: 'GeeksForGeeks', id: 10 } ]

Approach: Let’s assume that name as attribute that differentiate the objects and need the object with minimum id number if multiple objects exists for same name. Use the map to store objects and check whether similar object seen or not.
Initialize an empty map.
Iterate through array using filter method.
Check if there is any entry in map with same name as of current object.
—-If true: i.e. there exists an entry with same name then, check if its id is less than current object’s id.
——–If true: i.e current object’s id is less than the id of the object returned by map then delete the map entry and enter the current object and return true.
——–if false: i.e. id of current object is greater than the id of object returned by map then return false.
—-If false: i.e. there is no entry in map with same name then enter the current object into map.
Print unique objects.
Example:
<script>objects = [{    name: 'Geeks',    id: 10}, {    name: 'GeeksForGeeks',    id: 10}, {    name: 'Geeks',    id: 20}, {    name: 'Geeks',    id: 10}];  let mymap = new Map();  unique = objects.filter(el => {    const val = mymap.get(el.name);    if(val) {        if(el.id < val) {            mymap.delete(el.name);            mymap.set(el.name, el.id);            return true;        } else {            return false;        }    }    mymap.set(el.name, el.id);    return true;});  console.log(unique);</script>
Output:
[ { name: 'Geeks', id: 10 }, 
  { name: 'GeeksForGeeks', id: 10 } ]

Time Complexity: O(n)Space Complexity: O(n)
Arrays
javascript-array
Arrays
JavaScript
Web Technologies
Web technologies Questions
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
How to write a running C code without main()?

21 Jun, 2022
Write a C language code that prints GeeksforGeeks without any main function. Logically it’s seems impossible to write a C program without using a main() function. Since every program must have a main() function because:-
It’s an entry point of every C/C++ program.
All Predefined and User-defined Functions are called directly or indirectly through the main.
Therefore we will use preprocessor(a program which processes the source code before compilation) directive #define with arguments to give an impression that the program runs without main. But in reality it runs with a hidden main function. Let’s see how the preprocessor doing their job:-  
Hence it can be solved in following ways:-
Using a macro that defines main 
Using a macro that defines main 
C
#include<stdio.h>#define fun mainint fun(void){    printf("Geeksforgeeks");    return 0;}
Output: Geeksforgeeks
         2. Using Token-Pasting Operator The above solution has word ‘main’ in it. If we are not allowed to even write main, we can use token-pasting operator (see this for details) 
C
#include<stdio.h>#define fun m##a##i##nint fun(){    printf("Geeksforgeeks");    return 0;}
Output: Geeksforgeeks
        3. Using Argumented Macro 
C
#include<stdio.h>#define begin(m,a,i,n) m##a##i##n#define start begin(m,a,i,n) void start() {printf("Geeksforgeeks");}
Output: Geeksforgeeks
       4. Modify the entry point during compilation 
C
#include<stdio.h>#include<stdlib.h> // entry point functionint nomain(); void _start(){     // calling entry point    nomain();    exit(0);} int nomain(){    puts("Geeksforgeeks");    return 0;}
Output: 
Geeksforgeeks
Compilation using command : gcc filename.c -nostartfiles (nostartfiles option tells the compiler to avoid standard linking) Explanation: Under normal compilation the body of _start() will contain a function call to main() [ this _start() will be appended to every code during normal compilation], so if that main() definition is not present it will result in error like “In function `_start’: (.text+0x20): undefined reference to `main’. In the above code what we have done is that we have defined our own _start() and defined our own entry point i.e nomain()
Refer Executing main() in C – behind the scene for another solution. References: Macros and Preprocessors in C 
Time Complexity: O(1)
Auxiliary Space: O(1)
This article is contributed by Abhay Rathi and improved by Shubham Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManasChhabra2
tarakki100
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
'this' pointer in C++
Ways to copy a vector in C++
Storage Classes in C
Understanding "extern" keyword in C
Check whether a given point lies inside a Triangle


Three points of a triangle are given; another point P is also given to check whether the point P is inside the triangle or not.
To solve the problem, let consider the points of the triangle are A, B, and C. When the area of triangle ΔABC = ΔABP + ΔPBC + ΔAPC, then the point P is inside the triangle.
Input:
Points of the triangle {(0, 0), (20, 0), (10, 30)} and point p (10, 15) to check.
Output:
Point is inside the triangle.
isInside(p1, p2, p3, p)
Input: Three points of a triangle, the point p to check.
Output: True, when p is inside the triangle.
Begin
   area := area of triangle(p1, p2, p3)
   area1 := area of triangle(p, p2, p3)
   area2 := area of triangle(p1, p, p3)
   area3 := area of triangle(p1, p2, p)
   if area = (area1 + area2 + area3), then
      return true
   else return false
End
#include <iostream>
#include<cmath>
using namespace std;

struct Point {
   int x, y;
};

float triangleArea(Point p1, Point p2, Point p3) {         //find area of triangle formed by p1, p2 and p3
   return abs((p1.x*(p2.y-p3.y) + p2.x*(p3.y-p1.y)+ p3.x*(p1.yp2.y))/2.0);
}

bool isInside(Point p1, Point p2, Point p3, Point p) {     //check whether p is inside or outside
   float area = triangleArea (p1, p2, p3);          //area of triangle ABC
   float area1 = triangleArea (p, p2, p3);         //area of PBC
   float area2 = triangleArea (p1, p, p3);         //area of APC
   float area3 = triangleArea (p1, p2, p);        //area of ABP

   return (area == area1 + area2 + area3);        //when three triangles are forming the whole triangle
}
 
int main() {
   Point p1={0, 0}, p2={20, 0}, p3={10, 30};
   Point p = {10, 15};
   if (isInside(p1, p2, p3, p))
      cout << "Point is inside the triangle.";
   else
      cout << "Point is not inside the triangle";
}
Point is inside the triangle.
Underline text with CSS

Use the text-decoration property to underline text with CSS. You can try to run the following code to underline text:
<html>
   <head>
   </head>
   <body>
      <p style = "text-decoration:underline;">
         India
      </p>
   </body>
</html>
Differentiate between int main and int main(void) function in C

int main represents that the function returns some integer even ‘0’ at the end of the program execution. ‘0’ represents the successful execution of a program.
The syntax of int main is as follows −
int main(){
   ---
   ---
   return 0;
}
int main(void) represents that the function takes NO argument. Suppose, if we don’t keep void in the bracket, the function will take any number of arguments.
The syntax of int main(void) is as follows −
int main(void){
   ---
   ---
   return 0;
}
Actually, both seem to be the same but, int main(void) is technically better as it clearly mentions that main can only be called without any parameter.
Generally, in C language, if a function signature does not specify any argument, that is the function can be called with any number of parameters or without any parameters.
Let’s take the same logic to implement the code for both functions. The only difference is the syntax for these functions.
Given below is the C program for int main() function without arguments −
 Live Demo
#include <stdio.h>
int main(){
   static int a = 10;
   if (a--){
      printf("after decrement a =%d\n", a);
      main(10);
   }
   return 0;
}
When the above program is executed, it produces the following result −
after decrement a =9
after decrement a =8
after decrement a =7
after decrement a =6
after decrement a =5
after decrement a =4
after decrement a =3
after decrement a =2
after decrement a =1
after decrement a =0
Given below is the same program but with int main(void) function −
#include <stdio.h>
int main(){
   static int a = 10;
   if (a--){
      printf("after decrement a =%d\n", a);
      main(10);
   }
   return 0;
}
When the above program is executed, it produces the following result −
error
If we write the same code for int main() and int main(void) we will get an error. This happens because void indicates that the function takes no parameters.
So, try to remove argument 10 in main in the above example and compile. Hence, after rectification the above code will be as follows −
 Live Demo
#include <stdio.h>
int main(){
   static int a = 10;
   if (a--){
      printf("after decrement a =%d\n", a);
      main();
   }
   return 0;
}
When the above program is executed, it produces the following result −
after decrement a =9
after decrement a =8
after decrement a =7
after decrement a =6
after decrement a =5
after decrement a =4
after decrement a =3
after decrement a =2
after decrement a =1
after decrement a =0
How to check the existence of URL in PHP?

15 May, 2019
Existence of an URL can be checked by checking the status code in the response header. The status code 200 is Standard response for successful HTTP requests and status code 404 means URL doesn’t exist.
Used Functions:
get_headers() Function: It fetches all the headers sent by the server in response to the HTTP request.
strpos() Function: This function is used to find the first occurrence of a string into another string.
Example 1: This example checks for the status code 200 in response header. If the status code is 200, it indicates URL exist otherwise not.
<?php  // Initialize an URL to the variable$url = "https://www.geeksforgeeks.org";  // Use get_headers() function$headers = @get_headers($url);  // Use condition to check the existence of URLif($headers && strpos( $headers[0], '200')) {    $status = "URL Exist";}else {    $status = "URL Doesn't Exist";}  // Display resultecho($status);  ?>
Output:
URL Exist

Example 2: This example checks for the status code 404 in response header. If the status code is 404, it indicates URL doesn’t exist otherwise URL exist.
<?php  // Initialize an URL to the variable$url = "https://www.geeksforgeeks.org";  // Use get_headers() function$headers = @get_headers($url);  // Use condition to check the existence of URLif($headers || strpos( $headers[0], '404')) {    $status = "URL Doesn't Exist";}else {    $status = "URL Exist";}  // Display resultecho($status);  ?>
Output:
URL Doesn't Exist

Example 3: This example uses curl_init() method to check the existence of an URL.
<?php  // Initialize an URL to the variable$url = "https://www.geeksfgeeks.org";  // Use curl_init() function to initialize a cURL session$curl = curl_init($url);  // Use curl_setopt() to set an option for cURL transfercurl_setopt($curl, CURLOPT_NOBODY, true);  // Use curl_exec() to perform cURL session$result = curl_exec($curl);  if ($result !== false) {          // Use curl_getinfo() to get information    // regarding a specific transfer    $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);         if ($statusCode == 404) {        echo "URL Doesn't Exist";    }    else {        echo "URL Exist";    }}else {    echo "URL Doesn't Exist";}   ?>
Output:
URL Doesn't Exist

Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comparing values of data frames in R Programming – all_equal() Function

23 Dec, 2021
all_equal() function in R Language is used to compare the values between dataframes.
Syntax: all_equal(target, current, check.attributes, check.names)
Parameters: 
target: object to compare
current: object to be compared with
check.attributes: If attributes of both be compared
check.names: If names be compared
Example 1: Comparing Equal Data frames
R
# R program to illustrate# all_equal function # Create three data framesdata1 <- data.frame(x1 = 1:10,                               x2 = LETTERS[1:10])data2 <- data.frame(x1 = 1:10,                    x2 = LETTERS[1:10])data3 <- data.frame(x1 = 2:12,                    x2 = LETTERS[1:5]) # Compare equal data framesall_equal(data1, data2, check.attributes = FALSE)                   
Output: 
TRUE
Here in the above code, we have compared equal data frames data1 and data2, and thus the output seems to be “TRUE”.
Example 2: Comparing Unequal dataframes
R
# R program to illustrate# all_equal function # Create three data framesdata1 <- data.frame(x1 = 1:10,                               x2 = LETTERS[1:10])data2 <- data.frame(x1 = 1:10,                    x2 = LETTERS[1:10])data3 <- data.frame(x1 = 2:12,                    x2 = LETTERS[1:5]) # Compare unequal data framesall_equal(data1, data3, check.names = FALSE)                   
Output: 
Rows in x but not y: 1, 2, 3, 4, 5, 6, 8, 9, 10. 
Rows in y but not x: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. 
Here in the above code, we compared the unequal data frames data1 and data3, so we got an error explaining what’s wrong in the code.
kumar_satyam
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.