code-rag-bench/online-tutorials huggingface dataset:
SimpleDateFormat applyPattern() Method in Java with Examples - GeeksforGeeks

08 Jul, 2021
The applyPattern() Method of SimpleDateFormat class is used to set a given defined pattern to the Date Format. It simply converts a particular date and time to a specific format as defined by the user for eg., dd/ MM/ yyyy HH:mm Z or MM/ dd/ yyyy HH:mm Z.Syntax:  
public void applyPattern(String pattern)
Parameters: The method takes one parameter pattern of String type and refers to the new date and time pattern for this date format.Return Value: The method returns void type.Below programs illustrate the working of applyPattern() Method of SimpleDateFormat:Example 1:  
Java
// Java code to illustrate// applyPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo {     public static void main(String[] args)        throws InterruptedException    {        SimpleDateFormat SDFormat            = new SimpleDateFormat();         // Initializing the calendar Object        Calendar cal = Calendar.getInstance();         // Using the below pattern        String new_pat = "dd/ MM/ yyyy HH:mm Z";         // Use of applyPattern() method        SDFormat.applyPattern(new_pat);         // Displaying Current date and time        String curr_date            = SDFormat.format(cal.getTime());         System.out.println("The Current Date: "                           + curr_date);         // Displaying the pattern        System.out.println("Applied Pattern: "                           + SDFormat.toPattern());    }}
The Current Date: 29/ 01/ 2019 07:22 +0000
Applied Pattern: dd/ MM/ yyyy HH:mm Z
 
Example 2:  
Java
// Java code to illustrate// applyPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo {     public static void main(String[] args)        throws InterruptedException    {        SimpleDateFormat SDFormat            = new SimpleDateFormat();         // Initializing the calendar Object        Calendar cal = Calendar.getInstance();         // Using the below pattern        String new_pat = "MM/ dd/ yyyy HH:mm Z";         // Use of applyPattern() method        SDFormat.applyPattern(new_pat);         // Displaying Current date and time        String curr_date            = SDFormat.format(cal.getTime());        System.out.println("The Current Date: "                           + curr_date);         // Displaying the pattern        System.out.println("Applied Pattern: "                           + SDFormat.toPattern());    }}
The Current Date: 01/ 29/ 2019 07:22 +0000
Applied Pattern: MM/ dd/ yyyy HH:mm Z
 
clintra
Java-Functions
Java-SimpleDateFormat
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
PL/SQL - EXIT Statement

The EXIT statement in PL/SQL programming language has the following two usages −
When the EXIT statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
When the EXIT statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
If you are using nested loops (i.e., one loop inside another loop), the EXIT statement will stop the execution of the innermost loop and start executing the next line of code after the block.
If you are using nested loops (i.e., one loop inside another loop), the EXIT statement will stop the execution of the innermost loop and start executing the next line of code after the block.
The syntax for an EXIT statement in PL/SQL is as follows −
EXIT;

DECLARE 
   a number(2) := 10; 
BEGIN 
   -- while loop execution  
   WHILE a < 20 LOOP 
      dbms_output.put_line ('value of a: ' || a); 
      a := a + 1; 
      IF a > 15 THEN 
         -- terminate the loop using the exit statement 
         EXIT; 
      END IF; 
   END LOOP; 
END; 
/ 
When the above code is executed at the SQL prompt, 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: 15  

PL/SQL procedure successfully completed.

The EXIT-WHEN statement allows the condition in the WHEN clause to be evaluated. If the condition is true, the loop completes and control passes to the statement immediately after the END LOOP.
Following are the two important aspects for the EXIT WHEN statement −
Until the condition is true, the EXIT-WHEN statement acts like a NULL statement, except for evaluating the condition, and does not terminate the loop.
Until the condition is true, the EXIT-WHEN statement acts like a NULL statement, except for evaluating the condition, and does not terminate the loop.
A statement inside the loop must change the value of the condition.
A statement inside the loop must change the value of the condition.
The syntax for an EXIT WHEN statement in PL/SQL is as follows −
EXIT WHEN condition;

The EXIT WHEN statement replaces a conditional statement like if-then used with the EXIT statement.
DECLARE 
   a number(2) := 10; 
BEGIN 
   -- while loop execution  
   WHILE a < 20 LOOP 
      dbms_output.put_line ('value of a: ' || a);  
      a := a + 1; 
      -- terminate the loop using the exit when statement 
   EXIT WHEN a > 15; 
   END LOOP; 
END;   
/
When the above code is executed at the SQL prompt, 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: 15  

PL/SQL procedure successfully completed.   

 Print
 Add Notes
 Bookmark this page
DirectX - Pixel Shader

The Pixel Shader is called once per pixel in comparison to vertex shader which it calls as per vertex and gets its data from the preceding pipeline station respectively from the preceding Shader. It calculates the required pixel color (pixel depth or any other values are possible) and returns them to the required pipeline.
The Pixel Shader is considered as the last Shader in the pipeline and therefore already gives the data to the Output Merger, which helps us to determine the final pixel color. Pixel Shaders are prominently used for rendering surfaces but in comparison to shaders, they can be used for special calculations. The two most important ways to use them include texturing and lighting, for which we will focus on the example following the pixel shader representation or structure.
In principle with reference to snapshot given below, you will find there is no real difference to a Vertex Shader, only the input and output data is different.
The following code demonstrates how texturing and lighting with a Pixel Shader is done −
struct PixelShaderInput{
   float4 position : SV_POSITION;
   float3 outVec : POSITION0;
   float3 normal : NORMAL0;
   float3 light : POSITION1;
};
float4 main(PixelShaderInput input) : SV_TARGET{
   float3 L = normalize(input.light);
   float3 V = normalize(input.outVec);
   float3 R = normalize(reflect(L, input.normal));
   float4 diffuse = Ka + (lightColor * Kd * max(dot(input.normal, L), 0.0f));
   diffuse = saturate(diffuse);
   float4 specular = Ks * pow(max(dot(R, V), 0.0f), shininess.x - 50.0f);
   specular = saturate(specular);
   float4 finalColor = diffuse + specular;
   return finalColor;
}
The buffer includes the light position in world coordinates which is created and a texture with reference to sampler is always used. The Sampler is mandatory to read the texture color on the corresponding texture coordinates. The Pixel Shader includes the input data received from the Vertex Shader which is interpolated by DirectX. This means with reference to the current pixel from the three vertices of the current triangle we can draw, distance- and mode-dependent "averages" are calculated.
 Print
 Add Notes
 Bookmark this page
Pad the values of the column with zeros in MySQL

For this, use the concept of ZEROFILL. It pads the displayed value of the field with zeros up to the display width set in the column definition
Let us first create a table −
mysql> create table DemoTable626 (Value int(5) zerofill);
Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable626 values(9);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable626 values(12);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable626 values(567);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable626 values(3478);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable626;
This will produce the following output −
+-------+
| Value |
+-------+
| 00009 |
| 00012 |
| 00567 |
| 03478 |
+-------+
4 rows in set (0.00 sec)
Fetch specific multiple documents in MongoDB

To fetch specific multiple documents in MongoDB, use $in. Let us create a collection with documents −
> db.demo593.insertOne({id:1,"Name":"Chris"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e93177dfd2d90c177b5bcd9")
}
> db.demo593.insertOne({id:2,"Name":"John"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e931785fd2d90c177b5bcda")
}
> db.demo593.insertOne({id:3,"Name":"Bob"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e93178cfd2d90c177b5bcdb")
}
> db.demo593.insertOne({id:4,"Name":"Sam"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e931792fd2d90c177b5bcdc")
}
Display all documents from a collection with the help of find() method −
> db.demo593.find();
This will produce the following output −
{ "_id" : ObjectId("5e93177dfd2d90c177b5bcd9"), "id" : 1, "Name" : "Chris" }
{ "_id" : ObjectId("5e931785fd2d90c177b5bcda"), "id" : 2, "Name" : "John" }
{ "_id" : ObjectId("5e93178cfd2d90c177b5bcdb"), "id" : 3, "Name" : "Bob" }
{ "_id" : ObjectId("5e931792fd2d90c177b5bcdc"), "id" : 4, "Name" : "Sam" }
Following is the query to fetch specific multiple documents −
> db.demo593.find({id:{$in:[1,3]}});
This will produce the following output −
{ "_id" : ObjectId("5e93177dfd2d90c177b5bcd9"), "id" : 1, "Name" : "Chris" }
{ "_id" : ObjectId("5e93178cfd2d90c177b5bcdb"), "id" : 3, "Name" : "Bob" }
GATE | GATE-CS-2004 | Question 45 - GeeksforGeeks

15 Sep, 2021
Consider the grammar with the following translation rules and E as the start symbol.
E → E1 # T { E.value = E1.value * T.value }
         | T{ E.value = T.value }
T → T1 & F { T.value = T1.value + F.value }
          | F{ T.value = F.value }
F → num { F.value = num.value } 
Compute E.value for the root of the parse tree for the expression: 2 # 3 & 5 # 6 & 4.(A) 200(B) 180(C) 160(D) 40Answer: (C)Explanation: See question 5 of https://www.geeksforgeeks.org/compilers-set-1/
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0056:18 / 58:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LdMTs93sekg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
Java program to Get IP address of the system

The InetAddress class This class represents an Internet Protocol (IP) address. You can get the local IP Address &amp; Hostname of the system using getLocalAddress() method of this class
Live Demo
import java.net.InetAddress;
public class GetIpAddress {
   public static void main(String args[]) throws Exception{
      InetAddress addr = InetAddress.getLocalHost();
      System.out.println("Local HostAddress: "+addr.getHostAddress());
      String hostname = addr.getHostName();
      System.out.println("Local host name: "+hostname);
   }
}
Local HostAddress: 192.168.25.1
Local host name: Tutorialspoint
Convert type of data object in R Programming - type.convert() Function - GeeksforGeeks

26 May, 2020
type.convert() function in R Language is used to compute the data type of a particular data object.It can convert data object to logical, integer, numeric, or factor.
Syntax: type.convert(x)
Parameter:x: It can be a vector matrix or an array
Example 1: Apply type.convert to vector of numbers
# R program to illustrate# type.convert to vector of numbers  # create an example vectorx1 <- c("1", "2", "3", "4", "5", "6", "7")    # Apply type.convert functionx1_convert <- type.convert(x1)       # Class of converted data        class(x1_convert)                                                        
Output:
[1] "integer"

Here in the above code, we can see that before type.convert() function all the numbers are stored in it, but still its a character vector. And after the function it became “Integer”.
Example 2: Type conversion of a vector with both characters and integers.
# R Program to illustrate# conversion of a vector with both characters and integers  # create an example vectorx1 <- c("1", "2", "3", "4", "5", "6", "7")    # Create example datax2 <- c(x1, "AAA")    # Class of example data    class(x2)                          # Apply type.convert functionx2_convert <- type.convert(x2)    # Class of converted data       class(x2_convert)          
Output:
[1] "character"
[1] "factor"

Here, in the above code there were some characters and some integers after using type.convert() function. So, the output comes to be a factor.
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Remove rows with NA in one column of R DataFrame
K-Means Clustering in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
OptionalInt getAsInt() method in Java with examples - GeeksforGeeks

30 Jul, 2019
OptionalInt help us to create an object which may or may not contain a int value. The getAsInt() method returns value If a value is present in OptionalInt object, otherwise throws NoSuchElementException.
Syntax:
public int getAsInt()

Parameters: This method accepts nothing.
Return value: This method returns the value described by this OptionalInt.
Exception: This method throws NoSuchElementException if no value is present
Below programs illustrate getAsInt() method:
Program 1:
// Java program to demonstrate// OptionalInt.getAsInt() method  import java.util.OptionalInt;  public class GFG {      public static void main(String[] args)    {          // Create an OptionalInt instance        OptionalInt opInt = OptionalInt.of(45);          System.out.println("OptionalInt: "                           + opInt.toString());          // Get value in this instance        // using getAsInt()        System.out.println("Value in OptionalInt = "                           + opInt.getAsInt());    }}
OptionalInt: OptionalInt[45]
Value in OptionalInt = 45

Program 2:
// Java program to demonstrate// OptionalInt.getAsInt() method  import java.util.OptionalInt;  public class GFG {      public static void main(String[] args)    {          try {              // Create an OptionalInt instance            OptionalInt opInt = OptionalInt.empty();              System.out.println("OptionalInt: "                               + opInt.toString());              // Get value in this instance            // using getAsInt()            System.out.println("Value in OptionalInt = "                               + opInt.getAsInt());        }        catch (Exception e) {              System.out.println("Exception: " + e);        }    }}
OptionalInt: OptionalInt.empty
Exception: java.util.NoSuchElementException: No value present

References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalInt.html#getAsInt()
Akanksha_Rai
Java - util package
Java-Functions
Java-OptionalInt
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
HashMap containsKey() Method in Java
How to Create Array of Objects in Java?
Convert Double to Integer in Java
Iterating over ArrayLists in Java
Generating random numbers in Java
How to substring value in a MySQL table column?

To substring a MySQL table column, use the in-built SUBSTR() function from MySQL. The syntax is as follows −
select substr(yourColumnName,AnyValue) as anyVariableName from yourTableName;
To understand the function substr(), let us create a table. The query to create a table is as follows −
mysql> create table SubStringDemo
   −> (
   −> UserId varchar(200)
   −> );
Query OK, 0 rows affected (0.55 sec)
Now insert some records in the table. The query to insert records is as follows −
mysql> insert into SubStringDemo values('Bob10015');
Query OK, 1 row affected (0.29 sec)

mysql> insert into SubStringDemo values('Smith0015');
Query OK, 1 row affected (0.22 sec)

mysql> insert into SubStringDemo values('Carol20010');
Query OK, 1 row affected (0.14 sec)
Now you can display all records from the table with the help of select statement. The query is as follows −
mysql> select *from SubStringDemo;
The following is the output −
+------------+
| UserId     |
+------------+
| Bob10015   |
| Smith0015  |
| Carol20010 |
+------------+
3 rows in set (0.00 sec)
The following is the query to substring MySQL table column −
mysql> select substr(UserId,5) as ExtractSubstring from SubStringDemo;
Here is the output that displays the substrings −
+------------------+
| ExtractSubstring |
+------------------+
| 0015             |
| h0015            |
| l20010           |
+------------------+
3 rows in set (0.00 sec)
Deep Learning with Keras - Importing Libraries

We first import the various libraries required by the code in our project.
As typical, we use numpy for array handling and matplotlib for plotting. These libraries are imported in our project using the following import statements
import numpy as np
import matplotlib
import matplotlib.pyplot as plot

As both Tensorflow and Keras keep on revising, if you do not sync their appropriate versions in the project, at runtime you would see plenty of warning errors. As they distract your attention from learning, we shall be suppressing all the warnings in this project. This is done with the following lines of code −
# silent all warnings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='3'
import warnings
warnings.filterwarnings('ignore')
from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
We use Keras libraries to import dataset. We will use the mnist dataset for handwritten digits. We import the required package using the following statement
from keras.datasets import mnist

We will be defining our deep learning neural network using Keras packages. We import the Sequential, Dense, Dropout and Activation packages for defining the network architecture. We use load_model package for saving and retrieving our model. We also use np_utils for a few utilities that we need in our project. These imports are done with the following program statements −
from keras.models import Sequential, load_model
from keras.layers.core import Dense, Dropout, Activation
from keras.utils import np_utils
When you run this code, you will see a message on the console that says that Keras uses TensorFlow at the backend. The screenshot at this stage is shown here −
Now, as we have all the imports required by our project, we will proceed to define the architecture for our Deep Learning network.

    87 Lectures 
     11 hours 

 Abhilash Nelson

    106 Lectures 
     13.5 hours 

 Abhilash Nelson

    28 Lectures 
     4 hours 

 Abhilash Nelson

    58 Lectures 
     8 hours 

 Soumyadeep Dey

    59 Lectures 
     2.5 hours 

 Mike West

    128 Lectures 
     5.5 hours 

 TELCOMA Global
 Print
 Add Notes
 Bookmark this page
Generating n random numbers between a range - JavaScript

We are required to write a JavaScript function that takes in a number, say n, and an array of two numbers that represents a range. The function should return an array of n random elements all lying between the range provided by the second argument.
Following is the code −
const num = 10;
const range = [5, 15];
const randomBetween = (a, b) => {
   return ((Math.random() * (b - a)) + a).toFixed(2);
};
const randomBetweenRange = (num, range) => {
   const res = [];
   for(let i = 0; i < num; ){
      const random = randomBetween(range[0], range[1]);
      if(!res.includes(random)){
         res.push(random);
         i++;
      };
   };
   return res;
};
console.log(randomBetweenRange(num, range));
This will produce the following output in console −
[
   '13.25', '10.31',
   '11.83', '5.25',
   '6.28',  '9.99',
   '6.09',  '7.58',
   '12.64', '8.92'
]
This is just one of the many possible outputs.
Let us run again to get a different random output −
[
   '5.29', '7.95',
   '11.61', '7.83',
   '10.56',  '7.48',
   '12.96',  '6.92',
   '8.98', '9.43'
]
Tryit Editor v3.7

Tryit: HTML image as an object
What are the differences in die() and exit() in PHP?

There is no difference between die and exit, they are the same.
The PHP Manual for exit states −
"This language construct is equivalent to die()."
The PHP Manual for die states −
"This language construct is equivalent to exit()."
However, there is a small difference, i.e the amount of time it takes for the parser to return the token.
How to remove the last digit of a number and execute the remaining digits in JavaScript?

Before the introduction of Bitwise operators, a number is first converted into a string and later on, using string methods, some part of that number is sliced and the remaining part is executed. Here type-conversion i.e a number into a string is necessary. But the introduction of Bitwise or has made the task very easy. When Bitwise or is used there is no necessity of type-conversion and there is no need of using any kind of string methods, reducing the effort and length of the code.
In the following example, a string method called "string.substring()" is used to remove the last digit of a number.
Live Demo
<html>
<body>
<script>
   var str = '2345';
   document.write((str.substring(0, str.length - 1)));
</script>
</body>
</html>
234
But after the advent of Bitwise or, the type conversion and string methods are nowhere in the picture. Bitwise or has made the code very concise.  
Live Demo
<html>
<body>
<script>
   document.write(2345 / 10 | 0)
   document.write("</br>");
   document.write(2345 / 100 | 0)
   document.write("</br>");
   document.write(2345 / 1000 | 0)
</script>
</body>
</html>
234
23
2
How to determine if date is weekend in JavaScript?

As we know the value 0 is for day Sunday and 6 for Saturday. First of all, you need to get day with the help of getDay().
Let’s set a date −
var givenDate=new Date("2020-07-18");
Now, we will get the day −
var currentDay = givenDate.getDay();
Following is the code to determine if date is weekend −
var givenDate=new Date("2020-07-18");
var currentDay = givenDate.getDay();
var dateIsInWeekend = (currentDay === 6) || (currentDay === 0);
if(dateIsInWeekend==true){
   console.log("The given date "+givenDate+" is a Weekend");
} else {
   console.log("The given date " +givenDate+"is a not a Weekend");
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo66.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo66.js
The given date Sat Jul 18 2020 05:30:00 GMT+0530 (India Standard Time) is a Weekend
How to write "Hello, World!" program in JavaScript?

JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script>.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.
Let us take a simple example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a "//-->".
Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write, which writes a string into our HTML document.
<html>
   <body>
      <script>
         <!--
            document.write("Hello World!")
         //-->
      </script>
   </body>
</html>
Sorting a JSON object in JavaScript

Suppose we have an object like this −
const obj = {
   key1: 56,
   key2: 67,
   key3: 23,
   key4: 11,
   key5: 88
};
We are required to write a JavaScript function that takes in this object and returns a sorted array like this −
const arr = [11, 23, 56, 67, 88];
Here, we sorted the object values and placed them in an array.
Therefore, let’s write the code for this function −
The code for this will be −
const obj = {
   key1: 56,
   key2: 67,
   key3: 23,
   key4: 11,
   key5: 88
};
const sortObject = obj => {
   const arr = Object.keys(obj).map(el => {
      return obj[el];
   });
   arr.sort((a, b) => {
      return a - b;
   });
   return arr;
};
console.log(sortObject(obj));
The output in the console will be −
[ 11, 23, 56, 67, 88 ]
How to get the current date and time in Java?

You can get the current date and time in Java in various ways. Following are some of them −
The no-arg constructor of the java.util.Date class returns the Date object representing the current date and time.
Live Demo
import java.util.Date;
public class CreateDate {
   public static void main(String args[]) {      
      Date date = new Date();
      System.out.print(date);
   }
}
Thu Nov 05 20:04:57 IST 2020
The now() method of the LocaldateTime class returns the Date object representing the current time.
Live Demo
import java.time.LocalDate;
import java.time.LocalDateTime;
public class CreateDateTime {
   public static void main(String args[]) {  
      LocalDateTime date = LocalDateTime.now();
      System.out.println("Current Date and Time: "+date);
   }
}
Current Date and Time: 2020-11-05T21:49:11.507
The getInstance() (without arguments) method of the this class returns the Calendar object representing the current date and time.
Live Demo
import java.util.Calendar;
import java.util.Date;
public class CreateDateTime {
   public static void main(String[] args) {
      Calendar obj = Calendar.getInstance();
      Date date = obj.getTime();
      System.out.println("Current Date and time: "+date);
   }
}
Current Date and time: Thu Nov 05 21:46:19 IST 2020
You can also get the current date ant time value using the java.time.Clock class as shown below −
Live Demo
import java.time.Clock;
public class CreateDateTime {
   public static void main(String args[]) {
      Clock obj = Clock.systemUTC();
      System.out.println("Current date time: "+obj.instant());
   }
}
Current date time: 2020-11-05T16:33:06.155Z
how to convert Object array to String array in java

As list.toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter. See the example below.
import java.util.ArrayList;
import java.util.List;
public class Tester {
   public static void main(String[] args) {
      List<String> data = new ArrayList<String>();
      data.add("A");
      data.add("B");
      data.add("C");
      //Object[] objects = data.toArray();
      String[] strObjects = data.toArray(new String[0]);
      for(String obj: strObjects) {
         System.out.println(obj);
      }
   }
}
A
B
C
cat - Unix, Linux Command

cat - Concatenate and print the content of files.
cat [Options] [File]...
Cat command concatenate FILE(s), or standard input, to standard output. With no FILE, or when FILE is -, it reads standard input.
Create two sample files
#sample.txt
This is a sample text file

#sample1.txt
This is a another sample text file

To display content of a file.
$ cat sample.txt
This is a sample text file

To display content of all txt files.
$ cat *.txt
This is a another sample text file
This is a sample text file

To concatenate two files.
$ cat sample.txt sample1.txt > sample2.txt
$ cat sample2.txt
This is a sample text file
This is a another sample text file

To put content of a file in a variable.
$ variable_content = 'cat sample.txt'


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to create a SplitPane in JavaFX?

A SplitPane is a UI component that contains two or more sides with a separator in between. This separator is movable; you can reduce/increase the area of a side using it. You can create a split pane by instantiating the javafx.scene.control.SplitPane class.
The sides of the SplitPane can be arranged either horizontally or vertically. By default, the SpliPane created is horizontal you can change its orientation using the setOrientation() method.
The following Example demonstrates the creation of a SplitPane.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.SplitPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class SplitPaneExample extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating ImageView object1
      Image img1 = new Image(new FileInputStream("D:\\images\\elephant.jpg"));
      ImageView view1 = new ImageView(img1);
      view1.setFitWidth(250);
      view1.setFitHeight(150);
      //Creating ImageView object2
      Image img2 = new Image(new FileInputStream("D:\\images\\boy.jpg"));
      ImageView view2 = new ImageView(img2);
      view2.setFitWidth(250);
      view2.setFitHeight(150);
      //Creating a SplitPane
      SplitPane splitPane = new SplitPane();
      //Creating stack panes holding the ImageView objects
      StackPane stackPane1 = new StackPane(view1);
      StackPane stackPane2 = new StackPane(view2);
      //Adding the stackpanes to the splitpane
      splitPane.getItems().addAll(stackPane1, stackPane2);
      //Setting anchor pane as the layout
      AnchorPane pane = new AnchorPane();
      AnchorPane.setTopAnchor(splitPane, 15.0);
      AnchorPane.setRightAnchor(splitPane, 15.0);
      AnchorPane.setBottomAnchor(splitPane, 15.0);
      AnchorPane.setLeftAnchor(splitPane, 15.0);
      pane.getChildren().addAll(splitPane);
      pane.setStyle("-fx-background-color: BEIGE");
      //Setting the stage
      Scene scene = new Scene(pane, 595, 300);
      stage.setTitle("Split Pane");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Sum of list with stream filter in Java

To get sum of list with stream filter in Java, the code is as follows −
 Live Demo
import java.util.*;
public class Demo
{
   public static void main(String[] args)
   {
      List<Integer> my_list = new ArrayList<Integer>();
      my_list.add(11);
      my_list.add(35);
      my_list.add(56);
      my_list.add(78);
      my_list.add(91);
      System.out.println(sum(my_list));
   }
   public static int sum(List<Integer> my_list)
   {
      System.out.println("In the main function, the sum of list with filter is ");
      return my_list.stream().filter(i -> i > 5).mapToInt(i -> i).sum();
   }
}
In the main function, the sum of list with filter is
271
A class named Demo contains the main function that creates an ArrayList. Elements are added into
the arraylist using the ‘add()’ function. The sum of all the elements of the list can be printed on the screen using the ‘sum’ function. Another function named ‘sum’ is defined that returns the filtered output by mapping the value to an integer.
Why are global and static variables initialized to their default values in C/C++?

Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code. These variables are allocated in .bss file and at the time of loading it allocates the memory by getting the constants alloted to the variables.
The following is an example of global and static variables.
 Live Demo
#include <stdio.h>
int a;
static int b;
int main() {
   int x;
   static int y;
   int z = 28;
   printf("The default value of global variable a : %d", a);
   printf("\nThe default value of global static variable b : %d", b);
   printf("\nThe default value of local variable x : %d", x);
   printf("\nThe default value of local static variable y : %d", y);
   printf("\nThe value of local variable z : %d", z);
   return 0;
}
The default value of global variable a : 0
The default value of global static variable b : 0
The default value of local variable x : 0
The default value of local static variable y : 0
The value of local variable z : 28
In the above program, global variables are declared outside the main() function and one of them is static variable. Three local variables are declared and variable z is initialized too.
int a;
static int b;
....
int x;
static int y;
int z = 28;
Their default values are printed.
printf("The default value of global variable a : %d", a);
printf("\nThe default value of global static variable b : %d", b);
printf("\nThe default value of local variable x : %d", x);
printf("\nThe default value of local static variable y : %d", y);
printf("\nThe value of local variable z : %d", z);
Python – Check if list contain particular digits

02 Feb, 2021
Given a List and some digits, the task is to write a python program to check if the list contains only certain digits.
Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5, 3]
Output : True
Explanation : All elements are made out of 1, 4, 5 or 3 only.

Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5]
Output : False
Explanation : 3 as a digit is required in allowed digits.
Method #1 : Using loop + str() + join()
In this, we iterate for each element in the list and check for each element to have all the digits by joining all digits, converting to string and checking for each in all digit of elements converted to a string.
Python3
# Python3 code to demonstrate working of# Test if list contain particular digits# Using loop + str() + join()  # initializing liststest_list = [435, 133, 113, 451, 134]  # printing original listprint("The original list is : " + str(test_list))  # initializing digitsdigs = [1, 4, 5, 3]  digt_str = ''.join([str(ele) for ele in digs])all_ele = ''.join([str(ele) for ele in test_list])  res = Truefor ele in all_ele:      # checking for all digits in element string    for el in ele:        if el not in digt_str:            res = False            break  # printing resultprint("Are all elements made from required digits? : " + str(res))
Output:
The original list is : [435, 133, 113, 451, 134]
Are all elements made from required digits? : True
Method #2 : Using any() + list comprehension
In this, we flag off if any digit not from digit string using any() and not operation. One liner alternative extended using iteration in a list comprehension.
Python3
# Python3 code to demonstrate working of# Test if list contain particular digits# Using any() + list comprehension  # initializing liststest_list = [435, 133, 113, 451, 134]  # printing original listprint("The original list is : " + str(test_list))  # initializing digitsdigs = [1, 4, 5, 3]  digt_str = ''.join([str(ele) for ele in digs])all_ele = ''.join([str(ele) for ele in test_list])  # any() checks if any element is not part of digitres = not any(ele not in digt_str for ele in all_ele)  # printing resultprint("Are all elements made from required digits? : " + str(res))
Output:
The original list is : [435, 133, 113, 451, 134]
Are all elements made from required digits? : True
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures and Algorithms | Set 38

21 Feb, 2019
This topic contains basic questions of Algorithm which can be helpful for GATE CS Preparation. So, it is recommended to solve each of these questions if you are preparing for GATE.
Ques-1: Which one of the following correctly determines the solution of the recurrence relation given below with T(1) = 1 ?
T(n)= 2T(n/4) + n1/2 
(A) O(n2)(B) O(n)(C) O(n1/2 log n)(D) O(log n)
Explanation:According Master Theorem,
T(n)= 2T(n/4) + n1/2 
Applying Masters Theorem,Here,
a = 2, b = 4, K = 1/2, and p = 0 

So, bK = 41/2 = 2 
Thus, a = bK and (p > -1) 
So, the formula is,
T(n)= O(nlogba log(P+1)n)
Therefore,
T(n) = O(nlog 42 log(0 + 1)n) = O(n1/2 log n)
So, option (C) is correct.
Ques-2: For merging two unsorted list of size p and q into sorted list of size (p + q). The time complexity in terms of number of comparisons is:
(A) O(log p + log q)(B) O(p log p) + q log q)(C) O(p + q)(D) None
Explanation:For sorting the array of size p individually it takes O(p log p) and the array of size q takes O(q log q) time, then merging will take O(m + n) time.Therefore, total number of comparisons
= O(p log p) + O(q log q) + p + q
= O(p log p) + O(q log q) 
So, option (B) is correct.
Ques-3: Which of the following sorting algorithms has the highest best case time complexity using array data structure ?
(A) Heap sort(B) Insertion sort(C) Bubble sort(D) Selection sort
Explanation:Best case time complexity of Heap sort is O(n log n)Best case time complexity of Insertion sort is O(n)Best case time complexity of Bubble sort is O(n)Best case time complexity of selection sort is O(n2).So, option (D) is correct.
Ques-4: Which of the following input gives the best case time for selection sort ?
(A) 1 2 3 4 5 6 7 8 9(B) 2 3 1 5 9 7 8 6(C) 9 8 7 6 5 4 3 2 1(D) All of the above take same amount of time.
Explanation:Selection sort in worst case and best case takes same time.So, option (D) is correct.
Ques-5: What is the time complexity of recursive function given below:
T(n)= 4T(n/2) + n2 
(A) O(n2)(B) O(n)(C) O(n2 log n)(D) O(n log n)
Explanation:According Master Theorem,Here,
a = 4, b = 2, k = 2, p = 0 

So, bk = 4 i.e., a = bk 
Therefore, the formula is
T(n) = O(nlog ba log(P+1)n)

So, T(n)= O(nlog 24 log(0 + 1)n) = O(n2 log n)
So, option (C) is correct.
GATE-CS-DS-&-Algo
MCQ
Algorithms Quiz
GATE
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
itertools.combinations() module in Python to print all possible combinations

23 Nov, 2020
Given an array of size n, generate and print all possible combinations of r elements in array.
Examples:
Input : arr[] = [1, 2, 3, 4],  
            r = 2
Output : [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve this problem in python using itertools.combinations() module.
It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
itertools.combinations(iterable, r) :It return r-length tuples in sorted order with no repeated elements. For Example, combinations(‘ABCD’, 2) ==> [AB, AC, AD, BC, BD, CD].
itertools.combinations_with_replacement(iterable, r) :It return r-length tuples in sorted order with repeated elements. For Example, combinations_with_replacement(‘ABCD’, 2) ==> [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD].
# Function which returns subset or r length from nfrom itertools import combinations  def rSubset(arr, r):      # return list of all subsets of length r    # to deal with duplicate subsets use     # set(list(combinations(arr, r)))    return list(combinations(arr, r))  # Driver Functionif __name__ == "__main__":    arr = [1, 2, 3, 4]    r = 2    print (rSubset(arr, r))
Output:
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python-Library
Combinatorial
Python
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read integers from console in Java

To read integers from console, use Scanner class.
Scanner myInput = new Scanner( System.in );
Allow a use to add an integer using the nextInt() method.
System.out.print( "Enter first integer: " );
int a = myInput.nextInt();
In the same way, take another input in a new variable.
System.out.print( "Enter second integer: " );
Int b = myInput.nextInt();
Let us see the complete example.
import java.util.Scanner;
public class Demo {
   public static void main( String args[] ) {
      Scanner myInput = new Scanner( System.in );
      int a;
      int b;
      int sum;
      System.out.print( "Enter first integer: " );
      a = myInput.nextInt();
      System.out.print( "Enter second integer: " );
      b = myInput.nextInt();
      sum = a + b;
      System.out.printf( "Sum = %d\n", sum );
   }
}
We added the following two integer values from the console.
5
10
After adding the values and running the program, the following output can be seen.
Enter first integer: 5
Enter second integer: 10
Sum = 15
Try-Catch-Finally in C#

C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
C# exception handling is performed using the following keywords −
try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
The following is an example showing how to handle exceptions in C# −
using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;

      DivNumbers() {
         result = 0;
      }

      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }

      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}
Above, we have set the values in a try, and then caught exceptions in the catch. Finally is also set to show the result −
try {
   result = num1 / num2;
} catch (DivideByZeroException e) {
   Console.WriteLine("Exception caught: {0}", e);
} finally {
   Console.WriteLine("Result: {0}", result);
}
Count frequencies of all elements in array in Python using collections module

As python allows duplicate elements in a list we can have one element present multiple Times. The frequency of elements in a list indicates how many times an element occurs in a list. In this article we use the Counter function of the collections module to find out the frequency of each item in a list.
Syntax: Counter(list)
Where list is an iterable in python
The below code uses the Counter() to keep track of frequency and items() to iterate over each item in the result of counter function for printing in a formatted manner.
from collections import Counter
list = ['Mon', 'Tue', 'Wed', 'Mon','Mon','Tue']

# Finding count of each element
list_freq= (Counter(list))

#Printing result of counter
print(list_freq)

# Printing it using loop
for key, value in list_freq.items():
   print(key, " has count ", value)
Running the above code gives us the following result −
Counter({'Mon': 3, 'Tue': 2, 'Wed': 1})
Mon has count 3
Tue has count 2
Wed has count 1