code-rag-bench/online-tutorials huggingface dataset:
First class function in JavaScript

JavaScript treats functions as objects and allow us to pass functions as parameter to another function and even return functions from other functions. In JavaScript the functions are first class functions meaning we can store them in variable, objects and array. The higher order functions can take function, return them or do both.
Following is the code to implement first class functions in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>First class function in Javascript</h1>
<div class="sample">[22,33,44,55]</div>
<br />
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to double each element of the above array</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let doubleNum = (ele) => {
      return ele * 2;
   };
   let arr = [22, 33, 44, 55];
   function doubleArray(arr, fn) {
      let doubleArr = [];
      arr.forEach((element) => {
         doubleArr.push(doubleNum(element));
      });
      return doubleArr;
   }
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "New array = " + doubleArray(arr, doubleNum);
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
How do we find out if first character of a string is a number in java?

The isDigit() method of the java.lang.Character class accepts a character as a parameter and determines whether it is a digit or not. If the given character is a digit this method returns true else, this method returns false.
Therefore, to determine whether the first character of the given String is a digit.
The charAt() method of the String class accepts an integer value representing the index and returns the character at the specified index. 
The charAt() method of the String class accepts an integer value representing the index and returns the character at the specified index. 
The toCharArray() method of this class converts the String to a character array and returns it you can get its first character as array[0].
The toCharArray() method of this class converts the String to a character array and returns it you can get its first character as array[0].
Retrieve the 1st character of the desired String using either of the methods.
Retrieve the 1st character of the desired String using either of the methods.
Then, determine whether it is a digit or not by passing it as a parameter to the isDigit() method.
Then, determine whether it is a digit or not by passing it as a parameter to the isDigit() method.
import java.util.Scanner;
public class FirstCharacterOfString {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String str = sc.next();
      //Converting String to a character array
      char charArray[] = str.toCharArray();
      boolean bool = Character.isDigit(charArray[0]);
      if(bool) {
         System.out.println("First character is a digit");
      } else {
         System.out.println("First character is not a digit");
      }
   }
}
Enter a String
krishna
First character is not a digit
Enter a String
2sample
First character is a digit
The matches() method of the String class accepts a regular expression and verifies it matches with the current String, if so, it returns true else, it returns false.
The regular expression to match String which contains a digit as first character is “^[0-9].*$”. Pass this as a parameter to the matches() method of the String class.
import java.util.Scanner;
public class FirstCharacterOfString {
   public static void main(String args[]) {
      //reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String str = sc.next();
      boolean bool = str.matches("^[0-9].*$");
      if(bool) {
         System.out.println("First character is a digit");
      } else {
         System.out.println("First character is not a digit");
      }
   }
}
Enter a String
krishna
First character is not a digit
Enter a String
2sample
First character is a digit
How to subtract 3 hours from a datetime in MySQL?

Subtract 3 hours from DateTime in MySQL, using any of the following ways. The first approach is as follows −
select date_add(yourColumnName,interval -3 hours) from yourTableName;
select date_sub(yourColumnName,interval 3 hours) from yourTableName;
Firstly, use now() to get the current date-time −
mysql> select now();
The following is the output −
+---------------------+
| now()               |
+---------------------+
| 2018-11-30 10:13:23 |
+---------------------+
1 row in set (0.00 sec)
The query to subtract 3 hours from DateTime is as follows. With date_add, we have set a negative date −
mysql> select date_add(now(),interval -3 hour);
The following is the output −
+----------------------------------+
| date_add(now(),interval -3 hour) |
+----------------------------------+
| 2018-11-30 07:13:28              |
+----------------------------------+
1 row in set (0.00 sec)
Get the current date and time −
mysql> select now();
The output −
+---------------------+
| now()               |
+---------------------+
| 2018-11-30 10:14:12 |
+---------------------+
1 row in set (0.00 sec)
Implement the second method using date_sub(). The query is as follows −
mysql> select date_sub(now(),interval 3 hour);
The following output displays the date subtracting 3 hours −
+---------------------------------+
| date_sub(now(),interval 3 hour) |
+---------------------------------+
| 2018-11-30 07:14:25             |
+---------------------------------+
1 row in set (0.00 sec)
for command in Linux with Examples - GeeksforGeeks

15 May, 2019
for command in Linux is used to repeatedly execute a set of command for every element present in the list.
Syntax:
for NAME [in WORDS ... ] ; do COMMANDS; done
Example:
Options:
help for : It displays help information.
linux-command
Linux-Shell-Commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Mathematical Functions in C#

The System.Math class in C# provides methods are properties to perform mathematical operations, trigonometric, logarithmic calculations, etc.
Some of its methods include −
For all the methods, refer MSDN
Let us see an example to get the absolute value −
using System;

class Program {
   static void Main() {
      int val1 = 250;
      int val2 = -150;

      Console.WriteLine("Before...");
      Console.WriteLine(val1);
      Console.WriteLine(val2);

      int abs1 = Math.Abs(val1);
      int abs2 = Math.Abs(val2);

      Console.WriteLine("After...");
      Console.WriteLine(abs1);
      Console.WriteLine(abs2);
   }
}
Logarithmic and Trigonometric functions are also part of the System. Math class in C#. Trigonometric Functions in C# includes ACos, ASin, Sin, Cos, Tan, etc. It comes under the Math type of the System namespace.
The following is an example showing how to implement trigonometric functions in C# −
using System;

class Program {
   static void Main() {
      Console.WriteLine(Math.Acos(0));
      Console.WriteLine(Math.Cos(2));

      Console.WriteLine(Math.Asin(0.2));
      Console.WriteLine(Math.Sin(2));
   }
}
React Conditional Rendering

In React, you can conditionally render components.
There are several ways to do this.
We can use the if JavaScript operator to decide which component to render.
We'll use these two components:
function MissedGoal() {
  return <h1>MISSED!</h1>;
}

function MadeGoal() {
  return <h1>Goal!</h1>;
}

Now, we'll create another component that chooses which component to render based on a condition:
function Goal(props) {
  const isGoal = props.isGoal;
  if (isGoal) {
    return <MadeGoal/>;
  }
  return <MissedGoal/>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);


Run 
Example »

Try changing the isGoal attribute to true:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={true} />);


Run 
Example »

Another way to conditionally render a React component is by using the && operator.
We can embed JavaScript expressions in JSX by using curly braces:
function Garage(props) {
  const cars = props.cars;
  return (
    <>
      <h1>Garage</h1>
      {cars.length > 0 &&
        <h2>
          You have {cars.length} cars in your garage.
        </h2>
      }
    </>
  );
}

const cars = ['Ford', 'BMW', 'Audi'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);


Run 
Example »

If cars.length  is equates to true,
the expression after && will render.
Try emptying the cars array:
const cars = [];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);

Run 
Example »

Another way to conditionally render elements is by using a ternary operator.
condition ? true : false

We will go back to the goal example.
Return the MadeGoal component if
  isGoal is true, 
  otherwise return the MissedGoal component:
function Goal(props) {
  const isGoal = props.isGoal;
  return (
    <>
      { isGoal ? <MadeGoal/> : <MissedGoal/> }
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);


Run 
Example »

To learn more, see the ternary operator section.
Use the correct logical operator to complete the following component.
function App({isLoggedIn}) {
  return (
    <>
      <h1>My Application</h1>
      {isLoggedIn  <Profile /> }
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Program to find maximum product of two distinct elements from an array in Python

Suppose we have a list of numbers called nums, we have to find the largest product of two unique elements.
So, if the input is like nums = [8, -3, 1, -5], then the output will be 15, (-3)*(-5) = 15 which is maximum here.
To solve this, we will follow these steps −
n := size of nums
n := size of nums
nums_sort := sort the list nums
nums_sort := sort the list nums
max_left := nums_sort[0] * nums_sort[1]
max_left := nums_sort[0] * nums_sort[1]
max_right := nums_sort[n-1] * nums_sort[n-2]
max_right := nums_sort[n-1] * nums_sort[n-2]
ans := maximum of max_left and max_right
ans := maximum of max_left and max_right
return ans
return ans
Let us see the following implementation to get better understanding
def solve(nums):
   nums_sort = sorted(nums)
   max_left = nums_sort[0] * nums_sort[1]
   max_right = nums_sort[-1] * nums_sort[-2]

   ans = max(max_left, max_right)
   return ans

nums = [8, -3, 1, -5]
print(solve(nums))
[8, -3, 1, -5]
15
Bootstrap 4 .flex-nowrap class

Avoid wrapping flex items in Bootstrap 4, using the .flex-nowrap class.
Below you can see the flex items aren’t wrapping after the “Eight” flex-item −
The flex is set in the div class as if we add any other class in <div>−
<div class="d-flex flex-nowrap bg-primary">
The following is an example to implement flex-nowrap class to avoid wrapping of flex items −
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 WRAP AND NOWRAP</h3>
      <p>Flex items will wrap</p>
      <div class="d-flex flex-wrap bg-primary">
        <div class="p-2 border">One</div>
        <div class="p-2 border">Two</div>
        <div class="p-2 border">Three</div>
        <div class="p-2 border">Four</div>
        <div class="p-2 border">Five</div>
        <div class="p-2 border">Six</div>
        <div class="p-2 border">Seven</div>
        <div class="p-2 border">Eight</div>
        <div class="p-2 border">Nine</div>
      </div><br>
      <p>Flex items won't wrap</p>
      <div class="d-flex flex-nowrap bg-primary">
        <div class="p-2 border">One</div>
        <div class="p-2 border">Two</div>
        <div class="p-2 border">Three</div>
        <div class="p-2 border">Four</div>
        <div class="p-2 border">Five</div>
        <div class="p-2 border">Six</div>
        <div class="p-2 border">Seven</div>
        <div class="p-2 border">Eight</div>
        <div class="p-2 border">Nine</div>
      </div><br>
   </div>
  </body>
</html>
How to use android date change listener ?

Before getting into the example, we should know what is date picker and how does it work in android. The date picker is a subclass of frame layout and it allows to select the date, month and year.
This example demonstrates how to use android date change listener.
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:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <DatePicker
      android:id="@+id/datePicker"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="36dp" />
</RelativeLayout>
In the above code, we have declare date picker to select the date. when you select the date it going to show current date on Toast message.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.DatePicker;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   @TargetApi(Build.VERSION_CODES.O)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      DatePicker datePicker = findViewById(R.id.datePicker);
      datePicker.setOnDateChangedListener(new DatePicker.OnDateChangedListener() {
         @Override
         public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Toast.makeText(MainActivity.this," You are changed date is : "+dayOfMonth +" -  "+monthOfYear+ " - "+year,Toast.LENGTH_LONG).show();
         }
      });
}
}
In the above code when you change the date using datechangedlistener, it going to show changed date, month and year on Toast message.
Step 4 − No need to change manifest.xml.
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 an 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 −
In the above example shows, when you change the date it going to show the changed date in toast message.
Click here to download the project code
Tryit Editor v3.7

Tryit: HTML image - alt attribute
How to convert a data frame with categorical columns to numeric in R?

We might want to convert categorical columns to numeric for reasons such as parametric results of the ordinal or nominal data. If we have categorical columns and the values are represented by using letters/words then the conversion will be based on the first character of the category. To understand the conversion, check out the below examples.
 Live Demo
Consider the below data frame −
set.seed(100)
x1<−sample(LETTERS[1:4],20,replace=TRUE)
x2<−sample(LETTERS[1:4],20,replace=TRUE)
x3<−sample(LETTERS[1:4],20,replace=TRUE)
x4<−sample(LETTERS[1:4],20,replace=TRUE)
df1<−data.frame(x1,x2,x3,x4)
df1
x1 x2 x3 x4
1 B C C B
2 C D A A
3 B B D A
4 D A C A
5 C D D B
6 A C B D
7 B C B C
8 B D A C
9 D B A C
10 C A B A
11 D B B A
12 B C A B
13 B D C D
14 D D C B
15 C B A C
16 B D C A
17 B D A B
18 C D D D
19 C A C C
20 C C C B
Converting columns in df1 to numerical −
df1[]<−as.numeric(factor(as.matrix(df1)))
df1
x1 x2 x3 x4
1 2 3 3 2
2 3 4 1 1
3 2 2 4 1
4 4 1 3 1
5 3 4 4 2
6 1 3 2 4
7 2 3 2 3
8 2 4 1 3
9 4 2 1 3
10 3 1 2 1
11 4 2 2 1
12 2 3 1 2
13 2 4 3 4
14 4 4 3 2
15 3 2 1 3
16 2 4 3 1
17 2 4 1 2
18 3 4 4 4
19 3 1 3 3
20 3 3 3 2
 Live Demo
y1<−sample(c("Hot","Cold","Bitter"),20,replace=TRUE)
y2<−sample(c("Hot","Cold","Bitter"),20,replace=TRUE)
y3<−sample(c("Hot","Cold","Bitter"),20,replace=TRUE)
df2<−data.frame(y1,y2,y3)
df2
y1 y2 y3
1 Bitter Hot Cold
2 Bitter Cold Hot
3 Bitter Bitter Cold
4 Cold Hot Bitter
5 Bitter Cold Cold
6 Cold Hot Bitter
7 Cold Cold Cold
8 Hot Cold Bitter
9 Bitter Bitter Bitter
10 Bitter Hot Bitter
11 Bitter Cold Cold
12 Bitter Bitter Hot
13 Hot Bitter Bitter
14 Cold Bitter Cold
15 Cold Bitter Bitter
16 Hot Bitter Hot
17 Bitter Cold Cold
18 Hot Cold Bitter
19 Hot Hot Cold
20 Hot Bitter Cold
Converting columns in df2 to numerical −
df2[]<−as.numeric(factor(as.matrix(df2)))
df2
y1 y2 y3
1 1 3 2
2 1 2 3
3 1 1 2
4 2 3 1
5 1 2 2
6 2 3 1
7 2 2 2
8 3 2 1
9 1 1 1
10 1 3 1
11 1 2 2
12 1 1 3
13 3 1 1
14 2 1 2
15 2 1 1
16 3 1 3
17 1 2 2
18 3 2 1
19 3 3 2
20 3 1 2
Here, first letter of the category is considered for numbering.
How to test WinRM connectivity using PowerShell?

In system admin role or as a PowerShell engineer you need to connect to many computers remotely. So as the first step, we need to test the remote connectivity by applying ping command or Test-Connection but many organizations have a stringent policy, and some of the servers ICMP packets are blocked. In
such a case you can check connectivity with WINRM.
If the WINRM is not allowed, you can ask your windows administrator to enable a firewall exception for
WINRM. WINRM is the thing that PowerShell uses it for remoting purposes. So before connecting to
remote server it is necessary to test remote WINRM connectivity with PowerShell. We need to use Test-
WS command for it.
Test-WSMan -ComputerName Test1-Win2k12
If you get the below response, then the WinRM connection is successful.
PS C:\Users\Administrator> Test-WSMan -ComputerName Test1-Win2k12
wsmid               :    http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd  
ProtocolVersion     :    http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor       :    Microsoft Corporation
ProductVersion      :    OS: 0.0.0 SP: 0.0 Stack: 3.0
If PSremoting is not enabled or WinRM is blocked by the firewall, you will get an error message.
How to open a Facebook page from an Android app using Kotlin?

This example demonstrates how to open a Facebook page from an Android app using 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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/rlMain"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="16dp"
   android:orientation="vertical">
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center_horizontal"
      android:layout_marginTop="30dp"
      android:layout_marginBottom="30dp"
      android:onClick="fbClick"
      android:text="open Facebook" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
   }
   fun fbClick(view: View) {
      startActivity(getOpenFacebookIntent());
   }
   private fun getOpenFacebookIntent(): Intent? {
      return try {
         packageManager.getPackageInfo("com.facebook.katana", 0)
         Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/426253597411506"))
      } catch (e: Exception) {
         Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/appetizerandroid"))
      }
   }
}
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="app.com.q11">
   <uses-permission android:name="android.permission.INTERNET"/>
   <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
Java Examples - Copy & Paste Image

How to read copy and paste an image using Java.
Following is the program to copy and paste an image using Java.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

public class CopyAndPasteAnImage {
   public static void main(String args[]) {

      //Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
      
      //Reading the Image from the file and storing it in to a Matrix object
      String file = "C:/opencv/logo.jpg";
      
      Mat matrix = Imgcodecs.imread(file);
      System.out.println("Image Loaded ..........");
      String file2 = "C:/opencv/logoResaved.jpg";

      //Writing the image
      Imgcodecs.imwrite(file2, matrix);
      System.out.println("Image Saved ............");
   }
}
 Print
 Add Notes
 Bookmark this page
Reverse a string in C/C++

Here is an example to reverse a string in C language,
#include<stdio.h>
#include<string.h>

int main() {
   char s[50], t;
   int i = 0, j = 0;

   printf("\nEnter the string to reverse :");
   gets(s);

   j = strlen(s) - 1;

   while (i < j) {
      t = s[i];
      s[i] = s[j];
      s[j] = t;
      i++;
      j--;
   }
   printf("\nReverse string is : %s", s);
   return (0);
}
Here is the output
Enter the string to reverse: Here is the input string.
Reverse string is : .gnirts tupni eht si ereH
In the above program, the actual code to reverse a string is present in main(). A char type array is declared char[50] which will store the input string given by user.
Then, we are calculating the length of string using library function strlen().
j = strlen(s) - 1;
Then, we are swapping the characters at position i and j. The variable i is incremented and j is decremented.
while (i < j) {
   t = s[i];
   s[i] = s[j];
   s[j] = t;
   i++;
   j--;
}
HTML | <iframe> scrolling Attribute - GeeksforGeeks

17 Sep, 2019
The HTML <iframe> scrolling Attribute is used to specify that whether the scrollbar will be displayed or not in the <Iframe> Element. Basically the scrollbar is used when the content is large than the Iframe Element.
Syntax
<iframe scrolling="auto | yes | no">
Attribute Values
auto: It has a default value. The scrollbar appears when needed.
yes: This value shows the scrollbar in the Iframe Element.
no: This value does not show the scrollbar in the Iframe Element.
Example:
<!DOCTYPE html><html>  <body>    <h1>    GeeksForGeeks    </h1>    <h2>        HTML Iframe scrolling Attribute    </h2>      <p>Content goes here</p>      <iframe src="https://ide.geeksforgeeks.org/tryit.php"             height="300"             width="400"             marginwidth="50"             scrolling="no">    </iframe>  </body>  </html>
Output:
Supported Browsers: The browsers supported by HTML <iframe> scrolling Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between save() and persist() in Hibernate

Save() and persist() both methods are used for saving object in the database. 
As per docs −
Save()  − Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
As per docs −
persist() −  Make a transient instance persistent. This operation cascades to associated instances if the association is mapped with cascade="persist". The semantics of this method are defined by JSR-220. 
1
Basic 
 It stores object in database
It also stores object in database
2
Return Type 
It return generated id and return type is serializable 
It does not return anything. Its void return type. 
3
Transaction Boundaries 
It can save object within boundaries and outside boundaries 
It can only save object within the transaction boundaries 
4.
Detached Object 
It will create a new row in the table for detached object  
It will throw persistence exception for detached object 
5.
Supported by 
It is only supported by Hibernate 
It is also supported by JPA
@Entity
public class User {
   @Id
   Integer id;
   String name;
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class SaveExample {
   public static void main(String[] args) {
      //get session factory to start transcation
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();
      User user = new User();
      user.setId(1)
      user.setName("ABCD")
      session.save(user);
      //Close resources
      tx.commit();
      sessionFactory.close();
   }
}
@Entity
public class User {
   @Id
   Integer id;
   String name;
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class PersistExample {
   public static void main(String[] args) {
      //get session factory to start transcation
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();
      User user = new User();
      user.setId(1)
      user.setName("ABCD")
      session.persist(user);
      //Close resources
      tx.commit();
      sessionFactory.close();
   }
}
Style all unvisited links with CSS

To style all unvisited links, use the CSS :link selector. You can try to run the following code to implement the :link selector:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         a:link {
            background-color: orange;
         }
      </style>
   </head>
   <body>
      <a href = "https://www.example.com">Demo Website</a>https://www.example.com/
   </body>
</html>
Implicit Parameters In Scala - GeeksforGeeks

07 Dec, 2021
Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called. In simpler terms, if no value or parameter is passed to a method or function, then the compiler will look for implicit value and pass it further as the parameter. For example, changing an integer variable to a string variable can be done by a Scala compiler rather than calling it explicitly. When implicit keyword used in the parameter scope of the function, all the parameters are marked as implicit.Note: A method can only contain one implicit keyword.
def func1(implicit x : Int) // x is implicitdef func2(implicit x : Int, y : Int) // x and y both are implicitdef func3 (x : Int)(implicit y : Int) // only y is implicit  
Example 1:
Scala
object Main{          def main(args: Array[String])     {        val value = 10        implicit val multiplier = 3        def multiply(implicit by: Int) = value * by                  // Implicit parameter will be passed here        val result = multiply                   // It will print 30 as a result        println(result)               }}
30
Example 2:
Scala
object Main{          def main(args: Array[String])    {        val message = "hello "        implicit val name = "world!"        def disp(implicit nm : String) = message + nm                  // Implicit parameter will be passed here        val result = disp                  // Implicit parameters will not be passed        val result2 = disp("GFG!")         println("With Implicit parameters:")        println(result)         println("Without Implicit parameters:")        println(result2)         }}
With Implicit parameters:
hello world!
Without Implicit parameters:
hello GFG!

surindertarika1234
Picked
Scala
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
How to get the first element of List in Scala
Scala Lists
Class and Object in Scala
Operators in Scala
Scala String replace() method with example
Inheritance in Scala
Scala String substring() method with example
Break statement in Scala
Count the frequency of a value in a DataFrame column in Pandas

To count the frequency of a value in a DataFrame column in Pandas, we can use df.groupby(column name).size() method.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Print the input DataFrame, df.
Print frequency of column, x.
Print frequency of column, x.
Print frequency of column, y.
Print frequency of column, y.
Print frequency of column, z.
Print frequency of column, z.
 Live Demo
import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 5],
      "y": [4, 10, 5, 10],
      "z": [1, 1, 5, 1]
   }
)

print "Input DataFrame is:\n", df
col = "x"
count = df.groupby('x').size()
print "Frequency of values in column ", col, "is:\n", count

col = "y"
count = df.groupby('y').size()
print "Frequency of values in column ", col, "is:\n", count

col = "z"
count = df.groupby('z').size()
print "Frequency of values in column ", col, "is:\n", count
Input DataFrame is:
   x  y  z
0  5  4  1
1  2 10  1
2  1  5  5
3 5  10  1

Frequency of values in column x is:
   x
1  1
2  1
5  2
dtype: int64

Frequency of values in column y is:
   y
4  1
5  1
10 2
dtype: int64

Frequency of values in column z is:
   z
1  3
5  1
dtype: int64
Check if a user exists in MySQL and drop it?

To check how many users are present in MySQL, use MySQL.user table. The syntax is as follows to check how many users are present.
mysql> SELECT User FROM mysql.user;
The following output displays the users −
+------------------+
| User             |
+------------------+
| Mac              |
| Manish           |
| mysql.infoschema |
| mysql.session    |
| mysql.sys        |
| root             |
| Smith            |
| am               |
+------------------+
8 rows in set (0.00 sec)
Now you can check and drop the user if it exist.
The syntax is as follows to drop a user from MySQL −
DROP USER IF EXISTS yourUserName;
Now you can implement the above syntax in order to drop if the user exists. I am applying drop on user ‘Mac’. The query is as follows.
mysql> DROP USER IF EXISTS Mac;
Query OK, 0 rows affected (0.11 sec)
Check whether the user ‘Mac’ has been deleted or not. The query is as follows −
mysql> SELECT User FROM mysql.user;
The following is the output that displays user ‘Mac’ successfully deleted −
+------------------+
| User             |
+------------------+
| Manish           |
| mysql.infoschema |
| mysql.session    |
| mysql.sys        |
| root             |
| Smith            |
| am               |
+------------------+
7 rows in set (0.00 sec)
Apache Pig - REPLACE()

This function is used to replace all the characters in a given string with the new characters.
Given below is the syntax of the REPLACE() function. This function accepts three parameters, namely,
string − The string that is to be replaced. If we want to replace the string within a relation, we have to pass the column name the string belongs to.
string − The string that is to be replaced. If we want to replace the string within a relation, we have to pass the column name the string belongs to.
regEXP − Here we have to pass the string/regular expression we want to replace.
regEXP − Here we have to pass the string/regular expression we want to replace.
newChar − Here we have to pass the new value of the string.
newChar − Here we have to pass the new value of the string.
grunt> REPLACE(string, 'regExp', 'newChar');

Assume that there is a file named emp.txt in the HDFS directory /pig_data/ as shown below. This file contains the employee details such as id, name, age, and city.
emp.txt
001,Robin,22,newyork
002,BOB,23,Kolkata
003,Maya,23,Tokyo
004,Sara,25,London 
005,David,23,Bhuwaneshwar 
006,Maggy,22,Chennai
007,Robert,22,newyork 
008,Syam,23,Kolkata
009,Mary,25,Tokyo 
010,Saran,25,London 
011,Stacy,25,Bhuwaneshwar 
012,Kelly,22,Chennai

And, we have loaded this file into Pig with a relation named emp_data as shown below.
grunt> emp_data = LOAD 'hdfs://localhost:9000/pig_data/emp1.txt' USING PigStorage(',')
   as (id:int, name:chararray, age:int, city:chararray);
Following is an example of the REPLACE() function. In this example, we have replaced the name of the city Bhuwaneshwar with a shorter form Bhuw.
grunt> replace_data = FOREACH emp_data GENERATE (id,city),REPLACE(city,'Bhuwaneshwar','Bhuw');
The above statement replaces the string 'Bhuwaneshwar' with 'Bhuw' in the column named city in the emp_data relation and returns the result. This result is stored in the relation named replace_data. Verify the content of the relation replace_data using the Dump operator as shown below.
grunt> Dump replace_data;
 
((1,newyork),newyork)
((2,Kolkata),Kolkata)
((3,Tokyo),Tokyo)
((4,London),London) 
((5,Bhuwaneshwar),Bhuw)
((6,Chennai),Chennai)
((7,newyork),newyork) 
((8,Kolkata),Kolkata)
((9,Tokyo),Tokyo) 
((10,London),London) 
((11,Bhuwaneshwar),Bhuw) 
((12,Chennai),Chennai) 


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Cypress - Hidden Elements

Cypress can handle the hidden elements. There are occasions, when the submenus get displayed only on hovering over the main menu. These submenus are initially made hidden with the Cascading Style Sheets (CSS) property display:none.
For handling the hidden elements, Cypress takes the help of the jQuery method show. It has to be invoked with the help of the Cypress command (invoke['show']).
For example, on hovering over the Sign in menu, the Sign in button gets displayed, as
shown below −
On moving the mouse out of the Sign in menu, the Sign in button gets hidden, as displayed below −
The implementation of the hidden elements with jQuery show method is as follows −
describe('Tutorialspoint Test', function () {
   // test case
   it('Scenario 1', function (){
      // launch URL
      cy.visit("https://www.amazon.com/");
      // show hidden element with invoke
      cy.get('#nav-flyout-ya-signin').invoke('show');
      //click hidden element
      cy.contains('Sign').click();
   });
});
Execution Results
The output is given below −
describe('Tutorialspoint Test', function () {
   // test case
   it('Scenario 1', function (){
      // launch URL
      cy.visit("https://www.amazon.com/");
      // show hidden element with invoke
      cy.get('#nav-flyout-ya-signin').invoke('show');
      //click hidden element
      cy.contains('Sign').click();
   });
});
The output is given below −
The execution logs show the hidden elements represented by an icon at the right of the steps.
Cypress has another technique for handling hidden elements.
For example, to click a hidden element we can use the Cypress command click and pass the option {force : true} as a parameter to it - click({ force: true }).
This modifies the hidden characteristics of the hidden element and we can click it.
Given below is the implementation with click having option in Cypress −
describe('Tutorialspoint Test', function () {
   // test case
   it('Scenario 1', function (){
      // launch URL
      cy.visit("https://www.amazon.com/");
      //click hidden element
      cy.contains('Sign').click({force:true});
   });
});
Execution Results
The output is mentioned below −
The execution logs show the hidden element clicked (Sign in) and we are navigated to the next page.

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
Matplotlib figure to image as a numpy array

We can use the following steps to convert a figure into a numpy array −
Read a figure from a directory; convert it into numpy array.
Read a figure from a directory; convert it into numpy array.
Use imshow() method to display the image.
Use imshow() method to display the image.
Use show() method to display it.
Use show() method to display it.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
im = plt.imread("bird.jpg")
print("Numpy array of the image is: ", im)
im = plt.imshow(im)
plt.show()
When we execute the code, it will show "bird.jpg" in a plot and show its numpy array on the console.
Numpy array of the image is: [[[162 162 170]
[162 162 170]
[160 163 170]
...
[ 97 98 92]
[ 98 100 95]
[ 94 96 91]]

[[159 159 167]
[159 159 167]
[157 160 167]
...
[ 94 95 89]
[ 95 97 92]
[ 92 94 89]]

[[157 158 163]
[157 158 163]
[154 157 164]
...
[ 93 94 89]
[ 95 95 93]
[ 95 95 93]]

...

[[163 163 165]
[163 163 165]
[164 164 164]
...
[187 165 151]
[158 131 112]
[133 105 84]]

[[163 163 165]
[163 163 165]
[163 163 163]
...
[160 134 117]
[143 112 92]
[127 96 75]]

[[164 164 166]
[163 163 165]
[163 163 163]
...
[145 116 98]
[129 98 78]
[124 92 71]]]
Remove Duplicates from Sorted Array in Python

Suppose we have a sorted list A. We have to return the length of the array after removing all duplicate entries. We have to perform this in O(1) extra space. So we have to do the operation in-place.
For an example, suppose A = [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5, 5, 6] Then the output will be 6, as there are six distinct elements.
To solve this, follow these steps −
If the list is empty, return 0
otherwise, initially take prev = first element of A. And define length = 0
for i := 1 to n-1, doif A[i] is not the same as prev, thenlength := length + 1prev := A[i]
if A[i] is not the same as prev, thenlength := length + 1prev := A[i]
length := length + 1
prev := A[i]
return length
Let us see the implementation to get a better understanding
 Live Demo
class Solution(object):
   def removeDuplicates(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      if len(nums) == 0:
         return 0
      length = 1
      previous = nums[0]
      index = 1
      for i in range(1,len(nums)):
         if nums[i] != previous:
            length += 1
            previous = nums[i]
            nums[index] = nums[i]
            index+=1
      return length
input_list = [1,1,2,2,2,3,3,3,3,4,5,5,5,6]
ob1 = Solution()
print(ob1.removeDuplicates(input_list))
[1,1,2,2,2,3,3,3,3,4,5,5,5,6]
6
How to convert Python datetime to epoch with strftime?

To convert python datetime to epoch with strftime you'd need to provide the strftime function with a formatting string that contains the code for formatting the date as seconds since epoch. The %s directive is used for this purpose. 
import datetime
timestamp = datetime.datetime(2017, 12, 1, 0, 0).strftime('%s')
print(timestamp)
This will give the output −
1445212800
If you're on Python 3.3+, you can simply use the timestamp function to get the time since epoch.
import datetime
timestamp = datetime.datetime(2017, 12, 1, 0, 0).timestamp()
print(timestamp)
This will give the output −
1445212800
How to read a HTTP header using JSP?

Following is the example which uses getHeaderNames() method of HttpServletRequest to read the HTTP header information. This method returns an Enumeration that contains the header information associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner. We will use the hasMoreElements() method to determine when to stop and the nextElement() method to get the name of each parameter name.
<%@ page import = "java.io.*,java.util.*" %>

<html>
   <head>
      <title>HTTP Header Request Example</title>
   </head>
   <body>
      <center>
         <h2>HTTP Header Request Example</h2>
         <table width = "100%" border = "1" align = "center">
            <tr bgcolor = "#949494">
               <th>Header Name</th>
               <th>Header Value(s)</th>
            </tr>
            <%
               Enumeration headerNames = request.getHeaderNames();
               while(headerNames.hasMoreElements()) {
                  String paramName = (String)headerNames.nextElement();
                  out.print("<tr><td>" + paramName + "</td>\n");
                  String paramValue = request.getHeader(paramName);
                  out.println("<td> " + paramValue + "</td></tr>\n");
               }
            %>
         </table>
      </center>
   </body>
</html>
Let us now put the above code in main.jsp and try to access it.
Remove elements from singly linked list in JavaScript

Suppose, we have a singly linked list like this −
const list = {
   value: 1,
   next: {
      value: 2,
      next: {
         value: 3,
         next: {
            value: 4,
            next: {
               value: 5,
               next: {
                  value: 6,
                     next: {
                        value: 7,
                        next: null
                     }
                  }
               }
            }
         }
      }
};
We are required to write a JavaScript function that takes in one such list as the first argument and a number as the second argument.
The function should search whether there exists a node with that value in the list, if it does, the function should remove the node from the list.
The code for this will be −
const list = {
   value: 1,
   next: {
      value: 2,
      next: {
         value: 3,
         next: {
            value: 4,
            next: {
               value: 5,
               next: {
                  value: 6,
                  next: {
                     value: 7,
                     next: null
                  }
               }
            }
         }
      }
   }
};
const recursiveTransform = (list = {}) => {
   if(list && list['next']){
      list['value'] = list['next']['value'];
      list['next'] = list['next']['next'];
      return recursiveTransform(list['next']);
   }else{
      return true;
   };
}
const removeNode = (list = {}, val, curr = list) => {
   // end reached and item not found
   if(!list){
      return false;
   }
   if(list['value'] !== val){
      return removeNode(list['next'], val, list);
   };
   return recursiveTransform(list);
};
console.log(removeNode(list, 3));
console.log(JSON.stringify(list, undefined, 4));
And the output in the console will be −
true
{
   "value": 1,
   "next": {
      "value": 2,
      "next": {
         "value": 4,
         "next": {
            "value": 6,
            "next": {
               "value": 7,
               "next": null
            }
         }
      }
   }
}
How to find the distinct subsets from a given array by backtracking using C#?

Distinct subsets problem gives us the different combination from the given array.
When the target is 2 then from the array, we take all the combination that corresponds to number 2, When the target is three then from the array, we take all the combination that corresponds to count 3. In the below example the array is [1,2,3] and the target is 2. So, we take all the combinations the corresponds to number 2 “1,2 “, “2,3”,”1,3””.
 Live Demo
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication{
   public class BackTracking{
      public void Subsets(int[] array){
         List<int> currentList = new List<int>();
         List<string> results = new List<string>();
         BackTrackkingCombination(array, 2, 0, currentList, results);
         foreach (var item in results){
            StringBuilder s = new StringBuilder();
            foreach (var item1 in item){
               s.Append(item1.ToString());
            }
            Console.WriteLine(s);
            s = null;
         }
      }
      public void BackTrackkingCombination(int[] array, int size, int startIndex, List<int> currentList, List<string> results){
         if (currentList.Count == size){
            StringBuilder s = new StringBuilder();
            foreach (var item in currentList){
               s.Append(item);
            }
            results.Add(s.ToString());
            return;
         }
         for (int i = startIndex; i < array.Length; i++){
            currentList.Add(array[i]);
            BackTrackkingCombination(array, size, i + 1, currentList, results); ;
            currentList.Remove(array[i]);
         }
      }
   }
   class Program{
      static void Main(string[] args){
         BackTracking b = new BackTracking();
         int[] arrs = { 1, 2, 3 };
         b.Subsets(arrs);
      }
   }
}
12
13
23