code-rag-bench/online-tutorials huggingface dataset:
Spring Boot CLI - Using Shell

Spring Boot CLI provides a Shell interface to run the commands in which we can directly run the commands as shown below. Go to E:\Test folder and type the following command.
E:/Test> spring shell

You will see the following output.
←[1mSpring Boot←[m←[2m (v2.6.3)←[m
Hit TAB to complete. Type 'help' and hit RETURN for help, and 'exit' to quit.
$

Type the following and see the output.
version
Spring CLI v2.6.3

You can press tab to auto complete the commands and type exit to finish the shell console.
Type the following and see the output.
$ exit
E:\Test\FirstApplication>

 Print
 Add Notes
 Bookmark this page
C# program to check if a value is in an array

Use the Array.Exists method to check if a value is in an array or not.
Set a string array −
string[] strArray = new string[] {"keyboard", "screen", "mouse", "charger" };
Let’s say you need to find the value “keyboard” in the array. For that, use Array.Exists() −
Array.Exists(strArray, ele => ele == "keyboard");
It returns a true value if element exists as shown below −
 Live Demo
using System;
using System.Text;
public class Demo {
   public static void Main() {
      string[] strArray = new string[] {"keyboard", "screen", "mouse", "charger" };
      bool res1 = Array.Exists(strArray, ele => ele == "harddisk");
      Console.WriteLine(res1);
      bool res2 = Array.Exists(strArray, ele => ele == "keyboard");
      Console.WriteLine(res2);
   }
}
False
True
How to create a ButtonBar in JavaFX?

A ButtonBar is simply an HBox on which you can arrange buttons. Typically, the buttons on a ButtonBar are Operating System specific. You can create a button bar by instantiating the javafx.scene.control.ButtonBar class.
The following Example demonstrates the creation of a ButtonBar.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ButtonBarExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating toggle buttons
      ToggleButton button1 = new ToggleButton("Java");
      button1.setPrefSize(60, 40);
      ToggleButton button2 = new ToggleButton("Python");
      button2.setPrefSize(60, 40);
      ToggleButton button3 = new ToggleButton("C++");
      button3.setPrefSize(60, 40);
      //Adding the buttons to a toggle group
      ToggleGroup group = new ToggleGroup();
      button1.setToggleGroup(group);
      button2.setToggleGroup(group);
      button3.setToggleGroup(group);
      //Create a ButtonBar
      ButtonBar buttonBar = new ButtonBar();
      //Adding the buttons to the button bar
      ButtonBar.setButtonData(button1, ButtonData.APPLY);
      ButtonBar.setButtonData(button2, ButtonData.APPLY);
      ButtonBar.setButtonData(button3, ButtonData.APPLY);
      buttonBar.getButtons().addAll(button1, button2, button3);
      //Adding the toggle button to the pane
      HBox box = new HBox(5);
      box.setPadding(new Insets(50, 50, 50, 150));
      box.getChildren().addAll(buttonBar);
      box.setStyle("-fx-background-color: BEIGE");
      //Setting the stage
      Scene scene = new Scene(box, 595, 150);
      stage.setTitle("Button Bar");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
JavaScript Object Properties

Properties in JavaScript are the values associated with an object. Following is the code implementing object properties 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;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript Object Properties</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to display name and age property from testObj
object
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   document.querySelector(".Btn").addEventListener("click", () => {
      let testObj = { name: "Rohan",age: 23,};
      sampleEle.innerHTML += "testObj.name = " + testObj.name + "<br>";
      sampleEle.innerHTML += "testObj.age = " + testObj.age + "<br>";
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
rmmod command in Linux with Examples - GeeksforGeeks

24 May, 2019
rmmod command in Linux system is used to remove a module from the kernel. Most of the users still use modprobe with the -r option instead of using rmmod.
Syntax:
rmmod [-f] [-s] [-v] [modulename]

Example:
rmmod bluetooth
Options:
rmmod command with help option: It will print the general syntax of the rmmod along with the various options that can be used with the rmmod command as well as gives a brief description about each option.
rmmod -v: This option prints messages about what the program is being doing. Usually rmmod only prints messages only if something went wrong.Example:rmmod -v bluetooth
Example:
rmmod -v bluetooth
rmmod -f: This option can be extremely dangerous. It takes no effect unless CONFIG_MODULE_FORCE_UNLOAD is being set when the kernel was compiled. With this option, you can remove the specified modules which are being used, or which are not being designed to be removed or have been marked as not safe.Example:sudo rmmod -f bluetooth
Example:
sudo rmmod -f bluetooth
rmmod -s : This option is going to send errors to syslog instead of standard error.Example:rmmod -s bluetooth
Example:
rmmod -s bluetooth
rmmod -V : This option will going to show version of program and then exit.rmmod -V
rmmod -V
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
tar command in Linux with examples
UDP Server-Client implementation in C
curl command in Linux with Examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
Python - Merge Pandas DataFrame with Inner Join

To merge Pandas DataFrame, use the merge() function. The inner join is implemented on both the DataFrames by setting under the “how” parameter of the merge() function i.e. −
how = “inner”
At first, let us import the pandas library with an alias −
import pandas as pd

Create DataFrame1 −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)


Now, create DataFrame2 −
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)


Merge DataFrames with a common column Car and "inner" in "how" parameter implements Inner Join −
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="inner")
Following is the code −
#
# Merge Pandas DataFrame with Inner Join
#

import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)

print"\nDataFrame2 ...\n",dataFrame2

# merge DataFrames with common column Car and "inner" in "how" parameter implements Inner Join
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="inner")
print"\nMerged dataframe with inner join...\n", mergedRes


This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW   100
1    Lexus   150
2     Audi   110
3  Mustang    80
4  Bentley   110
5   Jaguar    90

DataFrame2 ...
        Car   Reg_Price
0       BMW       7000
1     Lexus       1500
2     Tesla       5000
3   Mustang       8000
4  Mercedes       9000
5    Jaguar       6000

Merged dataframe with inner join...
       Car   Units   Reg_Price
0      BMW    100      7000
1    Lexus    150      1500
2  Mustang     80      8000
3   Jaguar     90      6000
select() function in Lua programming

The select function in Lua is used to return the number of arguments that are passed into it as an argument. It can be used in two forms, the first one includes passing an index and then it will return the numbers that are passed after that number into the function as an argument in a list format, the other pattern is if we pass the length operator as a first argument, in that case it simply returns a count of the multiple arguments that are provided.
Let’s explore both the cases in the examples shown below.
 Live Demo
print(select(1, "a", "b", "c")) --> a b c
print(select(2, "a", "b", "c")) --> b c
print(select(3, "a", "b", "c")) --> c
In the above example, we have passed an index, and we can see that the output from the select function will be the arguments after the given index.
a   b   c
b   c
c
 Live Demo
print(select("#")) --> 0
print(select("#", {1, 2, 3}))
print(select("#", 1, 2, 3))
print(select("#", {1,2,3}, 4, 5, {6,7,8}))
In the above example, instead of passing an index, I passed the length operator, and hence the output will simply be the number of arguments passed after it.
0
1
3
4
Textwrap - Text wrapping and filling in Python

The textwrap module provides TextWrapper class that performs wrapping or filling. It has convenience functions for the same purpose.
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph.
>>> sample_text = '''
The textwrap module provides some convenience functions, as well as TextWrapper class
that does all the work. If you’re just wrapping or filling one or two text strings,
the convenience functions should be good enough; otherwise, you should use an instance
of TextWrapper for efficiency.
'''
>>> import textwrap
>>> for line in (textwrap.wrap(sample_text, width = 50)):
print (line)

The textwrap module provides some convenience
functions, as well as TextWrapper class that
does all the work. If you’re just wrapping or
filling one or two text strings, the
convenience functions should be good enough;
otherwise, you should use an instance of
TextWrapper for efficiency.
>>> textwrap.fill(sample_text, width = 50)
' The textwrap module provides some convenience\nfunctions, as well as TextWrapper class that\ndoes all the work. If you’re just wrapping or\nfilling one or two text strings, the\nconvenience functions should be good enough;\notherwise, you should use an instance of\nTextWrapper for efficiency.'
Python MySQL - Create Database

You can create a database in MYSQL using the CREATE DATABASE query.
Following is the syntax of the CREATE DATABASE query −
CREATE DATABASE name_of_the_database

Following statement creates a database with name mydb in MySQL −
mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.04 sec)

If you observe the list of databases using the SHOW DATABASES statement, you can observe the newly created database in it as shown below −
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| logging            |
| mydatabase         |
| mydb               |
| performance_schema |
| students           |
| sys                |
+--------------------+
26 rows in set (0.15 sec)

After establishing connection with MySQL, to manipulate data in it you need to connect to a database. You can connect to an existing database or, create your own.
You would need special privileges to create or to delete a MySQL database. So if you have access to the root user, you can create any database.
Following example establishes connection with MYSQL and creates a database in it.
import mysql.connector

#establishing the connection
conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping database MYDATABASE if already exists.
cursor.execute("DROP database IF EXISTS MyDatabase")

#Preparing query to create a database
sql = "CREATE database MYDATABASE";

#Creating a database
cursor.execute(sql)

#Retrieving the list of databases
print("List of databases: ")
cursor.execute("SHOW DATABASES")
print(cursor.fetchall())

#Closing the connection
conn.close()
List of databases:
[('information_schema',), ('dbbug61332',), ('details',), ('exampledatabase',), ('mydatabase',), ('mydb',), ('mysql',), ('performance_schema',)]

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
What is the process of compilation and linking in python?

Compilation: The source code in python is saved as a .py file which is then compiled into a format known as byte code, byte code is then converted to machine code. After the compilation, the code is stored in .pyc files and is regenerated when the source is updated. This process is known as compilation.
Linking: Linking is the final phase where all the functions are linked with their definitions as the linker knows where all these functions are implemented. This process is known as linking.
import dis
def recursive_sum(n):
"""Function to return the sum of recursive numbers"""
if n <= 1:
return n
else:
return n + recursive_sum(n-1)

# change this value for a different result
number = 16
if number < 0:
print("The sum is",recursive_sum(number))
# by using dis module ,the bytecode is loaded into machine code ,and a piece of code that reads each instruction in the bytecode and executes whatever operation is indicated.
dis.dis(recursive_sum)
The sum is 136
4 0 LOAD_FAST 0 (n)
2 LOAD_CONST 1 (1)
4 COMPARE_OP 1 (<=)
6 POP_JUMP_IF_FALSE 12

5 8 LOAD_FAST 0 (n)
10 RETURN_VALUE

7 >> 12 LOAD_FAST 0 (n)
14 LOAD_GLOBAL 0 (recursive_sum)
16 LOAD_FAST 0 (n)
18 LOAD_CONST 1 (1)
20 BINARY_SUBTRACT
22 CALL_FUNCTION 1
24 BINARY_ADD
26 RETURN_VALUE
28 LOAD_CONST 2 (None)
30 RETURN_VALUE
Swift - Fallthrough Statement

A switch statement in Swift 4 completes its execution as soon as the first matching case is completed instead of falling through the bottom of subsequent cases as it happens in C and C++ programming languages.
The generic syntax of a switch statement in C and C++ is as follows −
switch(expression){
   case constant-expression :
      statement(s);
      break; /* optional */
   case constant-expression :
      statement(s);
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

Here we need to use a break statement to come out of a case statement, otherwise the execution control will fall through the subsequent case statements available below the matching case statement.
The generic syntax of a switch statement in Swift 4 is as follows −
switch expression {
   case expression1 :
      statement(s)
      fallthrough /* optional */
   case expression2, expression3 :
      statement(s)
      fallthrough /* optional */

   default : /* Optional */
      statement(s);
}

If we do not use fallthrough statement, then the program will come out of the switch statement after executing the matching case statement. We will take the following two examples to make its functionality clear.
The following example shows how to use a switch statement in Swift 4 programming without fallthrough −
var index = 10

switch index {
   case 100 :
      print( "Value of index is 100")
   case 10,15 :
      print( "Value of index is either 10 or 15")
   case 5 :
      print( "Value of index is 5")
   default :
      print( "default case")
}
When the above code is compiled and executed, it produces the following result −
Value of index is either 10 or 15

The following example shows how to use a switch statement in Swift 4 programming with fallthrough −
var index = 10

switch index {
   case 100 :
      print( "Value of index is 100")
      fallthrough
   case 10,15 :
      print( "Value of index is either 10 or 15")
      fallthrough
   case 5 :
      print( "Value of index is 5")
   default :
      print( "default case")
}
When the above code is compiled and executed, it produces the following result −
Value of index is either 10 or 15
Value of index is 5


    38 Lectures 
     1 hours 

 Ashish Sharma

    13 Lectures 
     2 hours 

 Three Millennials

    7 Lectures 
     1 hours 

 Three Millennials

    22 Lectures 
     1 hours 

 Frahaan Hussain

    12 Lectures 
     39 mins

 Devasena Rajendran

    40 Lectures 
     2.5 hours 

 Grant Klimaytys
 Print
 Add Notes
 Bookmark this page
Higher order components in React.js

Higher order component in short called as hoc. It’s a pattern which receives a component and returns a new component with add-on features to it.
//hoc is the name of a custom JavaScript function
const AddOnComponent= hoc(SimpleComponent);
We use component with state and/or props to build an UI. Similar way a hoc builds a new component from the provided component.
Use of hoc is making a cross cutting concerns in React. The components will take care of individual responsibility of single tasks while hoc functions will take care of cross cutting concerns.
Connect function from redux is an example of hoc.
Display welcome message to customer or admin based on user type.
Class App extends React.Component{
   render(){
      return (
         <UserWelcome message={this.props.message} userType={this.props.userType} />
      );
   }
}
Class UserWelcome extends React.Component{
   render(){
      return(
         <div>Welcome {this.props.message}</div>
      );
   }
}
const userSpecificMessage=(WrappedComponent)=>{
   return class extends React.Component{
      render(){
         if(this.props.userType==’customer’){
         return(
            <WrappedComponent {...this.props}/>
         );
         } else {
            <div> Welcome Admin </div>
         }
      }
   }
}
In the UserWelcome, we are just displaying message to user passed by parent component App.js.
The UserComponent is wrapped by hoc userSpecificMessage which received the props from wrapped component i.e. UserComponent
The hoc userSpecificMessage decides which message to display based on the type of user.
If the type of the user is customer it displays the message as it is. But if the user is not customer then it displays a Welcome Admin message by default.
With this way we can add the common functionality required by components in hoc and use it whenever required.
It allows code reuse and keeps the components clean with the individual tasks only.
How to list all functions in a Python module?

You can use the dir(module) to get all the attributes/methods of a module. For example,
>>> import math
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
But here as you can see attributes of the module(__name__, __doc__, etc) are also listed. You can create a simple function that filters these out using the isfunction predicate and getmembers(module, predicate) to get the members of a module. For example,
>>> from inspect import getmembers, isfunction
>>> import helloworld
>>> print [o for o in getmembers(helloworld) if isfunction(o[1])]
['hello_world']
Note that this doesn't work for built in modules as the type of functions for those modules is not function but built in function.
Extract day, hour, minute, etc. from a datetime column in PostgreSQL?

Let us create a new table containing a single timestamp column −
CREATE TABLE timestamp_test(
   ts timestamp
);
Now let us populate it with some data −
INSERT INTO timestamp_test(ts)
VALUES(current_timestamp),
(current_timestamp+interval '5 days'),
(current_timestamp-interval '18 hours'),
(current_timestamp+interval '1 year'),
(current_timestamp+interval '3 minutes'),
(current_timestamp-interval '6 years');
If you query the table (SELECT * from timestamp_test), you will see the following output −
Now, in order to extract hour, minute, etc. from the timestamp column, we use the EXTRACT function. Some examples are shown below −
SELECT EXTRACT(HOUR from ts) as hour from timestamp_test
Output −
Similarly −
SELECT EXTRACT(MONTH from ts) as month from timestamp_test
You can also extract not-so-obvious values like the ISO week, or the century −
SELECT EXTRACT(CENTURY from ts) as century, EXTRACT(WEEK from ts) as week from timestamp_test
To get a complete list of values you can extract from a timestamp column, see https://www.postgresql.org/docs/9.1/functions-datetime.html
Scala Collections - Fold Method

fold() method is a member of TraversableOnce trait, it is used to collapse elements of collections.
The following is the syntax of fold method.
def fold[A1 >: A](z: A1)(op: (A1, A1) ? A1): A1

Here, fold method takes associative binary operator function as a parameter. This method returns the result as value. It considers first input as initial value and second input as a function (which takes accumulated value and current item as input).
Below is an example program of showing how to use fold method −
object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get sum of all elements of the list
      val result = list.fold(0)(_ + _)
      //print result
      println(result)      
   }
}
Here we've passed 0 as initial value to fold function and then all values are added. Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

10


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to find and extract a number from a string in C#?

A regular expression is a pattern that could be matched against an input text.
The .Net framework provides a regular expression engine that allows such matching.
A pattern consists of one or more character literals, operators, or constructs.
Here are basic pattern metacharacters used by RegEx −
* = zero or more
? = zero or one
^ = not
[] = range
The ^ symbol is used to specify not condition.
the [] brackets if we are to give range values such as 0 - 9 or a-z or A-Z
 Live Demo
using System;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         string str1 = "123string456";
         string str2 = string.Empty;
         int val = 0;
         Console.WriteLine($"String with number: {str1}");
         for (int i = 0; i < str1.Length; i++){
            if (Char.IsDigit(str1[i]))
               str2 += str1[i];
         }
         if (str2.Length > 0)
            val = int.Parse(str2);
            Console.WriteLine($"Extracted Number: {val}");
         Console.ReadLine();
      }
   }
}
String with number: 123string456
Extracted Number: 123456
In the above example we are looping all the characters of the string str1. The
Char.IsDigit() validates whether the particular character is a number or not and adds it
to a new string which is later parsed to a numer.
 Live Demo
using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         string str1 = "123string456";
         string str2 = string.Empty;
         int val = 0;
         Console.WriteLine($"String with number: {str1}");
         var matches = Regex.Matches(str1, @"\d+");
         foreach(var match in matches){
            str2 += match;
         }
         val = int.Parse(str2);
         Console.WriteLine($"Extracted Number: {val}");
         Console.ReadLine();
      }
   }
}
String with number: 123string456
Extracted Number: 123456
In the above example, we use the regular expression (\d+) to extract only the numbers
from the string str1.
Format Year in yyyy format in Java

To format year in yyyy format is like displaying the entire year. For example, 2018.
Use the yyyy format like this −
SimpleDateFormat("yyyy");
Let us see an example −
// year in yyyy format
SimpleDateFormat simpleformat = new SimpleDateFormat("yyyy");
String strYear = simpleformat.format(new Date());
System.out.println("Current Year = "+strYear);
Above, we have used the SimpleDateFormat class, therefore the following package is imported −
import java.text.SimpleDateFormat;
The following is an example −
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss");
      System.out.println("Date and time = "+simpleformat.format(cal.getTime()));
      // displaying date
      simpleformat = new SimpleDateFormat("dd/MMMM/yyyy");
      String str = simpleformat.format(new Date());
      System.out.println("Current Date = "+str);
      // year in yyyy format
      simpleformat = new SimpleDateFormat("yyyy");
      String strYear = simpleformat.format(new Date());
      System.out.println("Current Year = "+strYear);
   }
}
Date and time = Mon, 26 Nov 2018 11:12:39
Current Date = 26/November/2018
Current Year = 2018
jQuery UI dialog close() Method - GeeksforGeeks

13 Jan, 2021
close() method is used to disable the dialog. This method does not accept any argument
Syntax:
$( ".selector" ).dialog("close");
Approach: First, add jQuery UI scripts needed for your project.
<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
Example:
HTML
<!doctype html><html lang="en">  <head>    <meta charset="utf-8">    <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"        rel="stylesheet">    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>    <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js">    </script>      <script>        $(function () {            $("#gfg").dialog({                autoOpen: false,            });            $("#geeks").click(function () {                $("#gfg").dialog("close");            });        });    </script></head>  <body>    <div id="gfg">        Jquery UI| close dialog method    </div>          <button id="geeks">Open Dialog</button></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
jQuery-UI
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
HTML | <img> align Attribute
Types of CSS (Cascading Style Sheet)
How to set the default value for an HTML <select> element ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery?
Traverse a collection of objects using the Enumeration Interface in Java

All the elements in a collection of objects can be traversed using the Enumeration interface. The method hasMoreElements( ) returns true if there are more elements to be enumerated and false if there are no more elements to be enumerated. The method nextElement( ) returns the next object in the enumeration.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.Enumeration;
import java.util.Vector;
public class Demo {
   public static void main(String args[]) throws Exception {
      Vector vec = new Vector();
      vec.add("John");
      vec.add("Gary");
      vec.add("Susan");
      vec.add("Mike");
      vec.add("Angela");
      Enumeration enumeration = vec.elements();
      System.out.println("The vector elements are:");
      while (enumeration.hasMoreElements()) {
         Object obj = enumeration.nextElement();
         System.out.println(obj);
      }
   }
}
The vector elements are:
John
Gary
Susan
Mike
Angela
Now let us understand the above program.
The Vector is created and Vector.add() is used to add the elements to the Vector. Then the vector elements are displayed using the enumeration interface. A code snippet which demonstrates this is as follows −
Vector vec = new Vector();
vec.add("John");
vec.add("Gary");
vec.add("Susan");
vec.add("Mike");
vec.add("Angela");
Enumeration enumeration = vec.elements();
System.out.println("The vector elements are:");
while (enumeration.hasMoreElements()) {
   Object obj = enumeration.nextElement();
   System.out.println(obj);
}
PyQt5 – How to open window in maximized format? - GeeksforGeeks

22 Apr, 2020
In this article we will see how to make a window to open in maximized format, which refer to full screen display window. We can do this by using showMaximized method which belongs to QWidget class.
Syntax : self.showMaximized()
Argument : It takes no argument.
Action performed It will open the window in full screen format.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating label        label = QLabel("Label", self)          # setting geometry to label        label.setGeometry(100, 100, 120, 40)          # adding border to label        label.setStyleSheet("border : 2px solid black")          # opening window in maximized size        self.showMaximized()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Python - Evaluate Expression given in String - GeeksforGeeks

27 Jul, 2021
Sometimes, while working with Python Strings, we can have certain computations in string format and we need to formulate its result. This can occur in domains related to Mathematics and data. Let’s discuss certain ways in which we can perform this task.
Method #1 : Using regex + map() + sum() The combination of above functions can be used to solve this problem. In this, we perform the task of computation using sum() and mapping of operator and operation using map(). This method can be used if the string has only + or -. Method #2 can be used for other operations as well.
Python3
# Python3 code to demonstrate working of# Expression evaluation in String# Using regex + map() + sum()import re # initializing stringtest_str = "45 + 98-10" # printing original stringprint("The original string is : " + test_str) # Expression evaluation in String# Using regex + map() + sum()res = sum(map(int, re.findall(r'[+-]?\d+', test_str))) # printing resultprint("The evaluated result is : " + str(res))
The original string is : 45+98-10
The evaluated result is : 133
 
Method #2 : Using eval() This is one of the way in which this task can be performed. In this, we perform computation internally using eval(). 
Python3
# Python3 code to demonstrate working of# Expression evaluation in String# Using eval() # initializing stringtest_str = "45 + 98-10" # printing original stringprint("The original string is : " + test_str) # Expression evaluation in String# Using eval()res = eval(test_str) # printing resultprint("The evaluated result is : " + str(res))
The original string is : 45+98-10
The evaluated result is : 133
 
asbrakavi
sagar0719kumar
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
C++ Program to Implement Sorted Singly Linked List

In data structure, Linked List is a linear collection of data elements. Each element or node of a list is comprising of two items - the data and a reference to the next node. The last node has a reference to null. Into a linked list the entry point is called the head of the list.
Each node in the list stores the contents and a pointer or reference to the next node in the list, in a singly linked list. Singly linked list does not store any pointer or reference to the previous node.
Developing a C++ program to implement sorted singly linked list.
Begin
   function createnode() to insert node in the list:
      It checks whether the list is empty or not.
      If the list is empty put the node as first element and update head.
      Initialize the next pointer with NULL.
      If list is not empty,
      It creates a newnode and inserts the number in the data field of the newnode.
      Now the newnode will be inserted in such a way that linked list will remain sorted.
      If it gets inserted at the last, then the newnode points to NULL.
      If the newnode inserted at the first, then the linked list starts from there.
End
Begin
   function display() to print the list content having n number of nodes:
      Initialize c = 0.
      Initialize pointer variable with the start address
      while (c <= n)
         Print the node info
         Update pointer variable
         Increment c.
End
#include<iostream>
using namespace std;
struct nod {
   int d;
   nod *n;
}
*p = NULL, *head = NULL, *q = NULL, *np = NULL;
int c = 0;
void createnode(int n) {
   np = new nod;
   np->d = n;
   np->n = NULL;
   if (c == 0) {
      head = np;
      p = head;
      p->n = head;
      c++;
   } else if (c == 1) {
      p = head;
      q = p;
      if (np->d < p->d) {
         np->n = p;
         head = np;
         p->n = np;
      } else if (np->d > p->d) {
         p->n = np;
         np->n = head;
      }
      c++;
   } else {
      p = head;
      q = p;
      if (np->d < p->d) {
         np->n = p;
         head = np;
         do {
            p = p->n;
         }
         while (p->n != q);
            p->n = head;
      } else if (np->d > p->d) {
         while (p->n != head && q->d < np->d) {
            q = p;
            p = p->n;
            if (p->n == head) {
               p->n = np;
               np->n = head;
            } else if (np->d< p->d) {
               q->n = np;
               np->n = p;
               break;
            }
         }
      }
   }
}
void display(int i) {
   nod *t = head;
   int c = 0;
   while (c <= i ) {
      cout<<t->d<<"\t";
      t = t->n;
      c++;
   }
}
int main() {
   int i = 0, n, a;
   cout<<"enter the no of nodes\n";
   cin>>n;
   while (i < n) {
      cout<<"\nenter value of node\n";
      cin>>a;
      createnode(a);
      i++;
   }
   cout<<"sorted singly link list"<<endl;
   display(n);
}
enter the no of nodes
5
enter value of node
6
enter value of node
4
enter value of node
7
enter value of node
3
enter value of node
2
sorted singly link list
2 3 4 6 7 2
Freeware v/s Shareware - GeeksforGeeks

18 Apr, 2019
Freeware:It is a software that is provided to the user free of cost with the fully functional mechanism having no expiry date.
Anyone can download it from the internet and use it for free.
Here the author retains the copyright to the software.Shareware:It is a commercial software that is initially distributed free of charge but later charge payment to keep the functionality on to continue the access.
 It allows the people to  “try before they buy”.
Referenceshttps://www.computerscience.gcse.guru/theory/free-software-freeware-sharewarehttps://www.diffen.com/difference/Freeware_vs_Shareware
Akanksha_Rai
Difference Between
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference Between Spark DataFrame and Pandas DataFrame
Difference between Internal and External fragmentation
Difference between Top down parsing and Bottom up parsing
Roadmap to Become a Web Developer in 2022
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Socket Programming in C/C++
DSA Sheet by Love Babbar
Must Do Coding Questions for Product Based Companies
How can I get days since epoch in JavaScript?

To get days since epoch, you need to use Math.abs() JavaScript method. Then use the Math.Floor() method to get the difference between dates since epoch and current date −
Live Demo
<html>
   <head>
      <title>JavaScript Clone Date</title>
   </head>
   <body>
      <script>
         var current_date, epocDate;

         current_date = new Date();
         document.write("Current Date: "+current_date);

         var epocDate = new Date(new Date().getTime() / 1000);
         document.write("<br>Since epoch: "+epocDate);
         var res = Math.abs(current_date - epocDate) / 1000;

         // get total days between two dates
         var days = Math.floor(res / 86400);
         document.write("<br>Difference (Days): "+days);
      </script>
   </body>
</html>
Current Date: Fri May 25 2018 15:42:43 GMT+0530 (India Standard Time)
Since epoch: Sun Jan 18 1970 21:44:03 GMT+0530 (India Standard Time)
Difference (Days): 17658
Groovy - remove()

Removes the element at the specified position in this List.
Object remove(int index)

Index – Index at which the value needs to be removed.
The removed value.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) {
      def lst = [11, 12, 13, 14];

      println(lst.remove(2));
      println(lst);
   }
}
When we run the above program, we will get the following result −
13 
[11, 12, 14]


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Partition problem

For this problem, a given set can be partitioned in such a way, that sum of each subset is equal.
At first, we have to find the sum of the given set. If it is even, then there is a chance to divide it into two sets. Otherwise, it cannot be divided.
For even value of the sum, then we will create a table named partTable, now use the following condition to solve the problem.
partTable[i, j] is true, when subset of array[0] to array[j-1] has sum equal to i, otherwise it is false.
Input:
A set of integers. {3, 1, 1, 2, 2, 1}
Output:
True if the set can be partitioned into two parts with equal sum.
Here the answer is true. One pair of the partitions are: {3, 1, 1}, {2, 2, 1}
checkPartition(set, n)
Input − The given set, the number of elements in the set.
Output − True when partitioning is possible to make two subsets of the equal sum.
Begin
   sum := sum of all elements in the set
   if sum is odd, then
      return

   define partTable of order (sum/2 + 1 x n+1)
   set all elements in the 0th row to true
   set all elements in the 0th column to false

   for i in range 1 to sum/2, do
      for j in range 1 to n, do
         partTab[i, j] := partTab[i, j-1]
         if i >= set[j-1], then
            partTab[i, j] := partTab[i, j] or with
            partTab[i – set[j-1], j-1]
      done
   done

   return partTab[sum/2, n]
End
#include <iostream>
using namespace std;

bool checkPartition (int set[], int n) {
   int sum = 0;

   for (int i = 0; i < n; i++)    //find the sum of all elements of set
      sum += set[i];

   if (sum%2 != 0)     //when sum is odd, it is not divisible into two set
      return false;

   bool partTab[sum/2+1][n+1];    //create partition table
   for (int i = 0; i <= n; i++)
      partTab[0][i] = true;    //for set of zero element, all values are true

   for (int i = 1; i <= sum/2; i++)
      partTab[i][0] = false;    //as first column holds empty set, it is false

   // Fill the partition table in botton up manner
   for (int i = 1; i <= sum/2; i++)  {
      for (int j = 1; j <= n; j++)  {
         partTab[i][j] = partTab[i][j-1];
         if (i >= set[j-1])
            partTab[i][j] = partTab[i][j] || partTab[i - set[j-1]][j-1];
      }      
   }  
   return partTab[sum/2][n];
}
   
int main() {
   int set[] = {3, 1, 1, 2, 2, 1};
   int n = 6;

   if (checkPartition(set, n))
      cout << "Given Set can be divided into two subsets of equal sum.";
   else
      cout << "Given Set can not be divided into two subsets of equal sum.";
} 
Given Set can be divided into two subsets of equal sum.
How to close an opened file in Python?

To close an opened file in python, just call the close function on the file's object.
>>> f = open('hello.txt', 'r')
>>> # Do stuff with file
>>> f.close()
Try not to open files in this way though as it is not safe. Use with ... open instead.
with open('hello.txt', 'r') as f:
    print(f.read())
The file auto closes as soon as you escape the with block.
Find the location with specified latitude and longitude using Python

06 Aug, 2021
In this article, we are going to write a python script to find the address of a specified latitude and longitude using the geopy module. The geopy module makes it easier to locate the coordinates of addresses, cities, countries, landmarks, and zipcode.
Installation:
To install GeoPy module, run the following command in your terminal.
pip install geopy
Step-by-step Approach:
Import the geopy module.
Initialize Nominatim API to get location from the input string.
Get location with geolocator.geocode() method.
Below is the program based on the above approach:
Python3
# Import modulefrom geopy.geocoders import Nominatim # Initialize Nominatim APIgeolocator = Nominatim(user_agent="geoapiExercises") # Assign Latitude & LongitudeLatitude = "25.594095"Longitude = "85.137566" # Displaying Latitude and Longitudeprint("Latitude: ", Latitude)print("Longitude: ", Longitude) # Get location with geocodelocation = geolocator.geocode(Latitude+","+Longitude) # Display locationprint("\nLocation of the given Latitude and Longitude:")print(location)
Output:
 
gulshankumarar231
adnanirshad158
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to sort an Array of Strings in Java

29 Nov, 2021
Array Of Strings
To sort an array of strings in Java, we can use Arrays.sort() function. 
Java
// A sample Java program to// sort an array of strings// in ascending and descending// orders using Arrays.sort(). import java.util.Arrays;import java.util.Collections; public class SortExample {    public static void main(String[] args)    {        String arr[] = { "practice.geeksforgeeks.org",                         "quiz.geeksforgeeks.org",                         "code.geeksforgeeks.org" };         // Sorts arr[] in ascending order        Arrays.sort(arr);        System.out.printf("Modified arr[] : \n%s\n\n",                          Arrays.toString(arr));         // Sorts arr[] in descending order        Arrays.sort(arr, Collections.reverseOrder());         System.out.printf("Modified arr[] : \n%s\n\n",                          Arrays.toString(arr));    }}
Modified arr[] : 
Modified arr[] : [quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org] 
 
ArrayList Of Strings
If we have an ArrayList to sort, we can use Collections.sort() 
Java
// A sample Java program to sort// an arrayList of strings// in ascending and descending// orders using Collections.sort(). import java.util.ArrayList;import java.util.Collections; public class SortExample {    public static void main(String[] args)    {        ArrayList<String> al = new ArrayList<String>();        al.add("practice.geeksforgeeks.org");        al.add("quiz.geeksforgeeks.org");        al.add("code.geeksforgeeks.org");         // Sorts ArrayList in ascending order        Collections.sort(al);        System.out.println(            "Modified ArrayList : \n" + al);         // Sorts arr[] in descending order        Collections.sort(al,                         Collections.reverseOrder());         System.out.println(            "Modified ArrayList : \n" + al);    }}
Modified ArrayList :  Modified ArrayList : [quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org] 
 
surinderdawra388
Java-ArrayList
Java-Arrays
Arrays
Java
Sorting
Strings
Arrays
Strings
Sorting
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get a specific row in a given Pandas DataFrame

20 Aug, 2020
In the Pandas DataFrame  we can find the specified row value with the using function iloc(). In this function we pass the row number as parameter.
Syntax : pandas.DataFrame.iloc[]Parameters :
Index Position : Index position of rows in integer or list of integer.
Return type : Data frame or Series depending on parameters
Example 1 :
# importing the moduleimport pandas as pd  # creating a DataFramedata = {'1' : ['g', 'e', 'e'],         '2' : ['k', 's', 'f'],         '3' : ['o', 'r', 'g'],         '4' : ['e', 'e', 'k']}df = pd.DataFrame(data)print("Original DataFrame")display(df)  print("Value of row 1")display(df.iloc[1])
Output :
Example 2:
# importing the moduleimport pandas as pd  # creating a DataFramedata = {'Name' : ['Simon', 'Marsh', 'Gaurav',                  'Alex', 'Selena'],          'Maths' : [8, 5, 6, 9, 7],          'Science' : [7, 9, 5, 4, 7],         'English' : [7, 4, 7, 6, 8]} df = pd.DataFrame(data)print("Original DataFrame")display(df)  print("Value of row 3 (Alex)")display(df.iloc[3])
Output :
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.