code-rag-bench/online-tutorials huggingface dataset:
How to style the separator using CSS in JavaFX?

A separator is a horizontal or, the vertical line separating the UI elements of an application. In JavaFX the javafx.scene.control.Separator class represents a separator, to create a separator you need to instantiate this class. You can control the visual appearance of the separator using CSS.
You create an alternative style to the separator, by creating a CSS file and enabling it in your application. Once you do so, the created style will be applied to all the separators in the application.
The setStyle() method accepts the CSS in string format and applies the specified style to the separator. Using this method you can enhance the visualization of the separator as shown below −
//Setting style for the separator using CSS
sep.setStyle("-fx-border-color:#D2691E; -fx-border-width:2");
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class StylingSeparator extends Application {
   public void start(Stage stage) {
      //Creating the check boxes
      CheckBox checkBox1 = new CheckBox("Java");
      CheckBox checkBox2 = new CheckBox("Python");
      CheckBox checkBox3 = new CheckBox("C++");
      CheckBox checkBox4 = new CheckBox("MongoDB");
      CheckBox checkBox5 = new CheckBox("Neo4J");
      CheckBox checkBox6= new CheckBox("Casandra");
      //Creating the label
      Label label = new Label("Select Technologies:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //Creating a separator
      Separator sep = new Separator();
      sep.setOrientation(Orientation.VERTICAL);
      sep.setMaxHeight(75);
      sep.setHalignment(HPos.CENTER);
      //Setting style for the separator using CSS
      sep.setStyle("-fx-border-color:#D2691E; -fx-border-width: 2;");
      //Adding the check boxes and separator to the pane
      VBox box1 = new VBox(5);
      box1.setPadding(new Insets(5, 5, 5, 50));
      box1.getChildren().addAll(checkBox1, checkBox2, checkBox3);
      VBox box2 = new VBox(5);
      box2.setPadding(new Insets(5, 5, 5, 10));
      box2.getChildren().addAll(checkBox4, checkBox5, checkBox6);
      HBox root = new HBox(box1, box2);
      root.getChildren().add(1,sep);
      //Setting the stage
      Scene scene = new Scene(root, 595, 130, Color.BEIGE);
      stage.setTitle("Separator Example");
      stage.setScene(scene);
      stage.show();
   }
      public static void main(String args[]){
      launch(args);
   }
}
time.Time.YearDay() Function in Golang with Examples - GeeksforGeeks

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.YearDay() function in Go language is used to find the day of the year as provided by “t”. Where, the range for non-leap years is [1, 365] and for leap years it is [1, 366]. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) YearDay() int

Here, “t” is the stated time.
Return value: It returns the day of the year as specified by “t”.
Example 1:
// Golang program to illustrate the usage of// Time.YearDay() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring t in UTC    t := time.Date(2019, 6, 5, 11,              35, 04, 0, time.UTC)      // Calling YearDay method    yrday := t.YearDay()      // Prints the day     // of the year as specified    fmt.Printf("The day of the year "+      "in the 't' specified is: %v\n", yrday)}
Output:
The day of the year in the 't' specified is: 156

Example 2:
// Golang program to illustrate the usage of// Time.YearDay() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring t in UTC    t := time.Date(2020, 35, 60,        45, 67, 94, 7567, time.UTC)      // Calling YearDay method    yrday := t.YearDay()      // Prints the day of the year as specified    fmt.Printf("The day of the year in "+      "the 't' specified is: %v\n", yrday)}
Output:
The day of the year in the 't' specified is: 365

Here, the “t” stated above has values that are out of usual range but they are normalized while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Golang Maps
Slices in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
Classification of Context Free Grammars - GeeksforGeeks

21 Nov, 2019
Context Free Grammars (CFG) can be classified on the basis of following two properties:
1) Based on number of strings it generates.
If CFG is generating finite number of strings, then CFG is Non-Recursive (or the grammar is said to be Non-recursive grammar)
If CFG can generate infinite number of strings then the grammar is said to be Recursive grammar
During Compilation, the parser uses the grammar of the language to make a parse tree(or derivation tree) out of the source code. The grammar used must be unambiguous. An ambiguous grammar must not be used for parsing. 2) Based on number of derivation trees.
If there is only 1 derivation tree then the CFG is unambiguous.
If there are more than 1 derivation tree, then the CFG is ambiguous.
Examples of Recursive and Non-Recursive Grammars
Recursive Grammars
1) S->SaS    
   S->b
The language(set of strings) generated by the above grammar is :{b, bab, babab,...}, which is infinite.
2) S-> Aa
   A->Ab|c
The language generated by the above grammar is :{ca, cba, cbba ...}, which is infinite.Note: A recursive context-free grammar that contains no useless rules necessarily produces an infinite language.
Non-Recursive Grammars
   S->Aa
   A->b|c
The language generated by the above grammar is :{ba, ca}, which is finite.
 Types of Recursive Grammars
Based on the nature of the recursion in a recursive grammar, a recursive CFG can be again divided into the following:
Left Recursive Grammar (having left Recursion)
Right Recursive Grammar (having right Recursion)
General Recursive Grammar(having general Recursion)
 Note:A linear grammar is a context-free grammar that has at most one non-terminal in the right hand side of each of its productions.
 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
VaibhavRai3
jishnu3
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Construction of LL(1) Parsing Table
Directed Acyclic graph in Compiler Design (with examples)
Types of Parsers in Compiler Design
Difference between Compiler and Interpreter
Peephole Optimization in Compiler Design
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Python | Unpack whole list into variables - GeeksforGeeks

05 Sep, 2019
Sometimes, while working with list, we can have a wish to have each of element of list to be converted or unpacked into required variables. This problem can occur in web development domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using "=" operatorThis task can be performed using a “=” operator. In this we just ensure enough variables as the count of list elements and assign them to list, the list elements get allotted to variables in order of their assignment.
# Python3 code to demonstrate working of# Unpack whole list into variables# using "=" operator  # initialize listtest_list = [1, 3, 7, 4, 2]  # printing original listprint("The original list is : " + str(test_list))  # Unpack whole list into variables# using "=" operatorone, two, three, four, five = test_list  # printing resultprint("Variables as assigned are : " + str(one) + " "                                     + str(two) + " "                                     + str(three) + " "                                     + str(four) + " "                                     + str(five))
The original list is : [1, 3, 7, 4, 2]
Variables as assigned are : 1 3 7 4 2

 
Method #2 : Using NamedtupleThis problem can be solved using a namedtuple, which can store the list elements with a variable name that can be accessed by using a dot operator succeeding with name of variable initialized.
# Python3 code to demonstrate working of# Unpack whole list into variables# using Namedtuplefrom collections import namedtuple  # initialize listtest_list = [1, 3, 7, 4, 2]  # printing original listprint("The original list is : " + str(test_list))  # Unpack whole list into variables# using Namedtupletemp = namedtuple("temp", "one two three four five")res = temp(*test_list)  # printing resultprint("Variables as assigned are : " + str(res.one) + " "                                     + str(res.two) + " "                                     + str(res.three) + " "                                     + str(res.four) + " "                                     + str(res.five))
The original list is : [1, 3, 7, 4, 2]
Variables as assigned are : 1 3 7 4 2

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

A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.
The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;

Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement.
#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 10;

   /* do loop execution */
   LOOP:do {
   
      if( a == 15) {
         /* skip the iteration */
         a = a + 1;
         goto LOOP;
      }
		
      printf("value of a: %d\n", a);
      a++;

   }while( a < 20 );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

 Print
 Add Notes
 Bookmark this page
C++ program to check if first and the last characters of string are equal

Given with an input of string and the task is to check whether the first and last characters of given string is equal or not.
Input-: study
Output-: not equal
   As the starting character is ‘s’ and the end character of a string is ‘y’
Input-: nitin
Output-: yes it have first and last equal characters
   As the starting character is ‘n’ and the end character of a string is ‘n’
Approach used below is as follows −
Input the string and store in an array of strings.
Calculate the length of a string using length() function
Check first and last element of a string array, if they are equal return 1 else retrun -1
Print the resultant output
Start
Step 1-> declare function to check if first and last charcters are equal or not
   int check(string str)
   set int len = str.length()
      IF (len < 2)
         return -1
      End
      If (str[0] == str[len - 1])
         return 1
      End
      Else
         return 0
      End
Step 2->Int main()
   declare string str = "tutorialsPoint"
   set int temp = check(str)
   If (temp == -1)
      Print “enter valid input"
   End
   Else if (temp == 1)
      Print "yes it have first and last equal characters"
   End
   Else
      Print "Not equal”
Stop
 Live Demo
#include<iostream>
using namespace std;
//function to check if first and last charcters are equal or not
int check(string str) {
   int len = str.length();
   if (len < 2)
      return -1;
   if (str[0] == str[len - 1])
      return 1;
   else
      return 0;
}
int main() {
   string str = "tutorialsPoint";
   int temp = check(str);
   if (temp == -1)
      cout<<"enter valid input";
   else if (temp == 1)
      cout<<"yes it have first and last equal characters";
   else
      cout<<"Not equal";
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
yes it have first and last equal characters
HTML for Attribute

The HTML for attribute bounds the <label> element to the first labelable element which has an id same as the value of for attribute.
Following is the syntax −
1. Returning value of for attribute −
labelObject.htmlFor
Let us see an example of for attribute −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Label htmlFor</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Label-htmlFor</legend>
<label id="CurrentEditor" for="editorTwo">Current Editor:</label><br>
<input type="text" id="editorOne" placeholder="editorOne">
<input type="text" id="editorTwo" placeholder="editorTwo">
<input type="button" onclick="getEventData()" value="Change Editor">
<div id="divDisplay">Label for attribute set as editor two</div>
</fieldset>
</form>
<script>
   var divDisplay = document.getElementById("divDisplay");
   var labelSelect = document.getElementById("CurrentEditor");
   function getEventData() {
      if(labelSelect.htmlFor === 'editorTwo'){
         divDisplay.textContent = 'Label for attribute set as editor one';
         labelSelect.htmlFor = 'editorOne';
      }
   }
</script>
</body>
</html>
This will produce the following output −
1) Before clicking ‘Change Editor’ button −
2) After clicking ‘Change Editor’ button −
Tryit Editor v3.7 - Show Java

static void Main(string[] args)
    {
      // Type your username and press enter
      Console.WriteLine("Enter username:");

      // Create a string variable and get user input from the keyboard and store it in the variable
      string userName = Console.ReadLine();

      // Print the value of the variable (userName), which will display the input value
      Console.WriteLine("Username is: " + userName);
LISP - Characters

In LISP, characters are represented as data objects of type character.
You can denote a character object preceding #\ before the character itself. For example, #\a means the character a.
Space and other special characters can be denoted by preceding #\ before the name of the character. For example, #\SPACE represents the space character.
The following example demonstrates this −
Create a new source code file named main.lisp and type the following code in it.
(write 'a)
(terpri)
(write #\a)
(terpri)
(write-char #\a)
(terpri)
(write-char 'a)
When you execute the code, it returns the following result −
A
#\a
a
*** - WRITE-CHAR: argument A is not a character

Common LISP allows using the following special characters in your code. They are called the semi-standard characters.
#\Backspace
#\Tab
#\Linefeed
#\Page
#\Return
#\Rubout
Numeric comparison functions and operators, like, < and > do not work on characters. Common LISP provides other two sets of functions for comparing characters in your code.
One set is case-sensitive and the other case-insensitive.
The following table provides the functions −
Create a new source code file named main.lisp and type the following code in it.
; case-sensitive comparison
(write (char= #\a #\b))
(terpri)
(write (char= #\a #\a))
(terpri)
(write (char= #\a #\A))
(terpri)
   
;case-insensitive comparision
(write (char-equal #\a #\A))
(terpri)
(write (char-equal #\a #\b))
(terpri)
(write (char-lessp #\a #\b #\c))
(terpri)
(write (char-greaterp #\a #\b #\c))
When you execute the code, it returns the following result −
NIL
T
NIL
T
NIL
T
NIL


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Writing XAML Application On MAC OS

XAML applications can be developed on Mac as well. On Mac, XAML can be used as iOS and Android applications. To setup the environment on Mac, go to www.xamarin.com. Click on Products and select the Xamarin Platform. Download Xamarin Studio and install it. It will allow you to develop applications for the various platforms.
In this chapter, you will learn the basic XAML syntax/rules to write XAML applications. Let’s have a look at a simple XAML file.
<Window x:Class = "Resources.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "525"> 
	
   <Grid> 
         
   </Grid> 
</Window> 
As you can see in the above XAML file, there are different kinds of tags and elements. The following table briefly describes all the elements.
<Window
It is the opening object element or container of the root.
x:Class="Resources.MainWindow"
It is the partial class declaration which connects the markup to the partial class code behind defined in it.
xmlns 
Maps the default XAML namespace for WPF client/framework
xmlns:x 
XAML namespace for XAML language which maps it to x: prefix
>
End of object element of the root.
<Grid>
</Grid>
Starting and closing tags of an empty grid object.
</Window>
Closing the object element
Syntax rules for XAML is almost similar to XML. If you take a look at an XAML document, then you will notice that actually it is a valid XML file. However, an XML file cannot be a valid XAML file. It is because in XML, the value of the attributes must be a string, while in XAML, it can be a different object which is known as Property element syntax.
The syntax of an Object element starts with a left angle bracket (<) followed by the name of the object, e.g. Button.
The syntax of an Object element starts with a left angle bracket (<) followed by the name of the object, e.g. Button.
Define some Properties and attributes of that object element.
Define some Properties and attributes of that object element.
The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>).
The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>).
Example of simple object with no child element −
<Button/>

Example of object element with some attributes −
<Button Content = "Click Me" Height = "30" Width = "60"/> 

Example of an alternate syntax to define properties (Property element syntax) −
<Button> 
   <Button.Content>Click Me</Button.Content> 
   <Button.Height>30</Button.Height> 
   <Button.Width>60</Button.Width> 
</Button>

Example of Object with Child Element − StackPanel contains Textblock as child element
<StackPanel Orientation = "Horizontal"> 
   <TextBlock Text = "Hello"/> 
</StackPanel> 

 Print
 Add Notes
 Bookmark this page
How to use Popover Component in ReactJS ? - GeeksforGeeks

22 Feb, 2021
A Popover is a graphical control which is of is a container-type element that hovers over the parent window, and it makes sure that all other interaction is blocked until it is selected. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Popper Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure:
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. 
App.js
import React from "react";import Button from "@material-ui/core/Button";import Popover from "@material-ui/core/Popover";  export default function App() {  const [anchorEl, setAnchorEl] = React.useState(null);  const open = Boolean(anchorEl);    return (    <div style={{ display: "block", padding: 30 }}>      <h4>How to use Popover Component in ReactJS?</h4>      <Button        variant="contained"        color="primary"        onClick={(event) => {          setAnchorEl(event.currentTarget);        }}      >        Click me to open Popover      </Button>      <Popover        anchorEl={anchorEl}        open={open}        id={open ? "simple-popover" : undefined}        onClose={() => {          setAnchorEl(null);        }}        transformOrigin={{          horizontal: "center",          vertical: "top",        }}        anchorOrigin={{          horizontal: "center",          vertical: "bottom",        }}      >        How are you?      </Popover>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/popover/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set background images in ReactJS ?
How to create a table in ReactJS ?
ReactJS useNavigate() Hook
How to navigate on path by button click in react router ?
React-Router Hooks
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Map function and Lambda expression in Python to replace characters

We want to replace a character a1 with a character a2 and a2 with a1. For example,
For the input string,
"puporials toinp"
and characters p and t, we want the end string to look like −
"tutorials point"
For this we can use map function and lambdas to make the replacement. The map(lambda, input) function iterates over each item passed to it(in form of iterable input) and apply the lambda expression to it. So we can use it as follows −
 Live Demo
def replaceUsingMapAndLambda(sent, a1, a2):
# We create a lambda that only works if we input a1 or a2 and swaps them.
newSent = map(lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2, sent)
return ''.join(newSent)

print(replaceUsingMapAndLambda("puporials toinp", "p", "t"))
This will give the output −
tutorials point
GCD of an array of numbers in java

Following is the example to calculate the GCD of the numbers of an array.
Live Demo
public class GCDOfArrayofNumbers{
   public static int gcd(int a,int b){
      int res = 0;
      while (b > 0){
         int temp = b;
         b = a % b;
         a = temp;
         res = a;
      }
      return res;
   }
   public static void main(String arg[]){
      int[] myArray = {3, 6, 8};
      int result = gcd(myArray[0],myArray[1]);
      for(int i = 2; i < myArray.length; i++){
         result = gcd(result, myArray[i]);
      }
      System.out.println("Gcd of n numbers is: "+result);
   }
}
GCD of n numbers is: 1
Inserting Images in a PDF using Java

08 Dec, 2020
To insert an image in a PDF using Java can be done by using a library called iText. iText is a Java library originally created by Bruno Lowagie which allows creating PDF, read PDF, and manipulate them.
Libraries required : 
iText
slf4j (Logging Library)
Download the iText jar files directly from here & download the slf4j jar file directly from here. To use the libraries add the jar files to the classpath of the system
Approach:
Get the current working directory of the running java program to create the PDF file in the same locationCreate a PdfWriter object (from itextpdf library) which writes the PDF file to the given pathCreate an empty PdfDocument objectCreate Image object from the image on diskAdd Image to the Document
Get the current working directory of the running java program to create the PDF file in the same location
Create a PdfWriter object (from itextpdf library) which writes the PDF file to the given path
Create an empty PdfDocument object
Create Image object from the image on disk
Add Image to the Document
Implementation:
Java
import java.io.*;  // importing itext library packagesimport com.itextpdf.io.image.*;import com.itextpdf.kernel.pdf.*;import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Image;  public class InsertImagePDF {    public static void main(String[] args)        throws IOException    {        String currDir = System.getProperty("user.dir");                // Getting path of current working directory        // to create the pdf file in the same directory of        // the running java program        String pdfPath = currDir + "/InsertImage.pdf";                // Creating path for the new pdf file        PdfWriter writer = new PdfWriter(pdfPath);                // Creating PdfWriter object to write pdf file to        // the path        PdfDocument pdfDoc = new PdfDocument(writer);                // Creating a PdfDocument object        Document doc = new Document(pdfDoc);                // Creating a Document object        ImageData imageData = ImageDataFactory.create(            currDir + "/image.jpg");                // Creating imagedata from image on disk(from given        // path) using ImageData object        Image img = new Image(imageData);                // Creating Image object from the imagedata        doc.add(img);                // Adding Image to the empty document        doc.close();                // Closing the document        System.out.println(            "Image added successfully and PDF file created!");    }}
After execution of the program:
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Export Eclipse projects to GitHub?

01 Apr, 2021
Eclipse is an integrated development environment (IDE) used in computer programming. It contains a base workspace and an extensible plug-in system for customizing the environment. Eclipse is written mostly in Java and its primary use is for developing Java applications, but it may also be used to develop applications in other programming languages via plug-ins.
Git is an open-source version control system. It means that whenever a developer develops some project (like an app or website) or something, he/she constantly updates it catering to the demands of users, technology, and whatsoever it maybe, Git is a version control system that lets you manage and keep track of your source code history. Find the appropriate web project according to your requirement in GitHub.
In this article, we will see how to push an existing project to GitHub using Eclipse IDE.
Step 1: Open Eclipse IDE and right-click on the project you want to push and go to Team->share project.
Step 2: It will add the project to the given repository as shown below:
Step 3: Again right-click on the project and go to Team->commit.
Step 4: Drag and Drop the files you want to commit from Unchanged Changes to Staged Changes.
Step 5: Write the commit message in “Commit Message” and click “Commit and Push“.
Step 6: Fill in your UserID and password of GitHub and click “Log in“.
Step 7: Push to the new-branch of GitHub Repository and click “Push“.
The new branch is created on GitHub and is required to be merged by creating a pull request.
GitHub
Git
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to zoom an element on Hover using CSS ?

27 Apr, 2020
In this article, we learn about how to zoom on hover using CSS. It is called pseudo-selector and used to select all the elements when the user moves the mouse over the elements. When the user hovering on the element the scale function is called to increase the dimensions of the element. It can be used on all the elements. An element must be declared in the document to see the working of this selector in all the elements.
Example:
<!DOCTYPE html><html>  <head>    <title>        How to zoom an element        on Hover using CSS ?    </title>    <meta name="viewport" content=        "width=device-width, initial-scale=1">      <style>        * {            box-sizing: border-box;        }          .sudo {              padding: 50px;            background-color: red;            transition: transform .2s;            width: 160px;            height: 160px;            margin: 0 auto;            border-radius: 29px;        }          .sudo:hover {            -ms-transform: scale(4.6);            /* IE 9 */            -webkit-transform: scale(1.5);            /* Safari 3-8 */            transform: scale(1.5);        }    </style></head>  <body>    <center>        <h1>            GeeksForGeek        </h1>          <h2>            How TO – Zoom on Hover            in inline CSS        </h2>          <div class="sudo">            Hover on Me        </div>    </center></body>  </html>
Output:
Before Hovering on Red-Box:
After Hovering on Red-Box:
Supported Browsers: The supported browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
Simple Port Scanner using Sockets in Python

12 Jul, 2021
Prerequisites: Socket Programming in Python
Before going to the programming, let us discuss about ports. In this article, we will check the virtual ports of a server or websites, or localhost. Every port has a unique number. There are 65,535 ports available in a host starting from 0. We can assign the ports for any services.
Example 1: In this program, you can scan a number of ports in a certain range.
Python3
# Here we import two modules, socket and time import socketimport time s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # here we asking for the target website# or hosttarget = input('What you want to scan?: ') # next line gives us the ip address# of the targettarget_ip = socket.gethostbyname(target)print('Starting scan on host:', target_ip) # function for scanning ports  def port_scan(port):    try:        s.connect((target_ip, port))        return True    except:        return False  start = time.time() # here we are scanning port 0 to 4for port in range(5):    if port_scan(port):        print(f'port {port} is open')    else:        print(f'port {port} is closed') end = time.time()print(f'Time taken {end-start:.2f} seconds')
 
 
Output:  
 
What you want to scan?: localhost
Starting scan on host: 127.0.0.1
port 0 is closed
port 1 is closed
port 2 is closed
port 3 is closed
port 4 is closed
Time taken 8.12 seconds
 
Note: you can change the range in the for loop for change the number of ports to be scanned. For scanning a website or a host it can take a certain time so be patient.
 
Example 2: If you want to scan a particular port then go for this solution.
 
Python3
# importing the sockets moduleimport socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)target = input('What you want to scan?: ') # getting the ip address using gethostbyname# functiont_IP = socket.gethostbyname(target)print("Starting scan on host: ", t_IP)  def port_scan(port):    try:        s.connect((t_IP, port))        return True    except:        return False  port = int(input("Enter the port number to be scanned: ")) if port_scan(port):    print('Port', port, 'is open')else:    print("port", port, "is closed")
Output:
What you want to scan?: localhost
Starting scan on host:  127.0.0.1
Enter the port number to be scanned: 135
Port 135 is open
Note: Here we are scanning the localhost. You can scan any host or website. If you are getting any error then sockets is unable to connect the target or perhaps you did some mistake in your code.
Warnings: Without taking permission from the administration scanning ports of a server or a website can be considered as a crime. There are many free websites available for testing, you can use them.
anikaseth98
Python-socket
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
C# program to find Union of two or more Dictionaries


Firstly, set both the dictionaries −
Dictionary < string, int > dict1 = new Dictionary < string, int > ();
dict1.Add("water", 1);
dict1.Add("food", 2);
Dictionary < string, int > dict2 = new Dictionary < string, int > ();
dict2.Add("clothing", 3);
dict2.Add("shelter", 4);
Now, create HashSet and use UnionsWith() method to find the union between the above two
Dictionaries −
HashSet < string > hSet = new HashSet < string > (dict1.Keys);
hSet.UnionWith(dict2.Keys);
The following is the complete code −
 Live Demo
using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {
      Dictionary < string, int > dict1 = new Dictionary < string, int > ();
      dict1.Add("water", 1);
      dict1.Add("food", 2);

      Dictionary < string, int > dict2 = new Dictionary < string, int > ();
      dict2.Add("clothing", 3);
      dict2.Add("shelter", 4);

      HashSet < string > hSet = new HashSet < string > (dict1.Keys);
      hSet.UnionWith(dict2.Keys);

      Console.WriteLine("Union of Dictionary...");
      foreach(string val in hSet) {
         Console.WriteLine(val);
      }
   }
}
Union of Dictionary...
water
food
clothing
shelter
Box plot with min, max, average and standard deviation in Matplotlib

To make a box plot for min, max, average and standard deviation in matplotlib,
Set the figure size and adjust the padding between and around the subplots.
Create a random dataset of 5☓5 dimension.
Find min, max, average and standard deviation from the data.
Make a Pandas dataframe with Step 3, min, max, average and standard deviation data.
Make a box plot from the dataframe column.
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.randn(5, 5)
min = data.min(0)
max = data.max(0)
avg = data.mean(0)
std = data.std(0)
df = pd.DataFrame(dict(min=min, max=max, avg=avg, std=std))
df.boxplot()
plt.show()
C# program to find Largest, Smallest, Second Largest, Second Smallest in a List

Set the list
var val = new int[] {
   99,
   35,
   26,
   87
};
Now get the largest number.
val.Max(z => z);
Smallest number
val.Min(z => z);
Second largest number
val.OrderByDescending(z => z).Skip(1).First();
Second smallest number
val.OrderBy(z => z).Skip(1).First();
The following is the code −
 Live Demo
using System;
using System.Linq;

public class Program {
   public static void Main() {
      var val = new int[] {
         99,
         35,
         26,
         87
      };

      var maxNum = val.Max(z => z);
      Console.WriteLine("Maximum Number: " + maxNum);

      var minNum = val.Min(z => z);
      Console.WriteLine("Minimum Number: " + minNum);

      var secondMax = val.OrderByDescending(z => z).Skip(1).First();
      Console.WriteLine("Second Largest Number: " + secondMax);

      var secondMin = val.OrderBy(z => z).Skip(1).First();
      Console.WriteLine("Second Smallest Number: " + secondMin);
   }
}
Maximum Number: 99
Minimum Number: 26
Second Largest Number: 87
Second Smallest Number: 35
Get Last Entry in a MySQL table?

You can get the last entry in a MySQL table using ORDER BY. The first approach is as follows:
Case 1: Using DESC LIMIT
SELECT * FROM yourTableName ORDER BY yourColumnName DESC LIMIT 1;
The second approach is as follows:
Case 2: Using MAX()
SET @anyVariableName = (SELECT MAX(yourColumnName) FROM yourTableName);
SELECT *FROM yourtableName WHERE yourColumnName = @anyVariableName;
Now to understand both the approaches, let us create a table. The query to create a table is as follows:
mysql> create table lastEntryDemo
   -> (
   -> Id int NOt NULL AUTO_INCREMENT,
   -> Name varchar(30),
   -> Age int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into lastEntryDemo(Name,Age) values('Larry',24);
Query OK, 1 row affected (0.14 sec)

mysql> insert into lastEntryDemo(Name,Age) values('John',21);
Query OK, 1 row affected (0.19 sec)

mysql> insert into lastEntryDemo(Name,Age) values('David',22);
Query OK, 1 row affected (0.18 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Bob',25);
Query OK, 1 row affected (0.20 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Carol',29);
Query OK, 1 row affected (0.17 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Mike',23);
Query OK, 1 row affected (0.14 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Sam',20);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from lastEntryDemo;
The following is the output:
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | Larry |   24 |
|  2 | John  |   21 |
|  3 | David |   22 |
|  4 | Bob   |   25 |
|  5 | Carol |   29 |
|  6 | Mike  |   23 |
|  7 | Sam   |   20 |
+----+-------+------+
7 rows in set (0.00 sec)
Here is the query to get last entry using ORDER BY.
Case 1: DESC LIMIT
The query is as follows:
mysql> select *from lastEntryDemo order by Name desc limit 1;
The following is the output:
+----+------+------+
| Id | Name | Age  |
+----+------+------+
| 7  | Sam  | 20   |
+----+------+------+
1 row in set (0.00 sec)
Case 2: Using MAX()
The query is as follows:
mysql> set @MaxId = (select max(Id) from lastEntryDemo);
Query OK, 0 rows affected (0.00 sec)

mysql> select *from lastEntryDemo where Id = @MaxId;
The following is the output:
+----+------+------+
| Id | Name | Age  |
+----+------+------+
| 7  | Sam  | 20   |
+----+------+------+
1 row in set (0.00 sec)
PHP program to find the sum of odd numbers within a given range

To find the sum of odd numbers within a given range, the code is as follows −
 Live Demo
<?php
function odd_num_sum($val)
{
   $entries = (int)($val + 1) / 2;
   $sum = $entries * $entries;
   return $sum;
}
function num_in_range($low, $high)
{
   return odd_num_sum($high) - odd_num_sum($low - 1);
}
$low = 3;
$high = 23;
echo "The sum of odd natural numbers between the numbers 3 and 23 is ", num_in_range($low, $high);
?>
The sum of odd natural numbers between the numbers 3 and 23 is 141.75
A function named ‘odd_num_sum’ is defined that computes the sum of odd numbers within a specific range of numbers. The function ‘num_in_range’ gives the range of values between two numbers that are passed as parameters to this function. Outside both the function, the range values are defined and this function ‘num_in_range’ is called by passing the low and high values as parameters. Relevant output is displayed on the console.
SMTP protocol client  in Python (smtplib)

Python's standard library has 'smtplib' module which defines an SMTP client session object that can be used to send mail via Python program.
A mail server is an application that handles and delivers e-mail over the internet. Outgoing mail servers implement SMTP, or Simple MailTransfer Protocol, servers which are an Internet standard for email transmission.
Incoming mail servers come in two main varieties. POP3, or Post office protocol and IMAP, or Internet Message Access Protocol.
This function returns an object of SMTP class. It encapsulates and manages a connection to an SMTP or ESMTP server. Following arguments are defined in the signature of this function −
It has the following methods that support SMTP operations −
connect() −
This method establishes a connection to a host on a given port.
login() −
This function takes username and password arguments to login to SMTP server.
quit() −
This function terminates SMTP session.
data() −
The 'message' argument to this function is sent to server.
docmd()−
This function sends a command and returns its response code
ehlo() −
This function identifies the server.
starttls() −
This function starts TLS mode.
getreply() −
This function receives reply from the server in the form of response code.
putcmd() −
This function sends a command to the server.
send_message() −
This function converts the message to a byte string and passes it to send mail.
sendmail() −
This command performs an entire mail transaction.
The arguments are −
Code below uses smtp server of gmail to send an email. The SMTP object uses gmail's smtp server at  port 527. The ehlo() command identifies the server. We also activate Transport Layer Security to the outgoing mail message.
Next, the login() command is invoked by passing credentials as arguments toit. Finally the mail message is assembled by attaching it a header in the prescribed format and it is sent using sendmail() method. The SMTP object is closed afterward.
import smtplib
content="HelloWorld"
mail=smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
sender='pythonanytime@gmail.com'
recipient='mlathkar@gmail.com'
mail.login('pythonanytime@gmail.com','m15v5l61')
header='To:'+receipient+'\n'+'From:'\
+sender+'\n'+'subject:testmail\n'
content=header+content
mail.sendmail(sender,recipient, content)
mail.close()
Before running above script, ensure that sender's gmail account is provided access to 'less secure apps'. 
https://myaccount.google.com/lesssecureapps
Set the shown toggle button to ON.
Execute above script after performing above setting. The message should be delivered to recipient's inbox.
How to plot scatter points in a 3D figure with a colorbar in Matplotlib?

To plot scatter points in a 3D figure with a colorbar in matplotlib, we can use the scatter() and colorbar() methods.
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 a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add an axis as a subplot arrangement.
Add an axis as a subplot arrangement.
Create xs, ys and zs data points using numpy.
Create xs, ys and zs data points using numpy.
Use scatter() method to create a scatter plot.
Use scatter() method to create a scatter plot.
Use colorbar() method with scatter scalar mappable instance for colorbar.
Use colorbar() method with scatter scalar mappable instance for colorbar.
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
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
xs = np.random.rand(100)
ys = np.random.rand(100)
zs = np.random.rand(100)
sc = ax.scatter(xs, ys, zs, c=xs, cmap="copper")
plt.colorbar(sc)
plt.show()
Throwing exceptions from C++ constructors

This is a simple example of throwing exceptions from C++ constructors
Class descriptions and pseudocodes:
Begin
   Declare a class sample1.
      Declare a constructor of sample1.
         Print “Construct an Object of sample1”
      Declare a destructor of sample1.
         Print “Destruct an Object of sample1”
   Declare a class sample.
      Declare a constructor of sample2.
         Declare variable i of the integer datatype.
         Initialize i = 7.
         Print “Construct an Object of sample1”.
         Throw i.
      Declare a destructor of sample2.
         Print “Destruct an Object of sample2”
   Try:
      Declare an object s1 of class sample1.
      Declare an object s2 of class sample2.
   Catch(int i)
      Print “Caught”.
      Print the value of variable i
End.
#include <iostream>
using namespace std;
class Sample1 {
   public:
      Sample1() {
         cout << "Construct an Object of sample1" << endl;
      }
      ~Sample1() {
         cout << "Destruct an Object of sample1" << endl;
      }
};
class Sample2 {
   public:
      Sample2() {
         int i = 7;
         cout << "Construct an Object of sample2" << endl;
         throw i;
      }
      ~Sample2() {
         cout << "Destruct an Object of sample2" << endl;
      }
};
int main() {
   try {
      Sample1 s1;
      Sample2 s2;
   } catch(int i) {
      cout << "Caught " << i << endl;
   }
}
Construct an Object of sample1
Construct an Object of sample2
Destruct an Object of sample1
Caught 7
C library Macro - errno

The C library macro extern int errno is set by system calls and some library functions in the event of an error to indicate if anything went wrong.
Following is the declaration for errno macro.
extern int errno
NA
NA
NA
NA
The following example shows the usage of errno Macro.
#include <stdio.h>
#include <errno.h>
#include <string.h>

extern int errno ;

int main () {
   FILE *fp;

   fp = fopen("file.txt", "r");
   if( fp == NULL ) {
      fprintf(stderr, "Value of errno: %d\n", errno);
      fprintf(stderr, "Error opening file: %s\n", strerror(errno));
   } else {
      fclose(fp);
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result in case file file.txt does not exist −
Value of errno: 2
Error opening file: No such file or directory


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Printing a list to a Tkinter Text widget

The Tkinter Text widget is used to take multiline user text input. It provides many properties and built-in functions that can be used to customize the text widget. Let's suppose we need to create an application in which we want to display a list of items in a Text widget. To insert a list of items in a Text widget, we have to iterate over each item in the list and insert them in the Text widget. The following example demonstrates how to implement it.
# Import the required library
from tkinter import *

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

# Set the geometry
win.geometry("700x350")

# Add the list of items
days= ["Sun", "Mon", "Tue","Wed","Thu","Fri","Sat"]

text=Text(win, width=80, height=15)
text.pack()

# Iterate over each item in the list
for day in days:
   text.insert(END, day + '\n')
   
win.mainloop()
Running the above code will display the days of week as the list in a text widget.