code-rag-bench/online-tutorials huggingface dataset:
Python PIL | Image.quantize() method

17 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
Image.quantize() Convert the image to ‘P’ mode with the specified number of colors.
Syntax: Image.quantize(colors=256, method=None, kmeans=0, palette=None)
Parameters:
colors – The desired number of colors, <= 256method – 0 = median cut 1 = maximum coverage 2 = fast octreekmeans – Integerpalette – Quantize to the PIL.ImagingPalette palette.
Returns type: An Image object.
Image Used:
     # Importing Image module from PIL package from PIL import Image import PIL   # creating a image object (main image) im1 = Image.open(r"C:\Users\System-Pc\Desktop\flower1.jpg")   # quantize a image im1 = im1.quantize(256)   # to show specified image im1.show() 
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Introduction To PYTHON
Java | Functions | Question 10

28 Jun, 2021
Predict the output of the following program.
class Test implements Cloneable{    int a;      Test cloning()    {        try        {            return (Test) super.clone();        }        catch(CloneNotSupportedException e)        {            System.out.println("CloneNotSupportedException is caught");            return this;        }    }}  class demo{      public static void main(String args[])    {        Test obj1 = new Test();        Test obj2;        obj1.a = 10;        obj2 = obj1.cloning();        obj2.a = 20;          System.out.println("obj1.a = " + obj1.a);        System.out.println("obj2.a = " + obj2.a);    }}
(A)
obj1.a = 10
obj2.a = 20
(B)
obj1.a = 20
obj2.a = 20
(C)
obj1.a = 10
obj2.a = 10
Answer: (A)Explanation: The clone( ) method generates a duplicate copy of the object on which it is called. Only classes that implement the Cloneable interface can be cloned.Quiz of this QuestionPlease comment below if you find anything wrong in the above post
Functions
Java-Functions
Java Quiz
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Constructors | Question 3
Java | Exception Handling | Question 2
Java | Class and Object | Question 7
Java | Class and Object | Question 1
Java | Exception Handling | Question 3
Java | Exception Handling | Question 4
Java | Exception Handling | Question 8
Java | Exception Handling | Question 6
Java | Abstract Class and Interface | Question 2
Java | Exception Handling | Question 7
Python SQLite - Establishing Connection

To establish connection with SQLite Open command prompt, browse through the location of where you have installed SQLite and just execute the command sqlite3 as shown below −
You can communicate with SQLite2 database using the SQLite3 python module. To do so, first of all you need to establish a connection (create a connection object).
To establish a connection with SQLite3 database using python you need to −
Import the sqlite3 module using the import statement.
Import the sqlite3 module using the import statement.
The connect() method accepts the name of the database you need to connect with as a parameter and, returns a Connection object.
The connect() method accepts the name of the database you need to connect with as a parameter and, returns a Connection object.
import sqlite3
conn = sqlite3.connect('example.db')
print("Connection established ..........")
Filtering MongoDB items by fields and subfields?

To filter items by fields and subfields, use dot notation. Let us create a collection with documents −
> db.demo638.insert({Name:"Chris"});
WriteResult({ "nInserted" : 1 })
> db.demo638.insert({Name:"David",details:{Subject:"MongoDB"}});
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo638.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e9c28666c954c74be91e6de"), "Name" : "Chris" }
   {
      "_id" : ObjectId("5e9c28866c954c74be91e6df"),
      "Name" : "David",
      "details" : {
         "Subject" : "MongoDB"
   }
}
Following is the query to filter items by multiple fields and subfields −
> db.demo638.find({"details.Subject":null});
This will produce the following output −
{ "_id" : ObjectId("5e9c28666c954c74be91e6de"), "Name" : "Chris" }
Matching Nonprintable Characters using Java regex

There are 7 common non printable characters used in general and each character has its own hexadecimal representation.
 Live Demo
Following Java program accepts an input text and counts the number of tab spaces in it −
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\\t";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("Number of tab spaces in the given iput text: "+count);
   }
}
sample text with tab spaces
Number of tab spaces in the given input text: 3
 Live Demo
You can also use the respective hexa-decimal representations of the non-printable characters to match.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\\x09";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("Number of tab spaces in the given iput text: "+count);
   }
}
Enter input text:
sample data with tab spaces
Number of tab spaces in the given input text: 4
Maximum contiguous sum of subarray in JavaScript

We are required to write a JavaScript function that takes in an array of array of positive and negative integers. Since the array also contains negative elements, the sum of contiguous elements can possibly be negative or positive.
Our function should pick an array of contiguous elements from the array that sums the greatest. Finally, the function should return that array.
For example −
If the input array is −
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
Then the maximum possible sum is 7 and the output subarray should be −
const output = [4, -1, -2, 1, 5];
Following is the code -
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
const maximumSubarray = (arr = []) => {
   let max = -Infinity;
   let currentSum = 0;
   let maxStartIndex = 0;
   let maxEndIndex = arr.length - 1;
   let currentStartIndex = 0;
   arr.forEach((currentNumber, currentIndex) => {
      currentSum += currentNumber;
      if (max < currentSum) {
         max = currentSum;
         maxStartIndex = currentStartIndex;
         maxEndIndex = currentIndex;
      }
      if (currentSum < 0) {
         currentSum = 0;
         currentStartIndex = currentIndex + 1;
      }
   });
   return arr.slice(maxStartIndex, maxEndIndex + 1);
};
console.log(maximumSubarray(arr));
Following is the output on console −
[ 4, -1, -2, 1, 5 ]
Sending an Attachment with email using Perl

If you want to send an attachment in your email using Perl, then following script serves the purpose −
#!/usr/bin/perl
use MIME::Lite;
$to = 'abcd@gmail.com';
$cc = 'efgh@mail.com';
$from = 'webmaster@yourdomain.com';
$subject = 'Test Email';
$message = 'This is test email sent by Perl Script';
$msg = MIME::Lite-=>new(
   From => $from,
   To => $to,
   Cc => $cc,
   Subject => $subject,
   Type => 'multipart/mixed'
);
# Add your text message.
$msg->attach(
   Type => 'text',
   Data => $message
);
# Specify your file as attachement.
$msg->attach(Type => 'image/gif',
   Path => '/tmp/logo.gif',
   Filename => 'logo.gif',
   Disposition => 'attachment'
);
$msg->send;
print "Email Sent Successfully\n";
You can attach as many files as you like in your email using attach() method.
How to show current location using HTML5 Geolocation with Google Maps?

HTML5 Geolocation API lets you share your location with your favorite websites. A Javascript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map. The geolocation coordinates specify the geographic location of the device.
Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information.
We will be using getCurrentPostion() method. To get current location using HTML5 Geolocation with Google Maps, you need to set an API key for Google Static Maps API.
Go to https://console.developers.google.com and get a free API key for Google Map. Add this key to the code to work Geolocation with it.
You can try to run the following code to show current location using HTML5 Geolocation with Google Maps
Live Demo
<!DOCTYPE HTML>
<html>
   <head>
      <script type="text/javascript">
         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var latlongvalue = position.coords.latitude + ","
            + position.coords.longitude;
            var img_url = "https://maps.googleapis.com/maps/api/staticmap?center="
            +latlongvalue+"&amp;zoom=14&amp;size=400x300&amp;key
            =AIzaSyAa8HeLH2lQMbPeOiMlM9D1VxZ7pbGQq8o";
            document.getElementById("mapholder").innerHTML =
            "<img src='"+img_url+"'>";
         }
         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            } else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }
         function getLocation(){
            if(navigator.geolocation){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               navigator.geolocation.getCurrentPosition
               (showLocation, errorHandler, options);
            } else{
               alert("Sorry, browser does not support geolocation!");
            }
         }
      </script>
   </head>
   <body>
      <div id="mapholder"></div>
      <form>
         <input type="button" onclick="getLocation();" value="Get Location"/>
      </form>
   </body>
</html>
How to find the index of given element of a Java List?

The indexOf(Object) method of the java.util.ArrayList class returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Using this method, you can find the index of a given element.
 Live Demo
import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      ArrayList<String> arrlist = new ArrayList<String>(5);
      arrlist.add("G");
      arrlist.add("E");
      arrlist.add("F");
      arrlist.add("M");
      System.out.println("Size of list: " + arrlist.size());
      for (String value : arrlist) {
         System.out.println("Value = " + value);
      }
      int retval=arrlist.indexOf("E");
      System.out.println("The element E is at index " + retval);
   }
}
Size of list: 4
Value = G
Value = E
Value = F
Value = M
The element E is at index 1
Does STL priority queue allow duplicate values? - GeeksforGeeks

15 Jul, 2018
Yes, in C++ priority_queue, we may have duplicate values.
// C++ program to demonstrate that duplicate// values are allowed in a priority queue// (with maximum value at the top)#include <bits/stdc++.h>using namespace std;  int main(){    priority_queue<int> pq;    pq.push(30);    pq.push(5);    pq.push(30);    cout << pq.top() << " ";    pq.pop();    cout << pq.top() << " ";    pq.pop();    return 0;}
30 30

// C++ program to demonstrate that duplicate// values are allowed in a priority queue// (with minimum value at the top)#include <bits/stdc++.h>using namespace std;  int main(){    priority_queue<int> pq;    pq.push(5);    pq.push(5);    pq.push(5);    cout << pq.top() << " ";    pq.pop();    cout << pq.top() << " ";    pq.pop();    cout << pq.top() << " ";    pq.pop();    return 0;}
5 5 5

cpp-priority-queue
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
Convert string to char array in C++
Pair in C++ Standard Template Library (STL)
Destructors in C++
new and delete operators in C++ for dynamic memory
Queue in C++ Standard Template Library (STL)
Elasticsearch - Frozen Indices

The indices that are searched frequently are held in memory because it takes time to rebuild them and help in an efficient search. On the other hand, there may be indices which we rarely access. Those indices need not occupy the memory and can be re-build when they are needed. Such indices are known as frozen indices.
Elasticsearch builds the transient data structures of each shard of a frozen index each time
that shard is searched and discards these data structures as soon as the search is complete. Because Elasticsearch does not maintain these transient data structures in memory, frozen indices consume much less heap than the normal indices. This allows for a much higher disk-to-heap ratio than would otherwise be possible.
The following example freezes and unfreezes an index −
POST /index_name/_freeze
POST /index_name/_unfreeze

Searches on frozen indices are expected to execute slowly. Frozen indices are not intended
for high search load. It is possible that a search of a frozen index may take seconds or minutes to complete, even if the same searches completed in milliseconds when the indices were not frozen.
The number of concurrently loaded frozen indices per node is limited by the number of threads in the search_throttled threadpool, which is 1 by default. To include frozen indices,
a search request must be executed with the query parameter − ignore_throttled=false.
GET /index_name/_search?q=user:tpoint&ignore_throttled=false

Frozen indices are ordinary indices that use search throttling and a memory efficient shard
implementation.
GET /_cat/indices/index_name?v&h=i,sth


    14 Lectures 
     5 hours 

 Manuj Aggarwal

    20 Lectures 
     1 hours 

 Faizan Tayyab
 Print
 Add Notes
 Bookmark this page
How to get the available azure VM size using Azure CLI in PowerShell?

To get all the available Azure VM sizes using Azure CLI from the specific location, we can use the az vm list-sizes command.
PS C:\> az vm list-sizes -l eastus
The default output is in the JSON format, as shown below.
To get the output in the table format, use the below command.
PS C:\> az vm list-sizes -l eastus -otable
Binary to original string conversion in JavaScript

We are required to write a JavaScript function that takes in a string that represents a binary code. The function should return the alphabetical representation of the string.
For example −
If the binary input string is −
const str = '1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100';
Then the output should be −
const output = 'Hello World';
The code for this will be −
const str = '1001000 1100101 1101100 1101100 1101111 100000 1010111
1101111 1110010 1101100 1100100';
const binaryToString = (binary = '') => {
   let strArr = binary.split(' ');
   const str = strArr.map(part => {
      return String.fromCharCode(parseInt(part, 2));
   }).join('');
   return str;
};
console.log(binaryToString(str));
And the output in the console will be −
Hello World
PHP | filemtime( ) Function - GeeksforGeeks

03 May, 2018
The filemtime() function in PHP is an inbuilt function which is used to return the last time of a specified file when its content was modified. The filemtime() function returns the last time the file was changed as a Unix Timestamp on success and False on failure.
The filename is passed as a parameter to the filemtime() function. The result of the filemtime() function is cached and a function called clearstatcache() is used to clear the cache.
Syntax:
filemtime($filename)
Parameters: The filemtime() function in PHP accepts only one parameter $filename. It specifies the file which you want to check.
Return Value: It returns the last time of a file when its content was modified as a Unix Timestamp on success and False on failure.
Errors And Exception:
The time resolution may differ from one file system to another.This function doesn’t works on some unix systems which have access time updates are disabled to increase performance.
The time resolution may differ from one file system to another.
This function doesn’t works on some unix systems which have access time updates are disabled to increase performance.
Examples:
Input : echo filemtime("gfg.txt");
Output : 1525159574

Input : echo "Last modified: ".date("F d Y H:i:s.", 
                              filemtime("gfg.txt"));
Output : Last modified: May 1 2018 07:26:14.

Below programs illustrate the filemtime() function.
Program 1:
<?php  // checking last time the contents// of a file were changedecho filemtime("gfg.txt");  ?>
Output:
1525159574
Program 2:
<?php  // checking last time the contents// of a file were changedecho filemtime("gfg.txt");  // checking last time the contents of// a file were changed and formatting// the output of the date echo "Last modified: ".date("F d Y H:i:s.",                       filemtime("gfg.txt"));?>
Output:
1525159574
Last modified: May 1 2018 07:26:14.

Reference:http://php.net/manual/en/function.filemtime.php
PHP-date-time
PHP-file-handling
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Vector get() Method in Java - GeeksforGeeks

17 Aug, 2018
The java.util.vector.get() method is used to fetch or retrieve an element at a specific index from a Vector.
Syntax:
Vector.get(int index)
Parameters: This method accepts a mandatory parameter index which is of integer data type. It specifies the position or index of the element to be fetched from the Vector.
Return Value: The method returns the element present at the position specified by the parameter index.
Below programs illustrate the Java.util.Vector.get() method:
Program 1:
// Java code to illustrate get() methodimport java.util.*;  public class VectorDemo {    public static void main(String args[])    {          // Creating an empty Vector        Vector<String> vec_tor = new Vector<String>();          // Use add() method to add elements in the Vector        vec_tor.add("Geeks");        vec_tor.add("for");        vec_tor.add("Geeks");        vec_tor.add("10");        vec_tor.add("20");          // Displaying the Vector        System.out.println("Vector: " + vec_tor);          // Fetching the specific element from the Vector        System.out.println("The element is: "                           + vec_tor.get(2));    }}
Vector: [Geeks, for, Geeks, 10, 20]
The element is: Geeks

Program 2:
// Java code to illustrate get() methodimport java.util.Vector;  public class VectorDemo {    public static void main(String args[])    {          // Creating an empty Vector        Vector<String> vec_tor = new Vector<String>();          // Use add() method to add elements in the Vector        vec_tor.add("1");        vec_tor.add("2");        vec_tor.add("3");        vec_tor.add("10");        vec_tor.add("20");          // Displaying the Vector        System.out.println("Vector: "                           + vec_tor);          // Fetching the specific element from the Vector        System.out.println("The element is: "                           + vec_tor.get(4));    }}
Vector: [1, 2, 3, 10, 20]
The element is: 20

Java - util package
Java-Collections
Java-Functions
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
Querying an array of arrays in MongoDB?

Use $in operator to query an array of arrays in MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.arrayOfArraysDemo.insertOne({"EmployeeName":"Larry","EmployeeSkills":[["Java","MongoDB","MySQL","SQL Server"]]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f7a8d8d10a061296a3c5b")
}
> db.arrayOfArraysDemo.insertOne({"EmployeeName":"Mike","EmployeeSkills":[["C","C++"]]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f7aa68d10a061296a3c5c")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.arrayOfArraysDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c7f7a8d8d10a061296a3c5b"),
   "EmployeeName" : "Larry",
   "EmployeeSkills" : [
      [
         "Java",
         "MongoDB",
         "MySQL",
         "SQL Server"
      ]
   ]
}
{
   "_id" : ObjectId("5c7f7aa68d10a061296a3c5c"),
   "EmployeeName" : "Mike",
   "EmployeeSkills" : [
      [
         "C",
         "C++"
      ]
   ]
}
Here is the query for querying an array of arrays in MongoDB −
> db.arrayOfArraysDemo.find({'EmployeeSkills':{$elemMatch:{$elemMatch:{$in:['MongoDB']}}}
}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c7f7a8d8d10a061296a3c5b"),
   "EmployeeName" : "Larry",
   "EmployeeSkills" : [
      [
         "Java",
         "MongoDB",
         "MySQL",
         "SQL Server"
      ]
   ]
}
Array Declarations in Java

Here is the syntax for declaring an array variable −
dataType[] arrayRefVar;   // preferred way.
or
dataType arrayRefVar[];  // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
The following code snippets are examples of this syntax −
double[] myList;   // preferred way.
or
double myList[];   // works but not preferred way.
You can create an array by using the new operator with the following syntax −
arrayRefVar = new dataType[arraySize];
The above statement does two things −
It creates an array using new dataType[arraySize].
It creates an array using new dataType[arraySize].
It assigns the reference of the newly created array to the variable arrayRefVar.
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively, you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −
double[] myList = new double[10];
The following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Here is a complete example showing how to create, initialize, and process arrays −
Live Demo
public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }

      // Summing all elements
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);

      // Finding the largest element
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);      
   }
}
This will produce the following result −
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
How to convert a string to int in Lua programming?

Lua does the implicit conversion or also known as coercion when it notices that you are trying to use a number but wrote a string, then it automatically converts the string into an int, and it is quite useful.
Let’s consider a simple example where I will declare a string variable, and then I will try to do an arithmetic operation on it, then once the Lua compiler infers that we are trying to use the string as an int, it will automatically convert it into an int.
Consider the example shown below −
 Live Demo
str = "10"
print(type(str))
num = 2 * str
print(num)
print(type(num))
string
20
number
Now that we know about the automatic conversion (coercion), it’s a good idea to learn how to do the conversion explicitly, the first approach is to append a 0 to the string value, and that value will be converted to an integer.
Consider the example shown below −
 Live Demo
-- uncommon method
str = "100"
num = str + 0
print(type(num))
print(num)
number
100
The above approach is not a very common one, and it's better to use the library function to convert a string to a number.
Consider the example shown below −
 Live Demo
-- common method
str = "100"
num = tonumber(str)
print(type(num))
print(num)
number
100
Node.js Jimp - GeeksforGeeks

14 Oct, 2021
Introduction Jimp is a node module used to do image processing which is provided by the npm installer. The Jimp – Javascript Image Manipulation Program is a library written entirely in JavaScript for Node, without any external or native dependencies. Various Image manipulations options available in this library are blit, blur, color, contain and many more.Image types supported by Jimp : 
@jimp/jpeg
@jimp/png
@jimp/bmp
@jimp/tiff
@jimp/gif
Advantages : Nodejs syntax is easy to handle and people with background from Python or C++ can get easily used to it. The compilation time in nodejs is faster than any other.Input Images:  
 
npm init -y
npm install jimp
Example 1:  
javascript
//npm install --save jimp//import jimp library to the environmentvar Jimp = require('jimp');  //User-Defined Function to read the imagesasync function main() {  const image1 = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png');  const image2 = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185333/gfg111.png');    //call to blit function   image1.blit(image2, 20, 40)  //write image  .write('blit1.png');  console.log("Image Processing Completed");}  main();
Output:  
Example 2:  
javascript
//npm install --save jimp//import jimp library to the environmentvar Jimp = require('jimp');  //User-Defined Function to read the imagesasync function main() {  const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185333/gfg111.png');  image.blur(2, function(err){    if (err) throw err;  })  .write('blur2.png');}    main();console.log("Image Processing Completed");
Output:  
Reference: https://www.npmjs.com/package/jimp 
mridulmanochagfg
Image-Processing
Node-Jimp
Node.js
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.sendFile() Function
Express.js res.redirect() Function
Mongoose | findByIdAndUpdate() Function
How to read and write Excel file in Node.js ?
Node.js fs.readdirSync() Method
Login form using Node.js and MongoDB
Bootstrap 4 .flex-wrap class

Use the flex-wrap class in Bootstrap 4 to wrap flex items. The following is the code snippet to wrap the flex items −
<div class="d-flex flex-wrap bg-primary">
  .
  .
  <!--  flex items - - >
  .
  .
</div>
Let us set some flex items in the flex-wrap class −
<div class="d-flex flex-wrap bg-primary">
  <div class="p-2 border">India</div>
  <div class="p-2 border">US</div>
  <div class="p-2 border">UK</div>
  <div class="p-2 border">Australia</div>
  <div class="p-2 border">Denmark</div>
</div>
You can try to run the following code to implement the flex-wrap class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container mt-3">
      <h3>Flex Examples</h3>
      <p>Wrap - Yes</p>
      <div class="d-flex flex-wrap bg-primary">
         <div class="p-2 border">India</div>
         <div class="p-2 border">US</div>
         <div class="p-2 border">UK</div>
         <div class="p-2 border">Australia</div>
         <div class="p-2 border">Denmark</div>
         <div class="p-2 border">India</div>
         <div class="p-2 border">Poland</div>
         <div class="p-2 border">Netherlands</div>
         <div class="p-2 border">Ireland</div>
         <div class="p-2 border">Brazil</div>
         <div class="p-2 border">Russia</div>
         <div class="p-2 border">Morocco</div>
      </div><br>
      <p>Wrap - No</p>
      <div class="d-flex flex-nowrap bg-primary">
        <div class="p-2 border">India</div>
        <div class="p-2 border">US</div>
        <div class="p-2 border">UK</div>
        <div class="p-2 border">Australia</div>
        <div class="p-2 border">Denmark</div>
        <div class="p-2 border">India</div>
        <div class="p-2 border">Poland</div>
        <div class="p-2 border">Netherlands</div>
        <div class="p-2 border">Ireland</div>
        <div class="p-2 border">Brazil</div>
        <div class="p-2 border">Russia</div>
        <div class="p-2 border">Morocco</div>
       </div><br>
    </div>
  </body>
</html>
What is Type safe in C#?

Type safe in C# wouldn’t allow an object to sneak into other object’s memory. Let us see an example to understand the concept of −
public class One {
   public int Prop{ get; set;}
}

public class Two {
   public int Prop{get;set;}
   public int Prop1{get;set;}
}
Let’s say I have an object Class One −
One ob = new One();
Now you won’t be able to cast your object ob to the second class i.e. class Two. If you will cast it then a compile time error will arise because of the Type Safe feature in C#.
time.Milliseconds() Function in Golang With Examples

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Milliseconds() function in Go language is used to find the duration of time in form of an integer millisecond count. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (d Duration) Milliseconds() int64

Here, d is the duration of time.
Return Value: It returns the duration value as int64.
Example 1:
// Golang program to illustrate the usage of// Milliseconds() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining duration    // of Milliseconds method    milli, _ := time.ParseDuration("7s")      // Prints duration as     // an integer milliseconds    fmt.Printf("Only %d milliseconds of "+      "task is remaining.", milli.Milliseconds())}
Output:
Only 7000 milliseconds of task is remaining.

Example 2:
// Golang program to illustrate the usage of// Milliseconds() function  // Including main packagepackage main  // Importing fmt and timeimport (    "fmt"    "time")  // Calling mainfunc main() {      // Defining duration of     // Milliseconds method    milli, _ := time.ParseDuration("2h1m2s4545ns")      // Prints duration as     // an integer milliseconds    fmt.Printf("Only %d milliseconds of"+     " task is remaining.", milli.Milliseconds())}
Output:
Only 7262000 milliseconds of task is remaining.

GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Structures in Golang
Loops in Go Language
Time Durations in Golang
How to iterate over an Array using for loop in Golang?
Strings in Golang
Go Variables
time.Parse() Function in Golang With Examples
Class and Object in Golang
Python | Consecutive elements grouping in list

09 Sep, 2019
Sometimes, while working with Python lists, we can have a problem in which we might need to group the list elements on basis of their respective consecutiveness. This kind of problem can occur while data handling. Let’s discuss certain way in which this task can be performed.
Method : Using enumerate() + groupby() + generator function + lambdaThis task can be performed using the combination of above functions. In this, we create a generator function, in which we pass the list whose index-element are accessed using enumerate() and grouped by consecutive elements using groupby() and lambda. Works with Python2 only
# Python code to demonstrate working of# Consecutive elements grouping list# using enumerate() + groupby() + generator function + lambdaimport itertools  # Utility Generator Functiondef groupc(test_list):    for x, y in itertools.groupby(enumerate(test_list), lambda (a, b): b - a):        y = list(y)        yield y[0][1], y[-1][1]  # initialize listtest_list = [1, 2, 3, 6, 7, 8, 11, 12, 13]  # printing original listprint("The original list is : " + str(test_list))  # Consecutive elements grouping list# using enumerate() + groupby() + generator function + lambdares = list(groupc(test_list))  # printing resultprint("Grouped list is : " + str(res))
The original list is : [1, 2, 3, 6, 7, 8, 11, 12, 13]
Grouped list is : [(1, 3), (6, 8), (11, 13)]

Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use FOR LOOP in MySQL Stored Procedure?

The following is the syntax to work with FOR LOOP in MySQL stored procedure −
delimiter //
CREATE procedure yourProcedureName()
wholeblock:BEGIN
   DECLARE anyVariableName1 INT ;
   Declare anyVariableName3 int;
   DECLARE anyVariableName2 VARCHAR(255);
   SET anyVariableName1 =1 ;
   SET anyVariableName3 =10;
   SET anyVariableName2 = '';
loop_label: FORLOOP
   IF anyVariableName1 > anyVariableName3 THEN
      LEAVE loop_label;
   END IF;
   SET anyVariableName2 = CONCAT(anyVariableName2 ,anyVariableName1 ,',');
   SET anyVariableName1 = anyVariableName1 + 1;
   ITERATE loop_label;
   END FORLOOP;
SELECT anyVariableName2;
END
//
Now you can implement the above syntax. The for loop query is as follows −
mysql> delimiter //
mysql> CREATE procedure ForLoop()
   -> wholeblock:BEGIN
   -> DECLARE start INT ;
   -> Declare maxLimit int;
   -> DECLARE result VARCHAR(255);
   -> SET start =1 ;
   -> SET maxLimit=10;
   -> SET result = '';
   -> loop_label: LOOP
   -> IF start > 10 THEN
   -> LEAVE loop_label;
   -> END IF;
   -> SET result = CONCAT(result,start,',');
   -> SET start = start + 1;
   -> ITERATE loop_label;   
   -> END LOOP;
   -> SELECT result;
   -> END
   -> //
Query OK, 0 rows affected (0.37 sec)
mysql> delimiter ;
The above for loop prints 1 to 10 i.e. in the following form 1,2,3,4,.....10. Call the stored
procedure using CALL command. The syntax is as follows −
call yourStoredProcedureName();
The query to call is as follows −
mysql> call ForLoop();
+-----------------------+
| result                |
+-----------------------+
| 1,2,3,4,5,6,7,8,9,10, |
+-----------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
How to check if an URL is valid or not using Java?

The URL class of the java.net package represents a Uniform Resource Locator which is used to point a resource(file or, directory or a reference) in the worldwide web.
This class provides various constructors one of them accepts a String parameter and constructs an object of the URL class. While passing URL to this method if you used an unknown protocol or haven’t specified any protocol this method throws a MalformedURLException.
Similarly, the toURI() method of this class returns an URI object of the current URL. If the current URL is not properly formatted or, syntactically incorrect according to RFC 2396 this method throws a URISyntaxException.
In a separate method invoke create an URL object by passing the requires URL in Sting format and invoke the toURI() method. Wrap this code in try-catch blocks, if an exception is thrown (MalformedURLException or, URISyntaxException) that indicates there is an issue with the given URL.
import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
public class ValidatingURL {
   public static boolean isUrlValid(String url) {
      try {
         URL obj = new URL(url);
         obj.toURI();
         return true;
      } catch (MalformedURLException e) {
         return false;
      } catch (URISyntaxException e) {
         return false;
      }
   }
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an URL");
      String url = sc.next();
      if(isUrlValid(url)) {
         URL obj = new URL(url);
         //Opening a connection
         HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
         //Sending the request
         conn.setRequestMethod("GET");
         int response = conn.getResponseCode();
         if (response == 200) {
            //Reading the response to a StringBuffer
            Scanner responseReader = new Scanner(conn.getInputStream());
            StringBuffer buffer = new StringBuffer();
            while (responseReader.hasNextLine()) {
               buffer.append(responseReader.nextLine()+"\n");
            }
            responseReader.close();
            //Printing the Response
            System.out.println(buffer.toString());
         }
      }else {
         System.out.println("Enter valid URL");
      }
   }
}
Enter an URL
ht://www.tutorialspoint.com/
Enter valid URL
Python | Get items in sorted order from given dictionary

28 Feb, 2019
Given a dictionary, the task is to get all items from the dictionary in sorted order. Let’s discuss different ways we can do this task.
Method #1: Using sorted()
# Python code to demonstrate# to get sorted items from dictionary  # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}  # printing iniial_dictionaryprint ("iniial_dictionary", str(ini_dict))  # getting items in sorted orderprint ("\nItems in sorted order")for key in sorted(ini_dict):    print (ini_dict[key])
iniial_dictionary {'b': 'bhuvan', 'c': 'chandan', 'a': 'akshat'}

Items in sorted order
akshat
bhuvan
chandan

 Method #2: Using d.items()
# Python code to demonstrate# to get sorted items from dictionary  # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}  # printing iniial_dictionaryprint ("iniial_dictionary", str(ini_dict))  # getting items in sorted orderprint ("\nItems in sorted order")for key, value in sorted(ini_dict.items()):    print(value)
iniial_dictionary {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'}

Items in sorted order
akshat
bhuvan
chandan

 
Method #3: Using operator
# Python code to demonstrate# to get sorted items from dictionary  import operator  # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}  # printing iniial_dictionaryprint "iniial_dictionary", str(ini_dict)  # getting items in sorted orderprint ("\nItems in sorted order")for key, value in sorted(ini_dict.iteritems(),                         key = operator.itemgetter(1),                          reverse = False):    print key, " ", value
iniial_dictionary {'a': 'akshat', 'c': 'chandan', 'b': 'bhuvan'}

Items in sorted order
a   akshat
b   bhuvan
c   chandan

Python dictionary-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 | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Abstract Class and Interface in Java

07 Mar, 2018
Which of the following is true about interfaces in java.
1) An interface can contain following type of members.
....public, static, final fields (i.e., constants) 
....default and static methods with bodies

2) An instance of interface can be created.

3) A class can implement multiple interfaces.

4) Many classes can implement the same interface.
1, 3 and 4
1, 2 and 4
2, 3 and 4
1, 2, 3 and 4
Answer: (A) Explanation: The instance of an interface can't be created because it acts as an abstract class.Quiz of this Question
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Spring Boot - Annotations
Git - Difference Between Git Fetch and Git Pull
SDE SHEET - A Complete Guide for SDE Preparation
How to Install and Use NVM on Windows?
DSA Sheet by Love Babbar
Download Image From URL in Android
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Moment.js moment.hour() Method

12 Mar, 2021
The moment().hour() Method is used to get the hours from the current time or to set the hours.
Syntax:
moment().hour();
or
moment().hours();
Parameters: This method accepts a single parameter number that you want to set hours then you will require an additional parameter:
Number::It ranges from 0 to 23 and used to set hours in a variable.
Return Value: This function returns the current time in hours
Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory.
Moment.js can be installed using the following command:
Installing module:
npm install moment
Example 1: Getting the current time in hours.
index.js
// Importing moment module const moment = require('moment');   var a = moment().hours();  console.log("hours is: ",a); 
Run index.js file using below command:
node index.js
Output:
hours is:  22
Example 2: Setting hours of time.
index.js
Javascript
// Importing moment moduleconst moment = require('moment');   var a = moment().hours(20);  console.log(a); 
Run index.js file using below command:
node index.js
Output:
Moment<2021-02-10T20:34:30+05:30>
Reference: https://momentjs.com/docs/#/get-set/hour/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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 ?
Differences between Functional Components and Class Components in React
Validate a password using HTML and JavaScript

16 Apr, 2019
The task is to validate the password using HTML and JavaScript.
A password is correct if it contains:
At least 1 uppercase character.At least 1 lowercase character.At least 1 digit.At least 1 special character.Minimum 8 characters.
At least 1 uppercase character.
At least 1 lowercase character.
At least 1 digit.
At least 1 special character.
Minimum 8 characters.
Example:
<!DOCTYPE html><html>  <head>    <title>validate password</title>    <script type="text/javascript">        function test_str() {            var res;            var str =                document.getElementById("t1").value;            if (str.match(/[a-z]/g) && str.match(                    /[A-Z]/g) && str.match(                    /[0-9]/g) && str.match(                    /[^a-zA-Z\d]/g) && str.length >= 8)                res = "TRUE";            else                res = "FALSE";            document.getElementById("t2").value = res;          }    </script></head>  <body>    <p>        String:        <input type="text"                placeholder="abc"               id="t1" />        <br/>        <br/>        <input type="button"               value="Check"                onclick="test_str()" />        <br/>        <br/> Output:        <input type="text"                id="t2"               readonly/>    </p></body>  </html>
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.