code-rag-bench/online-tutorials huggingface dataset:
Find Simple Closed Path for a given set of points in C++

Consider we have a set of points. We have to find a simple closed path covering all points. Suppose the points are like below, and the next image is making a closed path on those points.
To get the path, we have to follow these steps −
Find the bottom left point as P
Find the bottom left point as P
Sort other n – 1 point based on the polar angle counterclockwise around P, if polar angle of two points are same, then put them as the distance is shortest
Sort other n – 1 point based on the polar angle counterclockwise around P, if polar angle of two points are same, then put them as the distance is shortest
Traverse the sorted list of points, then make the path
Traverse the sorted list of points, then make the path
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Point {
   public:
   int x, y;
};
Point p0;
int euclid_dist(Point p1, Point p2) {
   return (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y);
}
int orientation(Point p1, Point p2, Point p3) {
   int val = (p2.y - p1.y) * (p3.x - p2.x) - (p2.x - p1.x) * (p3.y - p2.y);
   if (val == 0) return 0; // colinear
   return (val > 0)? 1: 2; // clockwise or counterclock wise
}
int compare(const void *vp1, const void *vp2) {
   Point *p1 = (Point *)vp1;
   Point *p2 = (Point *)vp2;
   int o = orientation(p0, *p1, *p2);
   if (o == 0)
   return (euclid_dist(p0, *p2) >= euclid_dist(p0, *p1))? -1 : 1;
   return (o == 2)? -1: 1;
}
void findClosedPath(Point points[], int n) {
   int y_min = points[0].y, min = 0;
   for (int i = 1; i < n; i++) {
      int y = points[i].y;
      if ((y < y_min) || (y_min == y && points[i].x < points[min].x))
      y_min = points[i].y, min = i;
   }
   swap(points[0], points[min]);
   p0 = points[0];
   qsort(&points[1], n-1, sizeof(Point), compare); //sort on polar angle
   for (int i=0; i<n; i++)
   cout << "(" << points[i].x << ", "<< points[i].y <<"), ";
}
int main() {
   Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},{0, 0}, {1, 2}, {3, 1}, {3, 3}};
   int n = sizeof(points)/sizeof(points[0]);
   findClosedPath(points, n);
}
(0, 0), (3, 1), (1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (0, 3),
Text alignment in a Matplotlib legend

To make text alignment in a matplotlib legend, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x data points using numpy.
Create x data points using numpy.
Plot x, sin(x) and cos(x) using plot() method.
Plot x, sin(x) and cos(x) using plot() method.
Place legend using legend() method and initialize a method.
Place legend using legend() method and initialize a method.
Iterate the legend.get_texts() method to set the horizontal alignment.
Iterate the legend.get_texts() method to set the horizontal alignment.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-5, 5, 100)

plt.plot(x, np.sin(x), label="$y=sin(x)$")
plt.plot(x, np.cos(x), label="$y=cos(x)$")

legend = plt.legend(loc='upper right')

for t in legend.get_texts():
   t.set_ha('left')

plt.show()
Animate CSS z-index property

To implement animation on z-index property with CSS, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            position: absolute;
         }
         #box div {
            background-color: orange;
            border: 2px solid yellow;
            width: 100px;
            height: 100px;
            opacity: 0.3;
         }
         div#demo {
            opacity: 1;
            background-color: coral;
            z-index: 1;
            animation: myanim 3s;
         }
         @keyframes myanim {
            30% {
               z-index: 3;
            }
         }
      </style>
   </head>
   <body>
      <h1>CSS z-index property</h1>
      <div id = "box">
         <div id = "demo"></div>
         <div style = "top:20px;left:20px;z-index:1;">One</div>
         <div style = "top:40px;left:40px;z-index:2;">Two</div>
         <div style = "top:60px;left:60px;z-index:3;">Three</div>
         <div style = "top:80px;left:80px;z-index:4;">Four</div>
         <div style = "top:100px;left:40px;z-index:5;">Five</div>
         <div style = "top:120px;left:60px;z-index:6;">Six</div>
         <div style = "top:140px;left:80px;z-index:7;">Seven</div>
      </div>
   </body>
</html>
How to get the running processes with the WMI object using PowerShell?

To get the running processes with a WMI object, you need to use class Win32_Process. With this method, you will get more properties than the Get-Process command.
Get-WmiObject –Class Win32_Process
GENUS                    : 2
__CLASS                    : Win32_Process
__SUPERCLASS               : CIM_Process
__DYNASTY                  : CIM_ManagedSystemElement
__RELPATH                  : Win32_Process.Handle="0"
__PROPERTY_COUNT           : 45
__DERIVATION               : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER                   : DESKTOP-9435KM9
__NAMESPACE                : root\cimv2
__PATH                     : \\DESKTOP-9435KM9\root\cimv2:Win32_Process.Handle="0"
Caption                    : System Idle Process
CommandLine                :
CreationClassName          : Win32_Process
CreationDate               : 20191225011715.424076+330
CSCreationClassName        : Win32_ComputerSystem
CSName                     : DESKTOP-9435KM9
Description                : System Idle Process
ExecutablePath             :
ExecutionState             :
Handle                     : 0
HandleCount                : 0
InstallDate                :
KernelModeTime             : 5294149218750
MaximumWorkingSetSize      :
MinimumWorkingSetSize      :
Name                       : System Idle Process
OSCreationClassName        : Win32_OperatingSystem
OSName                     : Microsoft Windows 10 Pro|C:\WINDOWS|\Device\Harddisk0\Partition4
OtherOperationCount        : 0
OtherTransferCount         : 0
PageFaults                 : 9
PageFileUsage              : 60
ParentProcessId            : 0
PeakPageFileUsage          : 60
PeakVirtualSize            : 8192
PeakWorkingSetSize         : 12
Priority                   : 0
PrivatePageCount           : 61440
ProcessId                  : 0
QuotaNonPagedPoolUsage     : 1
QuotaPagedPoolUsage        : 0
QuotaPeakNonPagedPoolUsage : 1
QuotaPeakPagedPoolUsage    : 0
ReadOperationCount         : 0
ReadTransferCount          : 0
SessionId                  : 0
Status                     :
TerminationDate            :
ThreadCount                : 4
UserModeTime               : 0
VirtualSize                : 8192
WindowsVersion             : 10.0.18362
WorkingSetSize             : 8192
WriteOperationCount        : 0
WriteTransferCount         : 0
PSComputerName             : DESKTOP-9435KM9
ProcessName                : System Idle Process
Handles                    : 0
VM                         : 8192
WS                         : 8192
Path                       :
LocalDate isAfter() method in Java

It can be checked if a particular LocalDate is after the other LocalDate in a timeline using the isAfter() method in the LocalDate class in Java. This method requires a single parameter i.e. the LocalDate object that is to be compared. It returns true if the LocalDate object is after the other LocalDate object and false otherwise.
A program that demonstrates this is given as follows −
 Live Demo
import java.time.*;
public class Main {
   public static void main(String[] args) {
      LocalDate ld1 = LocalDate.parse("2019-02-20");
      LocalDate ld2 = LocalDate.parse("2019-02-14");
      System.out.println("The LocalDate ld1 is: " + ld1);
      System.out.println("The LocalDate ld2 is: " + ld2);
      boolean flag = ld1.isAfter(ld2);
      if(flag)
         System.out.println("\nLocalDate object ld1 is after LocalDate object ld2");
      else
         System.out.println("\nLocalDate object ld1 is before LocalDate object ld2");
   }
}
The LocalDate ld1 is: 2019-02-20
The LocalDate ld2 is: 2019-02-14
LocalDate object ld1 is after LocalDate object ld2
Now let us understand the above program.
The two LocalDate objects ld1 and ld2 are displayed. It is checked if the LocalDate object ld1 is after the LocalDate object ld2 in the timeline using the isAfter() method. The returned value is displayed using an if statement. A code snippet that demonstrates this is as follows −
LocalDate ld1 = LocalDate.parse("2019-02-20");
LocalDate ld2 = LocalDate.parse("2019-02-14");
System.out.println("The LocalDate ld1 is: " + ld1);
System.out.println("The LocalDate ld2 is: " + ld2);
boolean flag = ld1.isAfter(ld2);
if(flag)
   System.out.println("\nLocalDate object ld1 is after LocalDate object ld2");
else
   System.out.println("\nLocalDate object ld1 is before LocalDate object ld2");
C++ Program to Represent Graph Using Adjacency List

The adjacency list representation of a graph is linked list representation. In this representation we have an array of lists The array size is V. Here V is the number of vertices. In other words, we can say that we have an array to store V number of different lists. If a list header is vertex u, then it signifies that it will hold all of the adjacent vertices of u.
This representation takes O(V+2E) for undirected graph, and O(V+E) for directed graph. If the number of edges are increased, then the required space will also be increased.
This representation takes O(V+2E) for undirected graph, and O(V+E) for directed graph. If the number of edges are increased, then the required space will also be increased.
Input:
Output:
Input − The u and v of an edge {u,v}, and the adjacency list
Output − Adjacency List of the graph G
Begin
   Append v into the list at index u
   Append u into the list at index v
End
 Live Demo
#include<iostream>
#include<list>
#include<iterator>
using namespace std;
void displayAdjList(list<int> adj_list[], int v) {
  for(int i = 0; i<v; i++) {
     cout << i << "--->";
     list<int> :: iterator it;
     for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) {
        cout << *it << " ";
     }
     cout << endl;
   }
}
void add_edge(list<int> adj_list[], int u, int v) {   //add v into the list u, and u into list v
   adj_list[u].push_back(v);
   adj_list[v].push_back(u);
}
main(int argc, char* argv[]) {
   int v = 6;      //there are 6 vertices in the graph
   //create an array of lists whose size is 6
   list<int> adj_list[v];
   add_edge(adj_list, 0, 4);
   add_edge(adj_list, 0, 3);
   add_edge(adj_list, 1, 2);
   add_edge(adj_list, 1, 4);
   add_edge(adj_list, 1, 5);
   add_edge(adj_list, 2, 3);
   add_edge(adj_list, 2, 5);
   add_edge(adj_list, 5, 3);
   add_edge(adj_list, 5, 4);
   displayAdjList(adj_list, v);
}
0--->4 3
1--->2 4 5
2--->1 3 5
3--->0 2 5
4--->0 1 5
5--->1 2 3 4
What is conditional compilation in C language?

In C programming language, several directives control the selective compilation of portions of the program code. They are as follows −
#if
#else
#elif
#endif
The general form of #if is as follows −
#if constant_expression
   statement sequence
#endif
#else works much like the C keyword else.
#elif means "else if" and establishes an if else-if compilation chain.
Amongst other things, #if provides an alternative method of "commenting out" code.
For example,
#if 0
   printf("#d", total);
#endif
Here, the compiler will ignore printf("#d", total);
#ifdef and #ifndef
#ifdef means "if defined", and is terminated by an #endif.
#indef means "if not defined".
#undef
#undef removes a previously defined definition.
#line
#line changes the contents of __LINE__ which contains the line number of the currently compiled code and __FILE__ which is a string that contains the name of the source file being compiled. Both of which are predefined identifiers in the compiler.
#pragma
The #pragma directive is an implementation-defined directive which allows the various instructions to be given to the compiler.
Following is the C program to demonstrate #ifdef, #ifndef , #else and #endif −
 Live Demo
# include <stdio.h>
# define a 10
void main(){
   #ifdef a
   printf("\n Hello I am here..");
   #endif
   #ifndef a
   printf("\n Not defined ");
   #else
   printf("\n R u There ");
   #endif
}
When the above program is executed, it produces the following result −
Hello I am here..
R u There
Java Regular expression to check if a string contains alphabet

Following is the regular expression to match alphabet in the given input −
"^[a-zA-Z]*$"
Where,
^ matches the starting of the sentence.
[a-zA-z] matches the lower case and upper case letters.
* indicates the occurrence for zero or more times.
& indicates the end of the line.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ContainsAlphabetExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      String names[] = new String[5];
      for(int i=0; i<names.length;i++){
         System.out.println("Enter your name: ");
         names[i] = sc.nextLine();
      }
      //Regular expression to accept English alphabet
      String regex = "^[a-zA-Z]*$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      for (String name : names) {
         //Creating a Matcher object
         Matcher matcher = pattern.matcher(name);
         if(matcher.matches()) {
            System.out.println(name+" is a valid name");
         } else {
            System.out.println(name+" is not a valid name");
         }
      }
   }
}
Enter your name:
krishna
Enter your name:
kasyap
Enter your name:
maruthi#
Enter your name:
Sai_Ram
Enter your name:
Vani.Viswanath
krishna is a valid name
kasyap is a valid name
maruthi# is not a valid name
Sai_Ram is not a valid name
Vani.Viswanath is not a valid name
import java.util.Scanner;
public class Just {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.nextLine();
      String regex = "^[a-zA-Z]*$";
      boolean result = name.matches(regex);
      if(result) {
         System.out.println("Given name is valid");
      } else {
         System.out.println("Given name is not valid");
      }
   }
}
Enter your name:
vasu#dev
Given name is not valid
MongoDB query to add multiple documents

To perform multiple write operations, use bulkWrite(). Let us create an array list values. Following is the query −
> const arrayList = [
...    {"Value1":100, "Value2":200, "Name": "John"},
...    {"Value1":100, "Value2":200, "Name": "Bob"}
... ];
> let op1 = [];
> arrayList.forEach(({ Value1, Value2, Name }) => {
...    op1.push({
...       "updateOne": {
...          "filter": { Name},
...          "update": { "$set": { Value1, Value2, Name } },
...          "upsert": true
...       }
...    })
... });
> db.demo397.bulkWrite(op1);
{
   "acknowledged" : true,
   "deletedCount" : 0,
   "insertedCount" : 0,
   "matchedCount" : 0,
   "upsertedCount" : 2,
   "insertedIds" : {
   },
   "upsertedIds" : {
      "0" : ObjectId("5e5e8c07f995e1718151981c"),
      "1" : ObjectId("5e5e8c07f995e1718151981d")
   }
}
Display all documents from a collection with the help of find() method −
> db.demo397.find();
This will produce the following output −
{ "_id" : ObjectId("5e5e8c07f995e1718151981c"), "Name" : "John", "Value1" : 100, "Value2" : 200 }
{ "_id" : ObjectId("5e5e8c07f995e1718151981d"), "Name" : "Bob", "Value1" : 100, "Value2" : 200 }
MySQL Tryit Editor v1.0

SELECT CustomerName, City, Country FROM Customers
ORDER BY (CASE
WHEN City IS NULL THEN Country
ELSE City
END);
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to find the first character of a string in C#?

To get the first character, use the substring() method.
Let’s say the following isour string −
string str = "Welcome to the Planet!";
Now to get the first character, set the value 1 in the substring() method.
string res = str.Substring(0, 1);
Let us see the complete code −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      string str = "Welcome to the Planet!";
      string res = str.Substring(0, 1);
      Console.WriteLine(res);
   }
}
W
turtle.reset() function in Python - GeeksforGeeks

28 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to delete the turtle’s drawings and restore its default values. It doesn’t require any argument.
Syntax :
turtle.reset()

Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle  # motionfor i in range(20):    turtle.forward(2+2*i)    turtle.left(45)      # reset the workturtle.reset()
Output :
Example 2 :
Python3
# import packageimport turtle  # make turtle objects# and set positiont1 = turtle.Turtle()t2 = turtle.Turtle()t1.up()t1.setpos(-70, 0)t1.down()t2.up()t2.setpos(70, 0)t2.down()  # loop for patternfor i in range(20):    t1.forward(2+2*i)    t1.left(45)    t2.forward(2+2*i)    t2.left(90)  # reset first turtle# another remain as it ist1.reset()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
CouchDB - Attaching Files

You can attach files to CouchDB just like email. The file contains metadata like name and includes its MIME type, and the number of bytes the attachment contains. To attach files to a document you have to send PUT request to the server. Following is the syntax to attach files to the document −
$ curl -vX PUT http://127.0.0.1:5984/database_name/database_id
/filename?rev=document rev_id --data-binary @filename -H "Content-Type:
type of the content"
The request has various options that are explained below.
--data-binary@ − This option tells cURL to read a file’s contents into the HTTP request body.
--data-binary@ − This option tells cURL to read a file’s contents into the HTTP request body.
-H − This option is used to mention the content type of the file we are going to upload.
-H − This option is used to mention the content type of the file we are going to upload.
Let us attach a file named boy.jpg, to the document with id 001, in the database named my_database by sending PUT request to CouchDB. Before that, you have to fetch the data of the document with id 001 to get its current rev id as shown below.
$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   "_id": "001",
   "_rev": "1-967a00dff5e02add41819138abb3284d"
}
Now using the _rev value, send the PUT request to the CouchDB server as shown below.
$ curl -vX PUT http://127.0.0.1:5984/my_database/001/boy.jpg?rev=1-
967a00dff5e02add41819138abb3284d --data-binary @boy.jpg -H "ContentType:
image/jpg"
To verify whether the attachment is uploaded, fetch the document content as shown below−
$ curl -X GET http://127.0.0.1:5984/my_database/001
{
   "_id": "001",
   "_rev": "2-4705a219cdcca7c72aac4f623f5c46a8",
   "_attachments": {
      "boy.jpg": {
         "content_type": "image/jpg",
         "revpos": 2,
         "digest": "md5-9Swz8jvmga5mfBIsmCxCtQ==",
         "length": 91408,
         "stub": true
      }
   }
}

Using this option, you can upload a new attachment such as a file, image, or document, to the database. To do so, click on the Upload Attachment button. A dialog box will appear where you can choose the file to be uploaded. Select the file and click on the Upload button.
The file uploaded will be displayed under _attachments field. Later you can see the file by clicking on it.
 Print
 Add Notes
 Bookmark this page
How to get all children of a process using Process API in Java 9?

Process handling classes and related API have been introduced in Java 9. We can use the ProcessHandle interface and related methods to get pid and information about other related processes. We need to get all children of a process, then use java.lang.ProcessHandle.children() method. This method returns a stream, typically a process that has no children.
In the below example, we can get the first process and retrieve its children's process information.
import java.util.stream.Stream;
import java.util.Optional;

public class ChilderenProcessTest {
   public static void main(String args[]) throws InterruptedException {
      System.out.println("---------------------------");
      System.out.println("Children Processes:");
      Optional<ProcessHandle> processHandle = ProcessHandle.allProcesses().findFirst();
      processHandle.ifPresent(proc -> proc.children().forEach(child -> System.out.println("PID: [ " + child.pid() + " ], Cmd: [ " + child.info().command() + " ]")));
   }
}
---------------------------
Children Processes:
PID: [ 0 ], Cmd: [ Optional.empty ]
PID: [ 4 ], Cmd: [ Optional.empty ]
PID: [ 424 ], Cmd: [ Optional.empty ]
PID: [ 504 ], Cmd: [ Optional.empty ]
PID: [ 560 ], Cmd: [ Optional.empty ]
PID: [ 444 ], Cmd: [ Optional.empty ]
PID: [ 1236 ], Cmd: [ Optional.empty ]
PID: [ 1288 ], Cmd: [ Optional.empty ]
PID: [ 1408 ], Cmd: [ Optional.empty ]
PID: [ 1424 ], Cmd: [ Optional.empty ]
PID: [ 1452 ], Cmd: [ Optional.empty ]
PID: [ 1468 ], Cmd: [ Optional.empty ]
PID: [ 5412 ], Cmd: [ Optional[C:\WINDOWS\System32\taskhostex.exe] ]
PID: [ 3760 ], Cmd: [ Optional[C:\Program Files\Synaptics\SynTP\SynTPEnh.exe] ]
PID: [ 5216 ], Cmd: [ Optional[C:\WINDOWS\explorer.exe] ]
PID: [ 2460 ], Cmd: [ Optional[C:\Program Files (x86)\Dell Wireless\Bluetooth Suite\BtvStack.exe] ]
PID: [ 6064 ], Cmd: [ Optional[C:\Program Files\Realtek\Audio\HDA\RtkNGUI64.exe] ]
PID: [ 7172 ], Cmd: [ Optional[C:\Program Files (x86)\Google\Chrome\Application\chrome.exe] ]
PID: [ 860 ], Cmd: [ Optional[C:\Program Files (x86)\Google\Chrome\Application\chrome.exe] ]
PID: [ 9000 ], Cmd: [ Optional.empty ]
PID: [ 4180 ], Cmd: [ Optional[C:\WINDOWS\System32\cmd.exe] ]
PID: [ 3748 ], Cmd: [ Optional[C:\WINDOWS\System32\conhost.exe] ]
PID: [ 3376 ], Cmd: [ Optional.empty ]
PID: [ 2548 ], Cmd: [ Optional.empty ]
PID: [ 1820 ], Cmd: [ Optional[C:\Program Files\Java\jdk-9.0.4\bin\java.exe] ]
How to get the ip address in C#?

IP (Internet Protocol) Address is an address of your network hardware.
It helps in connecting your computer to other devices on your network and all over the world. An IP Address is made up of numbers or characters.
All devices that are connected to an internet connection have a unique IP address which means there’s a need of billions of IP addresses.
This requirement is fulfilled by the new IP version IPv6.
Private IP Address
A private IP address is the address of your device connected on the home or business network. If you have a few different devices connected to one ISP (Internet Service Provider), then all your devices will have a unique private IP address. This IP address cannot be accessed from devices outside your home or business network.
For example: 192.168.1.1
class Program{
   static void Main(string[] args){
      string IPAddress = GetIPAddress();
      System.Console.WriteLine(IPAddress);
      Console.ReadLine();
   }
   public static string GetIPAddress(){
      string IPAddress = string.Empty;
      IPHostEntry Host = default(IPHostEntry);
      string Hostname = null;
      Hostname = System.Environment.MachineName;
      Host = Dns.GetHostEntry(Hostname);
      foreach (IPAddress IP in Host.AddressList){
         if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork){
            IPAddress = Convert.ToString(IP);
         }
      }
      return IPAddress;
   }
}
192.168.1.1
Ionic - Javascript Keyboard

Keyboard is one of the automated features in Ionic. This means that Ionic can recognize when there is a need to open the keyboard.
There are some functionalities, which the developers can adjust while working with the Ionic keyboard. When you want to hide some elements while the keyboard is open, you can use the hide-on-keyboard-open class. To show you how this works we created input and button that needs to be hidden when the keyboard is open.
<label class = "item item-input">
   <input type = "text" placeholder = "Input 1">
</label>

<button class = "button button-block hide-on-keyboard-open">
   button
</button>
The above code will produce the following screen −
Now, when we tap on the input field, the keyboard will open automatically and the button will become hidden.
A nice feature of Ionic is that it will adjust elements on screen, so the focused element is always visible when the keyboard is open. The following image below shows ten Input forms and the last one is blue.
When we tap the blue form, Ionic will adjust our screen, so the blue form is always visible.
Note − This will work only if the screen is within a directive that has a Scroll View. If you start with one of the Ionic templates, you will notice that all templates use ion-content directive as a container to other screen elements, so the Scroll View is always applied.

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    185 Lectures 
     46.5 hours 

 Nikhil Agarwal
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.6 - Show C++

using namespace std;
​
int main() {
  int x, y;
  int sum;
  cout << "Type a number: ";
  cin >> x;
  cout << "Type another number: ";
  cin >> y;
  sum = x + y;
Evaluate Postfix Expression

For solving a mathematical expression, we need prefix or postfix form. After converting infix to postfix, we need postfix evaluation algorithm to find the correct answer.
Here also we have to use the stack data structure to solve the postfix expressions.
From the postfix expression, when some operands are found, pushed them in the stack. When some operator is found, two items are popped from the stack and the operation is performed in correct sequence. After that, the result is also pushed in the stack for future use. After completing the whole expression, the final result is also stored in the stack top.
Input:
Postfix expression: 53+62/*35*+
Output:
The result is: 39
postfixEvaluation(postfix)
Input: Postfix expression to evaluate.
Output: Answer after evaluating postfix form.
Begin
   for each character ch in the postfix expression, do
      if ch is an operator ⨀ , then
         a := pop first element from stack
         b := pop second element from the stack
         res := b ⨀ a
         push res into the stack
      else if ch is an operand, then
         add ch into the stack
   done
   return element of stack top
End
#include<iostream>
#include<cmath>
#include<stack>
using namespace std;

float scanNum(char ch) {
   int value;
   value = ch;
   return float(value-'0');   //return float from character
}

int isOperator(char ch) {
   if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
      return 1;    //character is an operator
   return -1;   //not an operator
}

int isOperand(char ch) {
   if(ch >= '0' && ch <= '9')
      return 1;    //character is an operand
   return -1;   //not an operand
}

float operation(int a, int b, char op) {
   //Perform operation
   if(op == '+')
      return b+a;
   else if(op == '-')
      return b-a;
   else if(op == '*')
      return b*a;
   else if(op == '/')
      return b/a;
   else if(op == '^')
      return pow(b,a);    //find b^a
   else
      return INT_MIN;    //return negative infinity
}

float postfixEval(string postfix) {
   int a, b;
   stack<float> stk;
   string::iterator it;

   for(it=postfix.begin(); it!=postfix.end(); it++) {
      //read elements and perform postfix evaluation
      if(isOperator(*it) != -1) {
         a = stk.top();
         stk.pop();
         b = stk.top();
         stk.pop();
         stk.push(operation(a, b, *it));
      }else if(isOperand(*it) > 0) {
         stk.push(scanNum(*it));
      }
   }
   return stk.top();
}

main() {
   string post = "53+62/*35*+";
   cout << "The result is: "<<postfixEval(post);
}
The result is: 39
Difference Between XML and HTML

In this post, we will understand the difference between HTML and XML.
It refers to Hyper Text Markup Language.
It refers to Hyper Text Markup Language.
It helps create web pages and applications.
It helps create web pages and applications.
It is a markup language.
It is a markup language.
It helps create static pages as well.
It helps create static pages as well.
It helps display data.
It helps display data.
It doesn’t transport data.
It doesn’t transport data.
HyperText helps define link between multiple web pages.
HyperText helps define link between multiple web pages.
Markup Language helps define text document using tags, which gives a structure to the web page.
Markup Language helps define text document using tags, which gives a structure to the web page.
It helps annotate the text so that a system can understand it and use it.
It helps annotate the text so that a system can understand it and use it.
It ignores minor errors.
It ignores minor errors.
It is not case sensitive.
It is not case sensitive.
There are specific number of tags in HTML.
There are specific number of tags in HTML.
These tags are predefined.
These tags are predefined.
It doesn’t preserve white spaces.
It doesn’t preserve white spaces.
Closing tags are not a necessity.
Closing tags are not a necessity.
An example of HTML −
<!DOCTYPE html>
<html>
<head>
   <title>My title</title>
</head>
<body>
   <h1>title</h1>
   <p>A sample</p>
</body>
</html>
XML stands for ‘eXtensible Markup Language’.
XML stands for ‘eXtensible Markup Language’.
It is case sensitive.
It is case sensitive.
It doesn’t allow errors.
It doesn’t allow errors.
It helps provide a framework that would define markup languages.
It helps provide a framework that would define markup languages.
The tags are user defined.
The tags are user defined.
These tags are extensible.
These tags are extensible.
The white space can be preserved.
The white space can be preserved.
The tags help describe data.
The tags help describe data.
These tags aren’t used to display data.
These tags aren’t used to display data.
The closing tags are required.
The closing tags are required.
It helps create web pages and applications.
It helps create web pages and applications.
It is dynamic since it helps transport data.
It is dynamic since it helps transport data.
The design goals focus on simplicity, usability across internet.
The design goals focus on simplicity, usability across internet.
It supports Unicode.
It supports Unicode.
It can also be used to represent arbitrary data structures required for web services.
It can also be used to represent arbitrary data structures required for web services.
An example of XML −
<?xml version = "1.0"?>
<contactinfo>
   <address category = "type">
      <name>Mark</name>
      <College>MIT</College>
      <mobile>6787878</mobile>
   </address>
</contactinfo>
Mark
MIT
6787878
Java program to verify whether a given element exists in an array.

You can find whether a particular exists in a given array using any of the search algorithms. Here, we will see examples for linear search and binary search.
Iterate through the array.
Compare each element with the required element.
import java.util.Scanner;
public class ArraySearch {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array: ");
      for(int i=0; i<size; i++){
         myArray[i] = sc.nextInt();
      }
      System.out.println("Enter the value tobe searched: ");
      int searchVal = sc.nextInt();
      for (int i =0 ; i<myArray.length; i++) {
         if (myArray[i] == searchVal) {
            System.out.println("The index of element "+searchVal+" is : " + i);
         }
      }
   }
}
Enter the size of the array that is to be created:
5
Enter the elements of the array:
30
20
5
12
55
Enter the value to be searched:
12
The index of element 12 is : 3
The Arrays class of the java.util package provides a method with name binarySearch(), this method accepts a sorted array and a value to search and returns the index of the given element in the array.
import java.util.Arrays;
import java.util.Scanner;
public class ArraySearch {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array: ");
      for(int i=0; i>size; i++){
         myArray[i] = sc.nextInt();
      }
      //Sorting the array
      Arrays.sort(myArray);
      System.out.println("The sorted int array is:");
      for (int number : myArray) {
         System.out.print(number+" ");
      }
      System.out.println(" ");
      System.out.println("Enter the value to be searched: ");
      int searchVal = sc.nextInt();
      int retVal = Arrays.binarySearch(myArray,searchVal);
      System.out.println("Element found");
      System.out.println("The index of element in the sorted array: " + retVal);
   }
}
Enter the size of the array that is to be created:
5
Enter the elements of the array:
30
20
5
12
55
The sorted int array is:
5 12 20 30 55
Enter the value to be searched:
12
Element found
The index of element in the sorted array: 1
Jython - Modules

A module is a Jython script in which one or more related functions, classes or variables are defined. This allows a logical organization of the Jython code. The Program elements defined in a module can be used in another Jython script by importing either the module or the specific element (function/class) from it.
In the following code (hello.py) a function SayHello() is defined.
#definition of function
defSayHello(str):
   print "Hello ", str
   return
To use the SayHello() function from another script, import the hello.py module in it.
import hello
hello.SayHello("TutorialsPoint")

However, this will import all functions defined in the module. In order to import specific function from module use following syntax.
from modname import name1[, name2[,... nameN]

For example, to import only the SayHello() function, change the above script as follows.
from hello import SayHello
SayHello("TutorialsPoint")
There is no need to prefix the name of the module while calling the function.
 Print
 Add Notes
 Bookmark this page
Fetch the first letter of a column value and insert it in another column with MySQL

For this, use the concept of LEFT() function. Let us first create a table −
mysql> create table DemoTable2036
   -> (
   -> FirstLetter varchar(20),
   -> Title varchar(20)
   -> );
Query OK, 0 rows affected (1.01 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2036(Title) values('Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable2036(Title) values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable2036(Title) values('Adam');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2036;
This will produce the following output −
+-------------+-------+
| FirstLetter | Title |
+-------------+-------+
| NULL        | Chris |
| NULL        | John  |
| NULL        | Adam  |
+-------------+-------+
3 rows in set (0.00 sec)
Following is the query to fetch the first letter of a column value and place it to another column −
mysql> update DemoTable2036
   -> set FirstLetter=left(Title,1);
Query OK, 3 rows affected (0.23 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable2036;
This will produce the following output −
+-------------+-------+
| FirstLetter | Title |
+-------------+-------+
| C           | Chris |
| J           | John  |
| A           | Adam  |
+-------------+-------+
3 rows in set (0.00 sec)
C++ Hello World | Practice | GeeksforGeeks

Let's begin your journey towards coding with the very first question of coding world. Your task is to write code which prints Hello World. 
Example 1:
Input:
No Input
Output:
Hello World
Your Task:
In the function helloWorld(), output a line "Hello World" (without quotes).
-1
heartlucy14322 hours ago
cout << “Hello World”;
0
2002skr222 days ago
#include<iostream>
using namespace std;
int main(){
cout<<"Hello World";
return 0;
}
0
vedantchourasiya142 days ago
#include <iostream>using namespace std;int main() {   cout << "Hello, world!";   return 0;}
0
gocode3 days ago
#include<iostream>
using namespace std;
 
int main()
{
    cout<<"Hello World"<<endl;
    return 0;
 
}
0
honeydancer253 days ago
#include<iostream>using namespace std;main(){   cout <<"Hello World";   return 0;}
0
dikshasharmaug216 days ago
#include<iostrem.h>
std;
int main(){
cout<<"hello world";
}
0
pshiv27041 week ago
Include<iostream.h>
using namespace std;
int main () {
cout<<"Hello world":
return 0;
}
0
annuchhikara20011 week ago
#include<iostream>
using namespace std;
int main(){
cout<<"Hello World";
return 0;
}
0
sk31951132 weeks ago
#include<iostream>
using namespace std;
int main ()
{
cout<<"HELLO WOLD!";
return 0;
}
0
sudhanshuranjan0292 weeks ago
#include<iostream>
Using namespace std;
Int main(){
Cout<<"HELLOW WORLD"<<endl;
Returns;}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Minimum element in a max heap in C++.

Find the element with the least value in max heap.
Let us consider below max heap.
In max heap value of the root node is always greater than its childer. Because of this property, we can conclude that value will be present in one of the leaf nodes. If heap contains n nodes then there will be ceil(n/2) leaves.
Max heap is a complete binary tree hence it can be represented in an array. In such heap the first leaf will be present after floor(n/2) index. So in our example, the first leave will be present at index 5.
We can use the below algorithm to find min value in a max heap −
1. Find first leaf in a heap and consider its value as min
2. Iterate all remaining leaves and update min value if leaf with smaller value is found
#include <iostream>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int getMinElement(int *heap, int n){
   int minElement = heap[n / 2];
   for (int i = n / 2 + 1; i < n; ++i) {
      minElement = min(minElement, heap[i]);
   }
   return minElement;
}
int main(){
   int heap[] = {120, 90, 100, 70, 75, 80, 60, 25, 40, 35};
   cout << "Min value: " << getMinElement(heap, SIZE(heap)) << "\n";
   return 0;
}
When you compile and execute the above program. It generates the following output −
Min value: 25
How to Make Countplot or barplot with Seaborn Catplot? - GeeksforGeeks

25 Nov, 2020
In Python, we can normally plot barcharts for numerical variables. But when it comes to the case of categorical variables then we cannot normally plot the count for each category. Here comes Seaborn Catplot in the picture. It allows you to plot the count of each category for non-numerical/categorical variables.
Countplot gives a graphical visual for the count of observations in each category using bars. This cannot be used for quantitative variables. It can be created by passing the count value to the kind parameter.
Example: Let’s take an example of a titanic dataset.
Python3
# import librariesimport matplotlib.pyplot as pltimport seaborn as sns  # setting background stylesns.set_style('darkgrid')  # import datasetdata = sns.load_dataset('titanic')data.head()
Output:
Example 1: Creating the countplot
Python3
# plot for count of passengers belonging# to each gendersns.catplot(x='sex', kind='count', data=data)plt.xlabel("Gender")plt.ylabel("Count")
Output:
Example 2: Creating the grouped countplot
Python3
# Grouped Countplot/Barplot# Count of passengers who survived# or didn't of each gendersns.catplot(x='sex', hue='survived',            kind='count', data=data)  plt.xlabel("Gender")plt.ylabel("Count")
Output:
Example 3: Creating the horizontal countplot
Python3
# Plotting horizontallysns.catplot(y='sex', hue='survived',             kind='count', data=data)  plt.xlabel("Count")plt.ylabel("Gender")
Output:
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Block Scoping in JavaScript.

Block scope is an area between two { curly braces } which can be between loops, if condition or switch statement. The let and const introduced in ES2015 allow us to create block scoped variables that can be accessed only inside those block.
Following is the code showing block scoping in JavaScript −
 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 {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result{
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Block scoping in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to access variable inside and outside the block</h3>
<script>
   let resEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      let b = 44;{
         let a = 22;
      }
      resEle.innerHTML = 'Accessing variable inside its block b = ' + b + '<br>';
      try{
         a
      }
      catch(err){
         resEle.innerHTML += 'Accessing variable outside its block a = ' + err;
      }
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
How to convert XML to JSON array in Java?

A JSON is a lightweight data-interchange format and the format of JSON is like a key-value pair. We can convert XML to JSON array using org.json.XML class, this provides a static method, XML.toJSONObject() to convert XML to JSON array.
public static JSONObject toJSONObject(java.lang.String string) throws JSONException
In the below example, converting XML to JSON array
import org.json.*;
public class ConvertXMLToJSONArrayTest {
   public static String xmlString= "<?xml version=\"1.0\" ?><root><test       attrib=\"jsontext1\">tutorialspoint</test><test attrib=\"jsontext2\">tutorix</test></root>";
   public static void main(String[] args) {
      try {
         JSONObject json = XML.toJSONObject(xmlString); // converts xml to json
         String jsonPrettyPrintString = json.toString(4); // json pretty print
         System.out.println(jsonPrettyPrintString);
      } catch(JSONException je) {
         System.out.println(je.toString());
      }
   }
}
{"root": {"test": [
    {
    "attrib": "jsontext1",
    "content": "tutorialspoint"
    },
    {
    "attrib": "jsontext2",
    "content": "tutorix"
    }
]}}
Playit

div#myDIV {  position:static;  width:100px;  height:100px;  background:red;  left:10px;  top:100px;}
How to divide an array into half in java?

Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range.
You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.
import java.util.Arrays;
import java.util.Scanner;

public class SplittingAnArray {
   public static void main(String args[]) {
      Scanner s =new Scanner(System.in);
      System.out.println("Enter the required size of the array ::");
      int size = s.nextInt();
      int [] myArray = new int[size];
      System.out.println("Enter elements of the array");
      for(int i=0; i< size; i++) {
         myArray[i] = s.nextInt();
      }
      System.out.println(Arrays.toString(myArray));
      int[] myArray1 = Arrays.copyOfRange(myArray, 0, myArray.length/2);
      int[] myArray2 = Arrays.copyOfRange(myArray, myArray.length/2, myArray.length);
      System.out.println("First half of the array:: "+Arrays.toString(myArray1));
      System.out.println("First second of the array:: "+Arrays.toString(myArray2));
   }
}
Enter the required size of the array ::
6
Enter elements of the array
45
63
78
96
42
19
[45, 63, 78, 96, 42, 19]
First half of the array:: [45, 63, 78]
First second of the array:: [96, 42, 19]
Convert Hex String to byte Array in Java

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array.
byte[] val = new byte[str.length() / 2];
Now, take a for loop until the length of the byte array.
for (int i = 0; i < val.length; i++) {
   int index = i * 2;
   int j = Integer.parseInt(str.substring(index, index + 2), 16);
   val[i] = (byte) j;
}
Let us see the complete example.
 Live Demo
public class Demo {
   public static void main(String args[]) {
      String str = "p";
      byte[] val = new byte[str.length() / 2];
      for (int i = 0; i < val.length; i++) {
         int index = i * 2;
         int j = Integer.parseInt(str.substring(index, index + 2), 16);
         val[i] = (byte) j;
      }
      System.out.println(val);
   }
}
[B@2a139a55