code-rag-bench/online-tutorials huggingface dataset:
Java Examples - Reversing an array list

How to reverse an array list ?
Following example reverses an array list by using Collections.reverse(ArrayList)method.
import java.util.ArrayList;
import java.util.Collections;

public class Main {
   public static void main(String[] args) {
      ArrayList arrayList = new ArrayList();
      arrayList.add("A");
      arrayList.add("B");
      arrayList.add("C");
      arrayList.add("D");
      arrayList.add("E");
      System.out.println("Before Reverse Order: " + arrayList);
      Collections.reverse(arrayList);
      System.out.println("After Reverse Order: " + arrayList);
   }
}
The above code sample will produce the following result.
Before Reverse Order: [A, B, C, D, E]
After Reverse Order: [E, D, C, B, A]

Following example is another example of reverse of array.
public class HelloWorld {
   public static void main(String[] args) {
      int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
      System.out.println("Array before reverse:");
      
      for (int i = 0; i < numbers.length; i++) {
         System.out.print(numbers[i] + " ");
      } 
      for (int i = 0; i < numbers.length / 2; i++) {
         int temp = numbers[i];
         numbers[i] = numbers[numbers.length - 1 - i];
         numbers[numbers.length - 1 - i] = temp;
      } 
      System.out.println("\nArray after reverse:");
      for (int i = 0; i < numbers.length; i++) {
         System.out.print(numbers[i] + " ");
      } 
   }
}
The above code sample will produce the following result.
Array before reverse:
1 2 3 4 5 6 7 8 9 10 
Array after reverse:
10 9 8 7 6 5 4 3 2 1 

 Print
 Add Notes
 Bookmark this page
Why multiple inheritance is not supported in Java

In Java, a class cannot extend more than one class. Therefore following is illegal −
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritances.
The reason behind this is to prevent ambiguity.
Consider a case where class B extends class A and Class C and both class A and C have the same method display().
Now java compiler cannot decide, which display method it should inherit. To prevent such situation, multiple inheritances is not allowed in java.
How to change button label in confirm box using JavaScript?

To change button label in confirm box, try to run the following code. The code uses a JavaScript library jQuery and CSS to create a confirm box with different button label that the standard confirm box −
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      </script>
      <script>
         function functionConfirm(msg, myYes, myNo)
         {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes,.no").unbind().click(function()
            {
              confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.find(".no").click(myNo);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm
         {
            display: none;
            background-color: #91FF00;
            border: 1px solid #aaa;
            position: fixed;
            width: 250px;
            left: 50%;
            margin-left: -100px;
            padding: 6px 8px 8px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #48E5DA;
            display: inline-block;
            border-radius: 5px;
            border: 1px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 100px;
            cursor: pointer;
         }
         #confirm .message
         {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class="message"></div>
         <button class="yes">Like!</button>
         <button class="no">No, I Like Cricket!</button>
      </div>
      <button onclick = 'functionConfirm("Do you like Football?", function yes()
      {
         alert("Yes")
      }, function no()
      {
         alert("no")
      });'>submit</button>
   </body>
</html>
How to use jQuery hasAttribute() method to see if there is an attribute on an element?

Use jQuery hasAttribute() method to see if there is an attribute for an element.
You can try to run the following code to learn how to use hasAttribute() method:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
           $('button').on('click', function() {

             if (this.hasAttribute("style")) {
               alert('True')
             } else {
               alert('False')
             }
             
          })
         });
      </script>
   </head>
   <body>
       Check for attribute in the button element<br>
      <button class='button' style='background-color:blue;'>
      Button
      </button>
      <button class='button'>
      Button 2
      </button>
   </body>
</html>
Clojure - Strings subs

Returns the substring of ‘s’ beginning at start inclusive, and ending at end (defaults to length of string), exclusive.
Following is the syntax.
(subs s start end)

Parameters − ‘S’ is the input string. ‘Start’ is the index position where to start the substring from. ‘End’ is the index position where to end the substring.
Return Value − The substring.
Following is an example of the string formatting in Clojure.
(ns clojure.examples.hello
   (:gen-class))
(defn hello-world []
   (println (subs "HelloWorld" 2 5))
   (println (subs "HelloWorld" 5 7)))
(hello-world)
The above program produces the following output.
llo
Wo

 Print
 Add Notes
 Bookmark this page
How to create array of strings in Java?

In Java, you can create an array just like an object using the new keyword. The syntax of creating an array in Java using new keyword −
type[] reference = new type[10];
Where,
type is the data type of the elements of the array.
type is the data type of the elements of the array.
reference is the reference that holds the array.
reference is the reference that holds the array.
And, if you want to populate the array by assigning values to all the elements one by one using the index −
reference [0] = value1;
reference [1] = value2;
You can declare an array of Strings using the new keyword as &mius;
String[] str = new String[5];

And then, you can populate the string using the indices as −
str[0] = "JavaFX";
str[1] = "OpenCV";
str[2] = "ApacheFlume";
str[3] = "Apache Hadoop";
str[4] = "WebGL";
You can also create a String array directly using the curly braces as −
String str = str[0] = {"JavaFX", "OpenCV", "ApacheFlume", "Apache Hadoop", "WebGL"}
How do I make a dotted/dashed line in Android?

This example demonstrates how do I make a dotted/dashed line in Android.
Step 1 - Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 - Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/parent"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:gravity="center"
   android:background="#33FFFF00"
   android:orientation="vertical">
   <TextView
      android:id="@+id/text"
      android:textSize="18sp"
      android:textAlignment="center"
      android:text="click to show toast at top"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />
   <ImageView
      android:layout_width="match_parent"
      android:layout_marginTop="10dp"
      android:layout_height="5dp"
      android:src="@drawable/dotted"
      android:layerType="software" />
</LinearLayout>
In the above code, we have text view with image view. Image view contains a dotted background. So create dotted.xml in drawable as shown below -
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
   <solid android:color="@android:color/white" />
   <stroke android:width="1dip" android:color="#4fa5d5"/>
   <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/>
</shape>
Step 3 - Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView text;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      text = findViewById(R.id.text);
      text.setText("Dotted line for text view ");
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -
The above result contains a dotted line.
Click here to download the project code
PLSQL | INITCAP Function

20 Sep, 2019
The INITCAP function in PLSQl is used for setting the first character in each word to uppercase and the rest to lowercase.Words are delimited by white space or characters that are not alphanumeric.The INITCAP function in PLSQL can accept char can of any of the datatypes such as CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The value returned by the INITCAP function is of the same datatype as char. The database sets the case of the initial characters based on the binary mapping defined for the underlying character set.
Syntax:
INITCAP(string)
Parameters Used:
string:It is used to specify the string whose first character in each word will be converted to uppercase and all remaining characters converted to lowercase.
Return Value:The INITCAP function in PLSQL returns a string value.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1:
DECLARE 
   Test_String string(20) := 'geeksforgeeks';
      
BEGIN 
   dbms_output.put_line(INITCAP(Test_String)); 
   
END; 
Output:
Geeksforgeeks 
Example-2:
DECLARE 
   Test_String string(40) := 'Hello, welcome to geeksforgeeks.';
      
BEGIN 
   dbms_output.put_line(INITCAP(Test_String)); 
   
END; 
Output:
Hello, Welcome To Geeksforgeeks. 
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Display Multiple Images in One Window using OpenCV Python?

06 Apr, 2022
Prerequisites: Opencv
In this article, we will show how to display Multiple Images In One window using OpenCV in Python.
Import module
Load the Multiple images using cv2.imread()
Concatenate the images using concatenate(), with axis value provided as per orientation requirement
Display all the images using cv2.imshow()
Wait for keyboard button press using cv2.waitKey()
Exit window and destroy all windows using cv2.destroyAllWindows()
cv2.imread(): reads an image file from the given specific location
concatenate((image1,image2), axis): concatenates multiple images along a given mentioned axis (horizontal or vertical), The value of axis is given as 1 for combining them horizontally and 0 for combining them vertically.
cv2.imshow(): displays an image in a window
cv2.waitKey(): is a keyboard binding function. Its argument is the time in milliseconds. The function waits for specified milliseconds for any keyboard event.
cv2.destroyAllWindows(): If you have multiple windows open and you do not need those to be open, you can use cv2.destroyAllWindows() to close those all.
Program:
Python3
import cv2import numpy as np # Read First Imageimg1 = cv2.imread('GFG.png') # Read Second Imageimg2 = cv2.imread('GFG.png')  # concatenate image HorizontallyHori = np.concatenate((img1, img2), axis=1) # concatenate image VerticallyVerti = np.concatenate((img1, img2), axis=0) cv2.imshow('HORIZONTAL', Hori)cv2.imshow('VERTICAL', Verti) cv2.waitKey(0)cv2.destroyAllWindows()
Input:
GFG.png
Output:
simmytarika5
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
How to convert a std::string to const char* or char* in C++?

In this section, we will see how to convert C++ string (std::string) to const char* or char*. These formats are C style strings. We have a function called c_str(). This will help us to do the task. It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
Following is the declaration for std::string::c_str.
const char* c_str() const;
This function returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object. If an exception is thrown, there are no changes in the string.
 Live Demo
#include <iostream>
#include <cstring>
#include <string>

int main () {
   std::string str ("Please divide this sentence into parts");

   char * cstr = new char [str.length()+1];
   std::strcpy (cstr, str.c_str());

   char * p = std::strtok (cstr," ");
   while (p!=0) {
      std::cout << p << '\n';
      p = std::strtok(NULL," ");
   }
   delete[] cstr;
   return 0;
}
Please
divide
this
sentence
into
parts
Count occurrence of a given character in a string using Stream API in Java

29 May, 2019
Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using Stream API.
Examples:
Input: str = "geeksforgeeks", c = 'e'
Output: 4
'e' appears four times in str.

Input: str = "abccdefgaa", c = 'a' 
Output: 3
'a' appears three times in str.

Approach:
Convert the string into character stream
Check if the character in the stream is the character to be counted using filter() function.
Count the matched characters using the count() function
Below is the implementation of the above approach:
// Java program to count occurrences// of a character using Stream  import java.util.stream.*;  class GFG {      // Method that returns the count of the given    // character in the string    public static long count(String s, char ch)    {          return s.chars()            .filter(c -> c == ch)            .count();    }      // Driver method    public static void main(String args[])    {        String str = "geeksforgeeks";        char c = 'e';        System.out.println(count(str, c));    }}
4

Related Article: Program to count occurrence of a given character in a string
Java-Stream-programs
Java
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Write a program to reverse an array or string
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
GATE | GATE CS 2020 | Question 16

11 Aug, 2021
What is the worst case time complexity of inserting n2 elements into an AVL-tree with n elements initially ?(A) Θ(n4)(B) Θ(n2)(C) Θ(n2 log n)(D) Θ(n3)Answer: (C)Explanation: Since AVL tree is balanced tree, the height is O(log n). So, time complexity to insert an element in an AVL tree is O(log n) in worst case.
Note:
Every insertion of element:
Finding place to insert = O(log n)
If property not satisfied (after insertion) do rotation = O(log n)

So, an AVL insertion take = O(log n) + O(log n) = O(log n) in worst case. 
Now, given n2 element need to insert into given AVL tree, therefore, total time complexity will be O(n2 log n).
Alternative method: Time complexity in worst case,
1st insertion time complexity = O(log n)
2nd insertion time complexity = O(log(n+1))
.
.
.
n2th insertion time complexity = O(log(n + n2)) 
So, total time complexity will be,
= O(log n) +  O(log n+1)) + .... +  O(log(n + n2))
= O(log n*(n+1)*(n+2)*...(n+n2))
= O(log nn2)
= O(n2 log n) 
Option (C) is correct.
GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0045:08 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2001 | Question 50
C++ | Static Keyword | Question 1

28 Jun, 2021
Predict the output of following C++ program.
#include <iostream>using namespace std;  class Test{    static int x;public:    Test() { x++; }    static int getX() {return x;}};  int Test::x = 0;  int main(){    cout << Test::getX() << " ";    Test t[5];    cout << Test::getX();}
(A) 0 0(B) 5 5(C) 0 5(D) Compiler ErrorAnswer: (C)Explanation: Static functions can be called without any object. So the call “Test::getX()” is fine.
Since x is initialized as 0, the first call to getX() returns 0. Note the statement x++ in constructor. When an array of 5 objects is created, the constructor is called 5 times. So x is incremented to 5 before the next call to getX().Quiz of this Question
C++-Static Keyword
Static Keyword
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
Smart Pointers in C++ and How to Use Them
C++ | Function Overloading and Default Arguments | Question 2
C++ | References | Question 4
C++ | new and delete | Question 4
C++ | const keyword | Question 1
C++ | Static Keyword | Question 3
Program to cyclically rotate an array by one in Python | List Slicing

21 Nov, 2018
Given an array, cyclically rotate the array clockwise by one.
Examples:
Input:  arr = [1, 2, 3, 4, 5]
Output: arr = [5, 1, 2, 3, 4]

We have existing solution for this problem please refer Program to cyclically rotate an array by one link. We will solve this problem in python quickly using List Comprehension. Approach is very simple, just remove last element in list and append it in front of remaining list.
# Program to cyclically rotate an array by one  def cyclicRotate(input):            # slice list in two parts and append     # last element in front of the sliced list            # [input[-1]] --> converts last element pf array into list     # to append in front of sliced list       # input[0:-1] --> list of elements except last element     print ([input[-1]] + input[0:-1])  # Driver programif __name__ == "__main__":    input = [1, 2, 3, 4, 5]    cyclicRotate(input)
Output:
[5, 1, 2, 3, 4]

KarlKwon
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ iostream Library - cout Object

The object of class ostream that represents the standard output stream oriented to narrow characters (of type char). It corresponds to the C stream stdout. The standard output stream is the default destination of characters determined by the environment. This destination may be shared with more standard objects (such as cerr or clog).
Object of class ostream, characters can be written to it either as formatted data using the insertion operator (operator<<) or as unformatted data, using member functions such as write.
Following is the declaration for std::cout.
extern ostream cout;
cout is not tied to any other output stream.
A program should not mix output operations on cout with output operations on wcout (or with other wide-oriented output operations on stdout): Once an output operation has been performed on either, the standard output stream acquires an orientation (either narrow or wide) that can only be safely changed by calling freopen on stdout.
 Print
 Add Notes
 Bookmark this page
How to set location and location.href using JavaScript ? - GeeksforGeeks

03 Dec, 2020
Both location and location.href are used to set or return the complete URL of your current page. They return a string which contains the entire URL with the protocol.
Syntax:
location = "https://www.geeksforgeeks.org";
or
location.href = "https://www.geeksforgeeks.org";
Both are used to set the URL. Both are described as running JavaScript 1.0 in the backend in Netscape 2.0 and have been running in all browsers ever since. However, you have the liberty to prefer any one of the two according to your convenience but it is preferred to use location.href because location might not support older versions of Internet Explorer. 
Commands like location.split(“#); cannot be used as location is an object but location.href can be used as it is a string. 
Example: The following code demonstrates the DOM Location href property.
HTML
<!DOCTYPE html> <html>    <head>    <style>         h1 {             color: green;         }                    h2 {             font-family: Impact;         }                    body {             text-align: center;         }     </style> </head>    <body>     <h1>GeeksforGeeks</h1>     <h2>Setting location and location.href</h2>           <p>         Click on the button to go         to designated URL     </p>       <button ondblclick="myhref()">        Destination URL    </button>           <p id="href"></p>           <script>         function myhref() {            location.href =           "https://www.geeksforgeeks.org";         }    </script> </body>    </html>  
Output:
Before Clicking the Button:
After Double Click on Button:
CSS-Misc
HTML-Misc
JavaScript-Misc
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
Pafy - Getting File Size of Stream - GeeksforGeeks

20 Jul, 2020
In this article we will see how we can get file size given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Stream is basically available resolution of video is available on youtube. File size is in the form of bytes normally the better the resolution the greater will be the file size.
We can get the pafy object with the help of new method and with the help of allstreams attribute we can get the all the streams available for the video, below is the command to get the pafy object for given video
video = pafy.new(url)
streams = video.allstreams

The video url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform.
In order to do this we use get_filesize method with the stream object of video
Syntax : stream.get_filesize()
Argument : It takes no argument
Return : It returns integer
Below is the implementation
# importing pafyimport pafy     # url of video url = "https://www.youtube.com / watch?v = vG2PNdI8axo"    # getting videovideo = pafy.new(url)   # getting all the available streamsstreams = video.allstreams  # selecting one streamstream = streams[1]# getting file size of streamvalue = stream.get_filesize()  # printing the valueprint("File Size in bytes: " + str(value))
Output :
File Size in bytes: 554085

Another example
# importing pafyimport pafy     # url of video url = "https://www.youtube.com / watch?v = i6rhnSoK_gc"    # getting videovideo = pafy.new(url)   # getting all the available streamsstreams = video.allstreams  # selecting one streamstream = streams[4]  # getting file size of streamvalue = stream.get_filesize()  # printing the valueprint("File Size in bytes: " + str(value))
Output :
File Size in bytes: 8125774

Python-Pafy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Python String | replace()
How to change the 'text-decoration' property with jQuery?

To change text decoration property with jQuery, use the jQuery css() property.
You can try to run the following code to change text-decoration property from underline to overline:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").on({
        mouseenter: function(){
        $(this).css({"text-decoration": "overline"});
        }
    });    
});
</script>
<style>
p {
   text-decoration: underline;
}
</style>
</head>
<body>
<p>Move the mouse pointer on the text to remove underline and add overline.</p>
</body>
</html>
JavaScript function to accept a string and mirrors its alphabet

We have to write a function that accepts a string and mirrors its alphabet. For example −
If the input is ‘abcd’
The output should be ‘zyxw’
The function simply takes every character and map to the that is (26 - N) alphabets away from
it, where is the 1 based index of that alphabet like 5 for e and 10 for j.
We will use the String.prototype.replace() method here, to match all the English alphabets
irrespective of their case. The full code for this function will be −
const str = 'ABCD';
const mirrorString = str => {
   const regex = /[A-Za-z]/g;
   return str.replace(regex, char => {
      const ascii = char.charCodeAt();
      let start, end;
      if(ascii > 96){
         start = 97;
         end = 122;
      } else {
         start = 65;
         end = 90;
      }
      return String.fromCharCode(end - (ascii-start));
   });
}
console.log(mirrorString(str));
console.log(mirrorString('Can we flip this as well'));
console.log(mirrorString('SOME UPPERCASE STUFF'));
The output in the console will be −
ZYXW
Xzm dv uork gsrh zh dvoo
HLNV FKKVIXZHV HGFUU
How to write MySQL procedure to insert data into a table?

To write stored procedure to insert data into a table, at first you need to create a table −
mysql> create table insertDataUsingStoredProcedure
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY ,
   -> Name varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (0.51 sec)
Following is the query to write stored procedure to insert data into the table −
mysql> DELIMITER //
mysql> CREATE PROCEDURE StoredProcedureInsertData(IN StudentName varchar(100),IN
StudentAge int)
   -> BEGIN
   -> insert into insertDataUsingStoredProcedure(Name,Age) values (StudentName, StudentAge );
   -> END
   -> //
Query OK, 0 rows affected (0.13 sec)
mysql> DELIMITER ;
Following is the query to call the above stored procedure to insert data into the table −
mysql> call StoredProcedureInsertData('Chris',24);
Query OK, 1 row affected (0.18 sec)
Now check the data has been inserted into the table or not −
mysql> select * from insertDataUsingStoredProcedure;
This will produce the following output −
+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 1  | Chris | 24   |
+----+-------+------+
1 row in set (0.00 sec)
How to get a number of days in a specified month using JavaScript?

To get numbers of days in a month, use the getDate() method and get the days.
You can try to run the following code to get a number of days in a month −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
      var days = function(month,year) {
         return new Date(year, month, 0).getDate();
      };
      document.write("Days in July: "+days(7, 2012)); // July month
      document.write("<br>Days in September: "+days(9, 2012)); // September Month
      </script>
   </body>
</html>
Days in July: 31
Days in September: 30
Timer1 based PWM in Arduino Uno

In an earlier article, we have seen how PWM can be set on Arduino Uno using the analogWrite() function. Pins 3,5,6,9,10 and 11 of Arduino Uno can support PWM. The frequency of the square wave is 490 Hz (about 2 ms time period) on all pins except 5 and 6, on which it is 980 Hz (about 1s time period). With analogWrite() you get control over the duty cycle, but not on the frequency of the generated square wave.
In this article, we will look at another way of setting PWM in Arduino Uno, specific to Timer1. The advantage of this method is that it allows us to control the frequency of the PWM signal as well, along with the duty cycle. This is based on the TimerOne library that we have seen in the past, in the article concerning Timer Interrupts in Arduino. Go to Tools → Library Manager, and download the TimerOne library.
The syntax for PWM is −
Timer1.pwm(pin, duty);
Where pin is the pin number on which you wish to set the PWM. Only pins 9 and 10 allow Timer1 based PWM.
Duty is the duty cycle (from 0 to 1023). 0 represents a duty cycle of 0%, while 1023 represents 100%.
If you wish to change the duty cycle mid-execution, you can use −
Timer1.setPwmDuty(pin, duty);
And to disable PWM, you can use −
Timer1.disablePwm(pin);
You may be wondering where did we set the frequency of the PWM. We do that in the setup, using the Timer.initialize() function.
Timer1.initialize(microseconds);
Where the argument is the microsecond interval of the wave. Thus, if you want a frequency of 100kHz, you set the microseconds time as 10.
Timer1.initialize(10);
We will look at the example that comes with the TimerOne library. Go to File → Examples → TimerOne → FanSpeed
You can also find the code on GitHub here − https://github.com/PaulStoffregen/TimerOne/blob/master/examples/FanSpeed/FanSpeed.pde
Over here, the speed of the fan, connected to pin 4 (you need to change it to pin 9 or 10 for Arduino Uno), is changed using PWM.
We include the library and begin with specifying the fan pin.
#include −TimerOne.h>
const int fanPin = 9;
In the setup, we initialize the Timer1 library at 40 microseconds interval (or 25 kHz frequency), and we also initialize Serial.
void setup(void)
{
   Timer1.initialize(40); // 40 us = 25 kHz
   Serial.begin(9600);
}
In the loop, we increase the duty cycle from 30% to 100%, in steps of 1% in a for loop.
void loop(void)
{
   // slowly increase the PWM fan speed
   //
   for (float dutyCycle = 30.0; dutyCycle < 100.0; dutyCycle++) {
      Serial.print("PWM Fan, Duty Cycle = ");
      Serial.println(dutyCycle);
      Timer1.pwm(fanPin, (dutyCycle / 100) * 1023);
      delay(500);
   }
}
How do I use InputFilter to limit characters in an EditText in Android Kotlin?

This example demonstrates how to use InputFilter to limit characters in an EditText in Android Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/editText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="40dp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.text.InputFilter
import android.text.InputFilter.LengthFilter
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   lateinit var editText: EditText
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      editText = findViewById(R.id.editText)
      val maxTextLength = 15
      editText.filters = arrayOf<InputFilter>(LengthFilter(maxTextLength))
      Toast.makeText(this, "EditText limit set to 15 characters", Toast.LENGTH_SHORT).show()
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Python Group by matching second tuple value in list of tuples - GeeksforGeeks

11 Dec, 2020
Given a list of tuples, the task is to group the tuples by matching the second element in the tuples. We can achieve this using dictionary by checking the second element in each tuple.
Examples:
Input : [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)]
Output: {80: [(20, 80), (31, 80)],
         11: [(88, 11), (27, 11)],
         22: [(1, 22)]}

Input : [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')]
Output: {'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],
         'Geek': [(20, 'Geek'), (31, 'Geek')]}


 
Code #1:
# Python program to group tuples by matching # second tuple value in list of tuples  # Initialisation Input = [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)]  Output = {}for x, y in Input:    if y in Output:        Output[y].append((x, y))    else:        Output[y] = [(x, y)]  # Printing Outputprint(Output)
{80: [(20, 80), (31, 80)], 11: [(88, 11), (27, 11)], 22: [(1, 22)]}

 Code #2:
# Python program to group tuples by matching # second tuple value in list of tuples  # Initialisation Input = [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')]  Output = {}for x, y in Input:    if y in Output:        Output[y].append((x, y))    else:        Output[y] = [(x, y)]  # Printing Outputprint(Output)
{'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],
 'Geek': [(20, 'Geek'), (31, 'Geek')]}

Python tuple-programs
python-tuple
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Matplotlib.figure.Figure.subplots_adjust() in Python - GeeksforGeeks

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The subplots_adjust() method figure module of matplotlib library is used to Update the SubplotParams with kwargs.
Syntax: subplots_adjust(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
Parameters: This method accept the following parameters that are discussed below:
left : This parameter is the left side of the subplots of the figure.
right : This parameter is the right side of the subplots of the figure.
bottom : This parameter is the bottom of the subplots of the figure.
top : This parameter is the top of the subplots of the figure.
wspace : This parameter is the amount of width reserved for space between subplots expressed as a fraction of the average axis width.
hspace : This parameter is the amount of height reserved for space between subplots expressed as a fraction of the average axis height.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.subplots_adjust() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt     x = [1, 2, 3, 4]y = [1, 4, 9, 16]   fig = plt.figure()axs = fig.subplots()  axs.plot(x, y)  fig.subplots_adjust(bottom = 0.15)  fig.suptitle("""matplotlib.figure.Figure.subplots_adjust()function Example\n\n""", fontweight ="bold")   fig.show() 
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import TextBox    fig, ax = plt.subplots()fig.subplots_adjust(bottom = 0.2)  t = np.arange(-2.0, 2.0, 0.001)s = np.sin(t)+np.cos(2 * t)  initial_text = "sin(t) + cos(2t)"l, = ax.plot(t, s, lw = 2)      def submit(text):    ydata = eval(text)    l.set_ydata(ydata)    ax.set_ylim(np.min(ydata), np.max(ydata))    plt.draw()   axbox = plt.axes([0.4, 0.05, 0.3, 0.075])  text_box = TextBox(axbox, 'Formula Used : ',                   initial = initial_text)text_box.on_submit(submit)  fig.suptitle("""matplotlib.figure.Figure.subplots_adjust()function Example\n\n""", fontweight ="bold")   fig.show() 
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Bootstrap dropdown closing when clicked in HTML

As you may have seen, whenever you open a dropdown, and click anywhere else, the dropdown close. 
By using the below given code, the dropdown menu can be kept open after click−
$('#myDropdown').on('hide.bs.dropdown', function () {
   return false;
});
Another option is to handle the clickevent −
The click event can also be handled byusing the following code. The event.stopPropagation() method stopsthe bubbling of an event to parent elements. It prevents any parentevent handlers from being executed −
$('#myDropdown .dropdown-menu').on({
   "click":function(e) {
       e.stopPropagation();
    }
});
Combine keys in a list of dictionaries in Python - GeeksforGeeks

22 Jun, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform a merge of dictionaries in list with similar keys. This kind of problem can come in data optimization domains. Let’s discuss a way in which this task can be performed.
Input : test_list = [{‘a’: 6}, {‘b’: 2}, {‘a’: 9}, {‘b’: 7}]Output : [{‘b’: 2, ‘a’: 6}, {‘b’: 7, ‘a’: 9}]
Input : test_list = [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]Output : [{‘a’: 8}, {‘a’: 2}, {‘a’: 3}]
Method : loop + ** operatorThe combination of above functions can be used to solve this problem. In this, we use brute force to construct a new dictionary and add keys only if that is not added in current. The task of merging dictionaries is by unpacking the initial dictionaries using “**” operator, and then packing again with dictionary with no repeated key and new one, using the usual dictionary initialization construct {}.
# Python3 code to demonstrate working of # Merge Similar Dictionaries in List# Using loop + "**" operator  # initializing listtest_list = [{'gfg' : 1}, {'is' : 2}, {'best' : 3},              {'gfg' : 5}, {'is' : 17}, {'best' : 14},              {'gfg' : 7}, {'is' : 8}, {'best' : 10},]  # printing original listprint("The original list is : " + str(test_list))  # Merge Similar Dictionaries in List# Using loop + "**" operatorres = [{}]for sub in test_list:    if list(sub)[0] not in res[-1]:        res[-1] = {**res[-1], **sub}    else:        res.append(sub)  # printing result print("The merged dictionaries : " + str(res)) 
The original list is : [{‘gfg’: 1}, {‘is’: 2}, {‘best’: 3}, {‘gfg’: 5}, {‘is’: 17}, {‘best’: 14}, {‘gfg’: 7}, {‘is’: 8}, {‘best’: 10}]The merged dictionaries : [{‘best’: 3, ‘is’: 2, ‘gfg’: 1}, {‘best’: 14, ‘is’: 17, ‘gfg’: 5}, {‘best’: 10, ‘is’: 8, ‘gfg’: 7}]
 
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Express.js – app.listen() Method

The app.listen() method binds itself with the specified host and port to bind and listen for any connections. If the port is not defined or 0, an arbitrary unused port will be assigned by the operating system that is mainly used for automated tasks like testing, etc.
The app object returned by express() is a JavaScript function, that is passed to Node’s HTTP servers as a callback which handles the requests. This makes the application to provide both HTTP and HTTPS versions of the same app with the same code base, as the app does not inherit from these.
app.listen([port], [host], [backlog], [callback])
Create a file with the name "appListen.js" and copy the following code snippet.
After creating the file, use the command "node appListen.js" to run this code.
// app.listen() Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
C:\home\node>> node appListen.js
Server listening on PORT 3000
Let’s take a look at one more example.
// app.listen() Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();

// Assigning a port that is already in use
var PORT = 80;

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
C:\home\node>> node appListen.js
Server listening on PORT 80
Write a C program to perform 3X3 matrix operations

Enter any 9 numbers at runtime and add the numbers in a row, column, and diagonal wise by using C Programming language
Step 1: Declare 9 variables
Step 2: enter 9 numbers at runtime
Step 3: store the numbers in 3 X 3 matrix form
        //x y z
        p q r
        a b c
Step 4: Do row calculation: add all the numbers in a row and print
        // (x+y+z),(p+q+r),(a+b+c)
Step 5: Do column calculation: add all the numbers in a Column and print
        //(x+p+a)(y+q+b)(z+r+c)
Step 6: Do Diagonal Calculation: add the numbers in diagonal and print
        //(x+q+c),(a+q+z)
 Live Demo
#include<stdio.h>
int main(){
   int x,y,z,p,q,r,a,b,c;
   printf(“enter any 9 numbers :\n");
   scanf(“%d%d%d%d%d%d%d%d%d",&x,&y,&z,&p,&q,&r,&a,&b,&c);//reading all 9 integers
   printf(“%d %d %d\n",x,y,z);
   printf(“%d %d %d\n",p,q,r);
   printf(“%d %d %d\n",a,b,c);
   printf(“Row total:%d %d %d\n",(x+y+z),(p+q+r),(a+b+c));//row calculation
   printf(“column total: %d %d %d\n",(x+p+a),(y+q+b),(z+r+c));//column calculation
   printf(“diagonal total :%d %d\n",(x+q+c),(a+q+z));//Diagonal calculation
   return 0;
}
enter any 9 numbers :
2 4 6 3 5 7 8 9 2
2 4 6
3 5 7
8 9 2
Row total:12 15 19
column total: 13 18 15
diagonal total :9 19
GATE | GATE-CS-2016 (Set 2) | Question 2 - GeeksforGeeks

28 Jun, 2021
Nobody knows how the Indian cricket team is going to cope with the difficult and seamer-friendly wickets in Australia. Choose the option which is closest in meaning to the underlined phrase in the above sentence.
(A) put up with
(B) put in with(C) put down to(D) put up againstAnswer: (A)Explanation:
put up with - is a phrasal verb
Meaning : to accept somebody/something that is annoying, unpleasant without complaining

This explanation has been contributed by Mohit Gupta.Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
Socket Programming in C#

The System.Net.Sockets namespace has a managed implementation of the Windows Sockets interface.
It has two basic modes − synchronous and asynchronous.
Let us see an example to work with System.Net.Sockets.TcpListener class −
TcpListener l = new TcpListener(1234);
l.Start();

// creating a socket
Socket s = l.AcceptSocket();
Stream network = new NetworkStream(s);
The following is the Socket useful in communicating on TCP/IP network −
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Above,
AddressFamily − It is the standard address families by the Socket class to resolve network addresses
AddressFamily − It is the standard address families by the Socket class to resolve network addresses
SocketType − The type of socket
SocketType − The type of socket
ProtocolType − This is the network protocol for communication on the Socket. It can be Tcp and Udp.
ProtocolType − This is the network protocol for communication on the Socket. It can be Tcp and Udp.