code-rag-bench/online-tutorials huggingface dataset:
How can we call the invokeLater() method in Java?


An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities.invokeLater() method works like SwingUtilities.invokeAndWait() except that it puts the request on the event queue and returns immediately. An invokeLater() method does not wait for the block of code inside the Runnable referred by a target to execute.
public static void invokeLater(Runnable target)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InvokeLaterTest extends Object {
   private static void print(String msg) {
      String name = Thread.currentThread().getName();
      System.out.println(name + ": " + msg);
   }
   public static void main(String[] args) {
      final JLabel label= new JLabel("Initial text");
      JPanel panel = new JPanel(new FlowLayout());
      panel.add(label);
      JFrame f = new JFrame("InvokeLater Test");
      f.setContentPane(panel);
      f.setSize(400, 300);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
      try {
         print("sleeping for 5 seconds");
         Thread.sleep(5000);
      } catch(InterruptedException ie) {
         print("interrupted while sleeping");
      }
      print("creating the code block for an event thread");
      Runnable setTextRun = new Runnable() {
         public void run() {
            try {
               Thread.sleep(100);
               print("about to do setText()");
               label.setText("New text");
            } catch(Exception e) {
               e.printStackTrace();
            }
         }
      };
      print("about to call invokeLater()");
      SwingUtilities.invokeLater(setTextRun);
      print("back from invokeLater()");
   }
}
main: sleeping for 5 seconds
main: creating the code block for an event thread 
main: about to call invokeLater() 
main: back from invokeLater() 
AWT-EventQueue-0: about to do setText()
Fromordinal() Function Of Datetime.date Class In Python

29 Aug, 2021
The fromordinal() function is used to return the Gregorian date corresponding to a specified Gregorian ordinal. This is the opposite of the toordinal() function that is used to convert a Gregorian date to a Gregorian ordinal. When a negative ordinal value or an ordinal beyond the value returned by the date.max.toordinal() is passed to the parameter of the toordinal() function, this function raises a ValueError.
Syntax: @classmethod  fromordinal(ordinal)
Parameters: This function accepts a parameter which is illustrated below:
ordinal: This is the specified Gregorian ordinal for which the Gregorian date is going to be found.
Return values: This function returns the Gregorian date corresponding to a specified Gregorian ordinal.
Example 1:  From the specific day of the Gregorian calendar.
Python3
# Python3 code for getting# the Gregorian date corresponding# to a given Gregorian ordinal. # Importing datetime moduleimport datetime # Specifying a Gregorian ordinalordinal = 123456; # Calling the fromordinal() function# over the specified Gregorian ordinaldate = datetime.date.fromordinal(ordinal); # Printing the Gregorian dateprint("The Gregorian date for the Gregorian\ordinal %d is: %s"%(ordinal, date));
Output:
The Gregorian date for the Gregorian ordinal 123456 is: 0339-01-05
Example 2: From first day of the Gregorian calendar.
Python3
# Python3 code for getting# the Gregorian date corresponding# to a given Gregorian ordinal. # Importing datetime moduleimport datetime # Calling the fromordinal() function over# the 1st day of Gregorian calendar as its parameterdate = datetime.date.fromordinal(1); # Printing the Gregorian date for the 1st date# of Gregorian calendarprint("Gregorian Date for the 1st day \of Gregorian calendar: %s"%date);
Output:
Gregorian Date for the 1st day of Gregorian calendar: 0001-01-01
simmytarika5
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
How to send HTTP response code in PHP?

26 Mar, 2019
HTTP Response code: There are three approaches to accomplish the above requirement, depending on the version.
For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one.
header("HTTP/1.1 200 OK");
Example:
$sapitype = php_sapi_name();if (substr($sapitype, 0, 3) == 'cgi')    header("Status: 404 Not Found");else    header("HTTP/1.1 404 Not Found");
For PHP versions 4.3: There are obviously a few problems when using first method. The biggest one is that it is partly parsed by PHP and is poorly documented. Since the version 4.3, the header() function has an additional 3rd argument through which we can set the response code. but to use the first argument should be a non-empty string.
header(':', true, 400);
header(‘X_PHP_Response_Code: 400', true, 400);

The second one is recommended. The header field name in this variant is not standardized and can be modified.
For PHP versions 5.4: This versions uses http_response_code() function to makes things easier.
http_response_code(400);
Example: This example uses http_response_code() function to send HTTP response code.
<?php  error_reporting(E_ERROR | E_PARSE);  // Initialize a variable into domain name$domain1 = 'https://contribute.geeksforgeeks.org';  // Function to get HTTP response code function get_http_response_code($domain1) {    $headers = get_headers($domain1);    return substr($headers[0], 9, 3);}  // Function call $get_http_response_code = get_http_response_code($domain1);  // Display the HTTP response codeecho $get_http_response_code;  // Check HTTP response code is 200 or notif ( $get_http_response_code == 200 )    echo "<br>HTTP request successfully";else    echo "<br>HTTP request not successfully!";      ?>
Output:
200
HTTP request successfully
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get element at specific position in List in C++

01 Dec, 2020
The list doesn’t have random access operator [] to access elements by indices, because std::list internally store elements in a doubly-linked list. So, to access an element at any Kth location, the idea is to iterate one by one from beginning to Kth element. Instead of iterating for K times. For this, an STL std::advance() function is used to find it in linear time.
Syntax:
advance(InputIterator& it, Distance N)
Parameters: This function accepts two parameters i.e., iterator that is to be traversed through the list and the position to where it has to be moved. The position can be negative for random access and bidirectional iterators.
Return Type: This function has no return type.
Below is the C++ implementation of the above approach:
C++
// C++ program to access  Kth element// of the list using advanced#include <bits/stdc++.h>using namespace std;  // Driver Codeint main(){    // Create list with initial value 100    list<int> li(5, 100);      // Insert 20 and 30 to the list    li.push_back(20);    li.push_back(30);      // Elements of list are    // 100, 100, 100, 100, 100, 20, 30      // Initialize iterator to list    list<int>::iterator it = li.begin();      // Move the iterator by 5 elements    advance(it, 5);      // Print the element at the it    cout << *it;      return 0;}
20

cpp-list
cpp-list-functions
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Difference between TreeMap and TreeSet in Java

28 Jan, 2021
TreeSet is mainly an implementation of SortedSet in java where duplication is not allowed and objects are stored in sorted and ascending order.
Some important features of the TreeSet are:
In TreeSet duplicate values are not allowed because it implements the SortedSet interface.
Objects in a TreeSet are stored in ascending order.
In TreeSet the insertion order of elements does not maintain.
TreeMap is an implementation of Map Interface. TreeMap is also an implementation of NavigableMap along with AbstractMap class.
Some important features of the TreeMap are:
In TreeMap null keys(like Map) are not allowed and thus a NullPointerException is thrown (Multiple null values may be associated with different keys).
TreeMap does not support the Entry.setValue method.
Below is the illustration of TreeSet and TreeMap in Java:
Example 1:
Java
// Illustration of TreeMap and TreeSet in Javaimport java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {        TreeSet<Integer> set = new TreeSet<>();        set.add(3);        set.add(4);        set.add(3);        set.add(5);          TreeMap<Integer, Integer> tm = new TreeMap<>();        tm.put(2, 4);        tm.put(3, 5);        tm.put(4, 5);        tm.put(2, 3);        System.out.println(set);        System.out.println(tm);    }}
[3, 4, 5]
{2=3, 3=5, 4=5}
Example 2:
Java
// Illustration of TreeMap and TreeSet in Javaimport java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {        TreeSet<String> l = new TreeSet<>();        l.add("geeks");        l.add("FOR");        l.add("geeks");        l.add("tutorial");          TreeMap<Integer, String> l1 = new TreeMap<>();          l1.put(1, "geeks");        l1.put(2, "FOR");        l1.put(3, "geeks");        l1.put(4, "tutorial");        System.out.println(l);        System.out.println(l1);    }}
[FOR, geeks, tutorial]
{1=geeks, 2=FOR, 3=geeks, 4=tutorial}
TreeSet
TreeMap
Java-Collections
java-TreeMap
java-treeset
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Differences between IPv4 and IPv6
Arrays in Java
Reverse a string in Java
Split() String method in Java with examples
Queue Interface In Java
For-each loop in Java
How to create an ordered list with list items numbered with lowercase roman numbers in HTML?

To create ordered list in HTML, use the <ol> tag. Ordered list starts with the <ol> tag. The list item starts with the <li> tag and will be marked as numbers, lowercase letters uppercase letters, roman letters, etc. The default numbers for list items.
For creating an ordered list with lowercase roman numbers, use the <ol> tag attribute type. This attribute will assign a lowercase roman number i.e. <ol type = “i”> to create ordered list numbered with lowercase roman numbers.
You can try to run the following code to create an ordered list with list items numbered with lowercase roman numbers in HTML −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>World Cup Teams</title>
   </head>
   <body>
      <h1>List of teams for World Cup</h1>
      <ol type = "i">
         <li>India</li>
         <li>Australia</li>
         <li>South Africa</li>
         <li>New Zealand</li>
         <li>Pakistan</li>
         <li>Srilanka</li>
         <li>West Indies</li>
         <li>Bangladesh</li>
      </ol>
   </body>
</html>
How to write an empty function in Python – pass statement?

07 Jun, 2022
In C/C++ and Java, we can write empty function as following
// An empty function in C/C++/Java
void fun() {  }

In Python, if we write something like following in Python, it would produce compiler error.
# Incorrect empty function in Pythondef fun(): 
Output :
IndentationError: expected an indented block
In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement.
# Correct way of writing empty function # in Pythondef fun():     pass
We can use pass in empty while statement also.
# Empty loop in Pythonmutex = Truewhile (mutex == True) :    pass
We can use pass in empty if else statements.
# Empty in if/else in Pythonmutex = Trueif (mutex == True) :    passelse :    print("False")
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Webcam QR code scanner using OpenCV

02 Mar, 2022
In this article, we’re going to see how to perform QR code scanning using a webcam. 
Webcam QR CODE Scanner
Before starting, You need to know how this process is going to work. Firstly you need to open your webcam, and you’ve to run your python program to make it ready to scan the QR code. You can take the Qr code picture on your mobile and show the picture in front of your webcam. It correctly identifies the QR code that presents on your screen. And this program redirects you to a link hidden in the QR code.
Requirements:
pip install OpenCV
pip install webbrowser ( built in )
Step 1: For creating the QR code scanner you need to install the OpenCV library on your command prompt. First, you need to import the cv2 and browser library.Cv2 is used for scanning the QR code through a webcam and a web browser is used to take the URL into the browser.
Python3
import cv2import webbrowser
Step 2: Next, we need to start the camera for capturing the QR code. For that declare a variable called a cap and in this variable pass the instance cv2.VideoCapture(0). The next process is we need to create a variable called detector and in this variable call the object cv2.QRCodeDetector(). This object is a very helpful one for capturing QR codes in real-time. 
Python3
cap = cv2.VideoCapture(0)# initialize the cv2 QRCode detectordetector = cv2.QRCodeDetector()
Step 3: This step is very important you need to create a while loop and in this loop create a variable called an img and this loop will read your webcam screen continuously until this loop breaks
Python3
while True:    _, img = cap.read()
Step 4:
Next, create a variable called data, and this variable is to be used to decode the QR code, and if any data is present in the QR code image it will break the loop and it open the link in your browser. So this is the condition that I inserted here.
Python3
# detect and decode   data, bbox, _ = detector.detectAndDecode(img)   # check if there is a QRCode in the image   if data:       a=data       break
Step 5:
Finally, call the object cv2.imshow this will produce the output and you’ve to assign the key to break the loop. Here I assigned the key that is called q, when we press the q it will stop the video streaming.
And then you’ve to create the variable, in this variable you need to call the object webbrowser.open( pass the variable an in this object )
Python3
cv2.imshow("QRCODEscanner", img)       if cv2.waitKey(1) == ord("q"):        break b=webbrowser.open(str(a))cap.release()cv2.destroyAllWindows()
 Output :
ddeevviissaavviittaa
OpenCV
Misc
Python
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages and Disadvantages of OOP
Introduction to Electronic Mail
Hypervisor
Cloud Computing
Analog to Digital Conversion
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Reshape the Matrix in C++

In different platform there is very useful function called 'reshape', that function is used to reshape a matrix into a new one with different size but data will be same. So, if we have a matrix and two values r and c for the row number and column number of the wanted reshaped matrix, respectively.
So, if the input is like [[5,10],[15,20]], row = 1 and col = 4, then the output will be [[5, 10, 15, 20]]
To solve this, we will follow these steps−
Define an array temp
Define an array temp
Define one 2D array res of size (r x c)
Define one 2D array res of size (r x c)
count := 0
count := 0
for initialize i := 0, when i < size of nums, update (increase i by 1), do −for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −insert nums[i, j] at the end of temp
for initialize i := 0, when i < size of nums, update (increase i by 1), do −
for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −insert nums[i, j] at the end of temp
for initialize j := 0, when j < size of nums[0], update (increase j by 1), do −
insert nums[i, j] at the end of temp
insert nums[i, j] at the end of temp
if r * c is not equal to size of nums, then −return nums
if r * c is not equal to size of nums, then −
return nums
return nums
for initialize i := 0, when i < r, update (increase i by 1), do −for initialize j := 0, when j < c, update (increase j by 1), do −count = count + 1res[i, j] := temp[count]
for initialize i := 0, when i < r, update (increase i by 1), do −
for initialize j := 0, when j < c, update (increase j by 1), do −count = count + 1res[i, j] := temp[count]
for initialize j := 0, when j < c, update (increase j by 1), do −
count = count + 1
count = count + 1
res[i, j] := temp[count]
res[i, j] := temp[count]
return res
return res
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto>> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
      vector<int> temp;
      vector<vector<int> > res(r, vector<int>(c));
      int count = 0;
      for (int i = 0; i < nums.size(); i++) {
         for (int j = 0; j < nums[0].size(); j++) {
            temp.push_back(nums[i][j]);
         }
      }
      if (r * c != nums.size() * nums[0].size())
         return nums;
      for (int i = 0; i < r; i++) {
         for (int j = 0; j < c; j++) {
            res[i][j] = temp[count++];
         }
      }
      return res;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{5,10},{15,20}};
   print_vector(ob.matrixReshape(v, 1, 4));
}
{{5,10},{15,20}}, 1, 4
[[5, 10, 15, 20, ],]
LocalDateTime ofInstant() method in Java with Examples

17 May, 2020
ofInstant(Instant instant, ZoneId zone) method of LocalDateTime class in Java is used to create an instance of LocalDateTime using an Instant and zone ID. These two parameters are passed to the method and method returns LocalDateTime on the basis of these two parameters. The calculation of the LocalDateTime follows the following step.
The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.Finally, the local date-time is calculated using the instant and the obtained offset.
The zone Id and instant are used to obtain the offset from UTC/Greenwich as there can be only one valid offset for each instance.
Finally, the local date-time is calculated using the instant and the obtained offset.
Syntax:
public static LocalDateTime 
       ofInstant(Instant instant,
                 ZoneId zone)

Parameters: The method accepts two parameters:
instant – It is of Instant type and represents the instant passed to create localdatetime.
zone – It is of ZoneId type and represents the time-zone used for creating the offset.
Return Value: This method returns the localdate-time.
Exceptions: This method throws DateTimeException if the result exceeds the supported range.
Below programs illustrate the ofInstant(Instant instant, ZoneId zone) method in Java:
Program 1:
// Java program to demonstrate// LocalDateTime.ofInstant(// Instant instant, ZoneId zone) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {        // Create LocalDateTime object        LocalDateTime localdatetime            = LocalDateTime.ofInstant(                Instant.now(),                ZoneId.systemDefault());          // Print full date        System.out.println(            "Date: " + localdatetime);    }}
Date: 2020-05-13T12:40:38.087

Program 2:
// Java program to demonstrate// LocalDateTime.ofInstant(// Instant instant, ZoneId zone) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {        // Create LocalDateTime object        LocalDateTime localdatetime            = LocalDateTime.ofInstant(                Instant.now(),                ZoneId.systemDefault());          // Print year only        System.out.println(            "Year: " + localdatetime.getYear());    }}
Year: 2020

References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#ofInstant(java.time.Instant, java.time.ZoneId)
Java-Functions
Java-LocalDateTime
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – color_matrix() function in Wand

08 May, 2020
color_matrix() method allows you to recalculate color values by applying a matrix transform. A matrix can be up to a 6×6 grid where each column maps to a color channel to reference, and each row represents a color channel to effect.red, green, blue, n/a, alpha, and a constant (a.k.a offset) describe the corresponding rows and columns.
Syntax :
wand.image.color_matrix(matrix)

Parameters :
Source Image :
Example 1:
# Import Image from wand.image modulefrom wand.image import Image  # Read image using Image functionwith Image(filename ="koala.jpeg") as img:    matrix = [[0, 0, 1],              [0, 1, 0],              [1, 0, 0]]    # Recalculate color using color_matrix() method    img.color_matrix(matrix)    img.save(filename ="cm_koala.jpeg")
Output:
Example 2:
# Import Image from wand.image modulefrom wand.image import Image  # Read image using Image functionwith Image(filename ="koala.jpeg") as img:    matrix = [[0, 1, 0],              [1, 0, 0],              [0, 0, 1]]    # Recalculate color using color_matrix() method    img.color_matrix(matrix)    img.save(filename ="cm_koala2.jpeg")
Output:
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Python – Generate random number except K in list

06 Mar, 2020
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed.
Method #1 : Using choice() + list comprehensionThe combination of above functions can be used to perform this task. In this, we first filter out the numbers except K using list comprehension and then feed that list to choice() for random number generation.
# Python3 code to demonstrate # Generate random number except K in list# using choice() + list comprehensionimport random  # Initializing list test_list = [4, 7, 8, 4, 6, 10]  # printing original listprint("The original list is : " + str(test_list))  # Initializing K K = 4  # Generate random number except K in list# using choice() + list comprehensionres = random.choice([ele for ele in test_list if ele != K])  # printing result print ("The random number except K is : " + str(res))
The original list is : [4, 7, 8, 4, 6, 10]
The random number except K is : 8

 
Method #2 : Using filter() + lambda + choice()This is yet another way in which this task can be performed. In this, we perform method of creating new list using filter and lambda.
# Python3 code to demonstrate # Generate random number except K in list# using choice() + filter() + lambdaimport random  # Initializing list test_list = [4, 7, 8, 4, 6, 10]  # printing original listprint("The original list is : " + str(test_list))  # Initializing K K = 4  # Generate random number except K in list# using choice() + filter() + lambdares = random.choice(list(filter(lambda ele: ele != K, test_list)))  # printing result print ("The random number except K is : " + str(res))
The original list is : [4, 7, 8, 4, 6, 10]
The random number except K is : 8

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
numpy.linalg.det() Method in Python

29 Jul, 2021
In NumPy, we can compute the determinant of the given square array with the help of numpy.linalg.det(). It will take the given square array as a parameter and return the determinant of that.
Syntax: numpy.linalg.det() Parameter: An square array. Return: The determinant of that square array.
Example 1:
Python
import numpy as npfrom numpy import linalg as LA  array1 = np.array([[1, 2], [3, 4]]) # Original 2-d arrayprint(array1) # Determinant of the said 2-D arrayprint(np.linalg.det(array1))
Output:
[[1 2]
 [3 4]]
-2.0000000000000004
Example 2:
Python
import numpy as npfrom numpy import linalg as LA  array1 = np.array([[1, 2, 3], [3, 4, 1], [3, 2, 1]]) # Original 2-d arrayprint(array1) # Determinant of the said 2-D arrayprint(np.linalg.det(array1))
Output:
[[1 2 3]
 [3 4 1]
 [3 2 1]]
-15.999999999999998
surinderdawra388
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
TypeScript - Multidimensional Arrays

An array element can reference another array for its value. Such arrays are called as multidimensional arrays. TypeScript supports the concept of multi-dimensional arrays. The simplest form of a multi-dimensional array is a two-dimensional array.
var arr_name:datatype[][]=[ [val1,val2,val3],[v1,v2,v3] ]

var arr_name:datatype[initial_array_index][referenced_array_index] = [ [val1,val2,val 3],
   [v1,v2,v3] ]

The following example better explains this concept.
var multi:number[][] = [[1,2,3],[23,24,25]]  
console.log(multi[0][0]) 
console.log(multi[0][1]) 
console.log(multi[0][2]) 
console.log(multi[1][0]) 
console.log(multi[1][1]) 
console.log(multi[1][2])

The above example initially declares an array with 2 elements. Each of these elements refer to another array having 3 elements. The pictorial representation of the above array is given below.
While referring to an array element here, the subscript of the initial array element must be followed by the subscript of the referenced array element. This is illustrated in the code.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var multi = [[1, 2, 3], [23, 24, 25]];
console.log(multi[0][0]);
console.log(multi[0][1]);
console.log(multi[0][2]);
console.log(multi[1][0]);
console.log(multi[1][1]);
console.log(multi[1][2]);

The output of the above code is as follows −
Node.js URL.pathToFileURL API

14 Oct, 2021
This URL.pathToFileURL function converts the path to a file and ensures that the URL control characters (/, \, : ) are correctly appended/adjusted when converting the given path into a File URL.
Syntax:
url.pathToFileURL(path)
Parameters: This function accepts single parameter path which holds the path to convert a file URL.
Return Value: This function returns the file URL object.
Below programs illustrates the use of URL.-pathToFileURL Method:
Example 1:
// Node program to demonstrate the  // URL.pathToFileURL API as Setter   // Importing the module 'url' var url = require('url');  // Some random path from systemconst path = 'D:\GeeksForGeeks'  // Converting the path to properly encoded fileconsole.log(url.pathToFileURL(path)) 
Output:
 
URL {
  href: 'file:///D:/GeeksForGeeks',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/D:/GeeksForGeeks',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}

Example 2:
// Node program to demonstrate the  // URL.pathToFileURL API as Setter   // Importing the module 'url' var url = require('url');    // Some random path from systemconst path = 'D:\NodeJS\node_modules\npm'  // Converting the path to properly encoded fileconsole.log(url.pathToFileURL(path)) 
Output:
URL {
  href: 'file:///D:/NodeJS%0Aode_modules%0Apm',
  origin: 'null',
  protocol: 'file:',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/D:/NodeJS%0Aode_modules%0Apm',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}

Note: The above program will compile and run by using the node app.js command.
Reference https://nodejs.org/api/url.html#url_url_pathtofileurl_path
Node-URL
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary items() method

04 Dec, 2020
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair.In Python Dictionary, items() method is used to return the list with all dictionary keys with values. 
Syntax: dictionary.items()Parameters: This method takes no parameters.Returns: A view object that displays a list of a given dictionary’s (key, value) tuple pair.
Example #1:  
Python3
# Python program to show working# of items() method in Dictionary  # Dictionary with three items Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' }  print("Dictionary items:")  # Printing all the items of the Dictionaryprint(Dictionary1.items())
Output:  
Dictionary items:
dict_items([('A', 'Geeks'), ('B', 4), ('C', 'Geeks')])


Order of these items in the list may not always be same.   Example #2: To show working of items() after modification of Dictionary.  
Python3
# Python program to show working# of items() method in Dictionary  # Dictionary with three items Dictionary1 = { 'A': 'Geeks', 'B': 4, 'C': 'Geeks' }  print("Original Dictionary items:")  items = Dictionary1.items()  # Printing all the items of the Dictionaryprint(items)  # Delete an item from dictionarydel[Dictionary1['C']]print('Updated Dictionary:')print(items)
Output:  
Original Dictionary items:
dict_items([('A', 'Geeks'), ('C', 'Geeks'), ('B', 4)])
Updated Dictionary:
dict_items([('A', 'Geeks'), ('B', 4)])


If the Dictionary is updated anytime, the changes are reflected in the view object automatically. 
001amankumar
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to clear all options in a dropdown box?

27 Sep, 2019
Clearing the entire dropdown list is pretty easy, all we have to do is to create a button, which calls a function that performs the deletion.Let’s look at the syntax of the deletion part:
document.getElementById("idofdropdownlist").innerHTML = "";
Here, it gets all the elements present in the given Id and clears then by assigning all the objects null, if not assigned to null, still object remains.Approach 1: Check out the code:
<!DOCTYPE html><html>  <body>      <p>Which character is your favorite guardian?</p>              <select id="guardian">            <!--dropdown list with id=guardian-->            <option>Guardians</option>            <option>Quill</option>            <option>Gamora</option>            <option>Drax</option>            <option>rocket</option>            <option>groot</option>            <option>mantis</option>        </select>          <input type="button" onclick="myFunction()"               value="Only IronMan clear them all" />        <!––Button which avokes myFuction()-->          <script>            function myFunction() {                //clears all the guardians with the specified id                document.getElementById("guardian").innerHTML =                    null;            }        </script></body>  </html>
Output:
Approach 2:This process not only removes the option but also removes the dropdown box too.Check out the code:
<html>  <body>      <p>Which character is your favorite guardian?</p>      <select id="guardian">        <!--dropdown list with id=guardian-->        <option>Guardians</option>        <option>Quill</option>        <option>Gamora</option>        <option>Drax</option>        <option>rocket</option>        <option>groot</option>        <option>mantis</option>    </select>      <input type="button"            onclick="myFunction()"            value="Only IronMan clear them all">    <!––Button which avokes myFuction()-->      <script>        function myFunction() {            //process the options in a loop and removes them            document.querySelectorAll(              '#guardian').forEach(guardian => guardian.remove())                //here, guardian inside the for is a variable not id.        }    </script></body>  </html>
Output:
These methods work on all browsers.
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
int Keyword in C#

22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. int is a keyword that is used to declare a variable which can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of System.Int32.
Syntax:
int variable_name = value;
Int keyword occupies 4 bytes (32 bits) space in the memory.
Example:
Input: num: -245

Output: num: -245
        Size of an int variable: 4

Input: num = 7923645

Output: Type of num: System.Int32
        num: 7923645
        Size of a int variable: 4

Example 1:
// C# program for int keywordusing System;using System.Text;  class geeks {      static void Main(string[] args)    {        // variable declaration        int num = -245;          // to print value        Console.WriteLine("num: " + num);          // to print size        Console.WriteLine("Size of a int variable: " + sizeof(int));    }}
Output:
num: -245
Size of a int variable: 4

Example 2:
// C# program for int keywordusing System;using System.Text;  namespace Test {  class geeks {      static void Main(string[] args)    {        // variable declaration        int num = 7923645;          // to print type of variable        Console.WriteLine("Type of num: " + num.GetType());          // to print value        Console.WriteLine("num: " + num);          // to print size        Console.WriteLine("Size of a int variable: " + sizeof(int));          // to print minimum & maximum value of int        Console.WriteLine("Min value of int: " + int.MinValue);        Console.WriteLine("Max value of int: " + int.MaxValue);          // hit ENTER to exit        Console.ReadLine();    }}}
Output:
Type of num: System.Int32
num: 7923645
Size of a int variable: 4
Min value of int: -2147483648
Max value of int: 2147483647

Example 3:
// C# program for int keywordusing System;using System.Text;  class geeks {      static void Main(string[] args)    {          // variable declaration        int num1 = 2147483650;          // to print value        Console.WriteLine("num1: " + num1);          // variable declaration        int num = 792.53;          // to print value        Console.WriteLine("num: " + num);    }}
Error: When we input wrong integer and also input number beyond the range
Constant value `2147483650′ cannot be converted to a `int’Cannot implicitly convert type `double’ to `int’
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
PostgreSQL – DISTINCT ON expression

07 Oct, 2021
PostgreSQL also provides on an expression as DISTINCT ON that is used with the SELECT statement to remove duplicates from a query set result just like the DISTINCT clause.In addition to that it also keeps the “first row” of each row of duplicates in the query set result. 
 
Syntax: SELECT DISTINCT ON (column_1) column_alias, column_2 FROM table_name ORDER BY column_1, column_2;
 
As the order of rows returned from the SELECT statement is unpredictable which means the “first row” of each group of the duplicate is also unpredictable. It is good practice to use the ORDER BY clause with the DISTINCT ON(expression) to make the result set in the desired order. 
Note: The DISTINCT ON expression must always match the leftmost expression in the ORDER BY clause. 
Now, let’s look into a few examples for better understanding. For the sake of example, we will create a sample database as explained below: 
Create a database(say, Favourite_colours) using the commands shown below:  
CREATE DATABASE Favourite_colours;
Now add a table(say, my_table) with columns(say, id, colour_1 and colour_2) to the database using the command below: 
 
CREATE TABLE my_table(
    id serial NOT NULL PRIMARY KEY,
    colour_1 VARCHAR,
    colour_2 VARCHAR
);
Now insert some data in the table that we just added to our database using the command below:  
INSERT INTO my_table(colour_1, colour_2)
VALUES
    ('red', 'red'),
    ('red', 'red'),
    ('red', NULL),
    (NULL, 'red'),
    ('red', 'green'),
    ('red', 'blue'),
    ('green', 'red'),
    ('green', 'blue'),
    ('green', 'green'),
    ('blue', 'red'),
    ('blue', 'green'),
    ('blue', 'blue');
Now check if everything is as intended by making a query as below:  
SELECT
    id,
    colour_1,
    colour_2
FROM
    my_table;
If everything is as intended, the output will be like as shown below:  
Since, our database is good to go, we move onto the implementation of the SELECT DISTINCT ON expression. 
Example 1:  
SELECT
    DISTINCT ON
    (colour_1) colour_1,
    colour_2
FROM
    my_table
ORDER BY
    colour_1,
    colour_2;
Output:  
Example 2: Notice the change in the query set result order. 
 
SELECT
    DISTINCT ON
    (colour_2) colour_2,
    colour_1
FROM
    my_table
ORDER BY
    colour_2,
    colour_1;
Output: 
 
 
akshaysingh98088
postgreSQL-constraints
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Batch Script - TITLE

This batch command sets the title displayed in the console window.
TITLE [Tilename]

Where tilename is the new name to be given to the title of the command prompt window.
@echo off 
Title “New Windows Title”
The above command will change the title of the window to “New Windows Title”.
 Print
 Add Notes
 Bookmark this page
What is Stale Element Reference Exception in Selenium Webdriver & How To Fix It?

We may encounter StaleElementReferenceException while working with Selenium webdriver. We can fix the StaleElementReferenceException in the Selenium webdriver. The term stale means something which is not fresh and decayed. Thus a stale element points to an element that is not present anymore.
There may be a case when an element was in DOM initially but after modifications in Document Object Model (DOM), the element becomes stale and the StaleElementReferenceException is thrown if we attempt to access this element.
This exception is caused whenever an element is not present in the DOM or deleted. We can handle this exception in the following ways −
Refreshing the page and verifying again.
Implement the retry method.
Code Implementation to illustrate StaleElementException.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class StaleElmnt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      //application launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");

      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));

      //enter text
      l.sendKeys("Selenium");

      //refresh page
      driver.navigate().refresh();

      //again enter text
      l.sendKeys("Selenium");

      //browser quit
      driver.quit();
   }
}
Code Implementation to fix the StaleElementException.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.StaleElementReferenceException;
public class StaleElmntFix{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      //application launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");

      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));

      //enter text
      l.sendKeys("Selenium");

      //refresh page
      driver.navigate().refresh();

      //fix exception with try-catch block
      try{
         l.sendKeys("Selenium");
      }
      catch(StaleElementReferenceException e){
         l = driver.findElement(By.id("gsc-i-id1"));
         l.sendKeys("Selenium");

         //obtain value entered
         String s= l.getAttribute("value");
         System.out.println("Value entered is: " +s);
      }
      driver.quit();
   }
}
C | Misc | Question 7 - GeeksforGeeks

01 Sep, 2021
The number of tokens in the following C statement is (GATE 2000)
printf("i = %d, &i = %x", i, &i);
(A) 3(B) 26(C) 10(D) 21Answer: (C)Explanation: In a C source program, the basic element recognized by the compiler is the “token.” A token is source-program text that the compiler does not break down into component elements.There are 6 types of C tokens : identifiers, keywords, constants, operators, string literals and other separators. There are total 10 tokens in the above printf statement.Below are tokens in above program.
printf
(
"i = %d, &i = %x"
, 
i
,
&
i
)
;
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE Previous Year Questions PYQ - Lexical Analysis | Compiler DesignWatch 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:0031:44 / 42:38•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xcubPntmL3Y" 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
C-Misc
Misc
C Quiz
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C | Structure & Union | Question 4
C | File Handling | Question 5
C | Dynamic Memory Allocation | Question 5
C | Advanced Pointer | Question 2
C | Pointer Basics | Question 6
C | Pointer Basics | Question 4
C | Operators | Question 1
C | Advanced Pointer | Question 1
C | Pointer Basics | Question 2
C | Pointer Basics | Question 1
What is the difference between equals and compareTo in Java?

The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string.
The result is a negative integer if this String object lexicographically precedes the argument string.
 The result is a positive integer if this String object lexicographically follows the argument string.
 The result is zero if the strings are equal, compareTo returns 0 exactly when the equals(Object) method would return true.
Live Demo
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials", str2 = "point";

      // comparing str1 and str2
      int retval = str1.compareTo(str2);

      // prints the return value of the comparison
      if (retval < 0) {
         System.out.println("str1 is greater than str2");
      } else if (retval == 0) {
         System.out.println("str1 is equal to str2");
      } else {
         System.out.println("str1 is less than str2");
      }
   }
}
str1 is less than str2
How to do bitwise complement on a 16-bit signal using Python?

If you want to get an inversion of only first 16 bits of a number, you can take a xor of that number with 65535(16 1s in binary). 
a = 3 # 11 in binary
b = a ^ 65535
print(bin(b))
This will give the output −
0b1111111111111100
How to detect the screen resolution with JavaScript?

To detect the screen resolution, use the concept of window.screen.
For width, use the following −
window.screen.availWidth
For height −
window.screen.availHeight
Following is the code to detect the screen resolution −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<script>
   console.log("Available Width="+window.screen.availWidth);
   console.log("Available Height="+window.screen.availHeight);
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −