code-rag-bench/online-tutorials huggingface dataset:
Can we change the access specifier from (public) while implementing methods from interface in Java?

An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
To create an object of this type you need to implement this interface, provide a body for all the abstract methods of the interface and obtain the object of the implementing class.
All the methods of the interface are public and abstract and, we will define an interface using the interface keyword as shown below −
interface MyInterface{
   public void display();
   public void setName(String name);
   public void setAge(int age);
}
While implementing/overriding methods the method in the child/implementing class must not have higher access restrictions than the one in the superclass. If you try to do so it raises a compile-time exception.
Since the public is the highest visibility or lowest access restriction and the methods of an interface are public by default, you cannot change the modifier, doing so implies increasing the access restriction, which is not allowed and generates a compile-time exception.
In the following example we are inheriting a method from an interface by removing the access specifier “public”.
 Live Demo
interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   public static int num = 10000;
   void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      MyInterface.num = 200;
   }
}
Compile-time error −
On compiling, the above program generates the following compile-time error.
InterfaceExample.java:7: error: display() in InterfaceExample cannot implement display() in MyInterface
   void display() {
         ^
attempting to assign weaker access privileges; was public
InterfaceExample.java:14: error: cannot assign a value to final variable num
   MyInterface.num = 200;
               ^
2 errors
How to remove an element from DOM using jQuery?

The empty() method removes all child nodes from the set of matched elements whereas the method remove() method removes all matched elements from the DOM.
To remove an element, use the remove() method.
You can try to run the following code to learn how to remove an element from DOM using jQuery:
Live Demo
<html>
   <head>
      <title>jQuery remove() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).remove( );
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below:</p>
      <span id = "result"> </span>
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>
Accessing the internet using the urllib.request module in Python

We use the urllib.request module in Python to access and open URLs, which most often use the HTTP protocol.
The interface used is also very simple for beginners to use and learn; it uses the urlopen function which can fetch various URLs using a variety of different protocols.
You will get a better understanding of what we are working with, once we start using its various functionalities. So, let us get started.
The urllib library comes packaged along with Python. So, you do not need to install it separately, but in case you want to add it to your environment and you don’t already have it, you can install it using the pip package manger.
Launch your terminal and use the below code,
pip install urllib
Once you have it installed, you can import the right modules and start writing your script.
We most often use urllib.request to open and read data, or the source code of the page. This becomes especially useful if you are trying to retrieve data from an API. For example,
import urllib.request
request_url = urllib.request.urlopen('https://official−joke−api.appspot.com/random_ten')
The above lines of code will open the joke api and read its data.
Suppose you want to print out its content, you can use −
print(request_url.read())
Note − This would print out value in byte format. If you want plain text, use decode function.
print(request_url.read().decode())
You even save the data from the API and then parse it later using RegEx to obtain only the essential data.
import urllib.request
data = urllib.request.urlopen('https://official−joke−api.appspot.com/random_ten')
data = data.read().decode()
print(data)
file = open("content.txt", "w+")
file.write(data)
file.close()
Note − You can access URLs with various protocols, including FTP, HTTPS, etc. The urlopen functions the exact same way for all the different protocols.
If you are working with Common Gateway Interface, you might want to send data to a URL. This is similarly how it works with HTTP where it sends out POST requests.
You can achieve this using the urllib.request along with the urllib.parse modules.
Let us import the modules first.
import urllib.parse
import urllib.request
url = 'http://www.google.com/cgi-bin/register.cgi'
values = {'name' : 'S Vijay Balaji', language' : 'Python' }
data = urllib.parse.urlencode(values)
data = data.encode('ascii')
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
   the_page = response.read()
This should then print out the source code from the URL provided.
The urllib.request module is very useful considering that we can retrieve internet resources and obtain data from them.
It comes in handy when parsing data from an API or reading through source code of a web page to scrape its content.
Project where urllib.request was used to extract data from various APIs − https://github.com/SVijayB/Steam_WebScraper.
There are various other functions from the urllib.request module. If you are curious and want to learn more, you can go through their official documentation at− https://docs.python.org/3/library/urllib.request.html.
When can I use a forward declaration in C/C++?

In C++ the forward declaration lets the code following the declaration know that there is are classes
with the name Person. This satisfies the compiler when it sees these names used. Later the linker
will find the definition of the classes.
Class Person;
void myFunc(Person p1) {
   // ...
}
Class Person {
   // Class definition here
};
So in this case when compiler encounters myFunc, it'll know that it is going to encounter this class
somewhere down in the code. This can be used in cases where code using the class is
placed/included before the code containing the class definition.
How to format a number as currency using CSS ? - GeeksforGeeks

03 Jun, 2020
Given a number and the task is to format the number of an HTML element as currency using CSS and a little bit of JavaScript. It is not possible to complete the task with pure CSS. A bit of JavaScript is needed for the parsing of the number to add the commas.
Approach: In the code, the CSS class currSign adds the currency sign (like ‘$’) before the number. The JavaScript function toLocaleString() returns a string with a language-sensitive representation of the number.
Example:
<!DOCTYPE html><html>  <head>    <meta name="viewport" content=        "width=device-width, initial-scale=1">      <!-- CSS style to add the sign of the          currency before the number -->    <style>        .currSign:before {            content: '$';        }    </style></head>  <body>    <!-- Some unformatted numbers -->    <div class="myDIV">88123.45</div>    <div class="myDIV">75123.45</div>    <div class="myDIV">789415123.45</div>    <div class="myDIV">123</div>      <!-- Javascript code to format the         number as per the locale -->    <script>        let x = document.querySelectorAll(".myDIV");        for (let i = 0, len = x.length; i < len; i++) {            let num = Number(x[i].innerHTML)                      .toLocaleString('en');            x[i].innerHTML = num;            x[i].classList.add("currSign");        }    </script></body>  </html>
Output:
CSS-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
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 ?
What is a pure function in JavaScript?

A pure function is a deterministic function. This means when a same input is passed every time, the function will return same output. In mathematical terms it is nothing but a well defined function.
A pure function will have the following properties
It depends only on its own arguments.
It depends only on its own arguments.
It wont try to change variables out of its scope.
It wont try to change variables out of its scope.
It doesn't produce any side effects.
It doesn't produce any side effects.
The following example is not a pure function because rather than depending on its own variables, the function is depending on variables(val1 and val2) that are out of its scope.
Live Demo
<html>
<body>
<script>
   let val1 = 6;
   let val2 = 4;
   function pure() {
      return val1 * val2;
   }
   document.write(pure());
</script>
</body>
</html>
24
In the following example the function, even though depending on its own arguments, is also depending on some outside variables(val). So it is not a pure function. 
Live Demo
<html>
<body>
<script>
   function pure(arg) {
      let val = 100;
      return val* arg;
   }
   document.write(pure(2));
</script>
</body>
</html>
200
The following example displays a pure function because there are no outside variables involved while the function is performing its tasks. The function returns the same output when a same parameter is passed to it 
Live Demo
<html>
<body>
   <script>
      function pure(arg) {
         return 4 * arg;
      }
      document.write(pure(2));
   </script>
</body>
</html>
8
Creating Java Hello World Program

Let us look at a simple code that will print the words Hello World.
Live Demo
public class MyFirstJavaProgram {
   /* This is my first java program.
      * This will print 'Hello World' as the output
   */
   public static void main(String []args) {
      System.out.println("Hello World");
      // prints Hello World
   }
}
Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −
Open notepad and add the code as above.
Save the file as: MyFirstJavaProgram.java.
Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have a different meaning in Java.
Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.
JSON.simple - Escaping Special Characters

The following characters are reserved characters and can not be used in JSON and must be properly escaped to be used in strings.
Backspace to be replaced with \b
Backspace to be replaced with \b
Form feed to be replaced with \f
Form feed to be replaced with \f
Newline to be replaced with \n
Newline to be replaced with \n
Carriage return to be replaced with \r
Carriage return to be replaced with \r
Tab to be replaced with \t
Tab to be replaced with \t
Double quote to be replaced with \"
Double quote to be replaced with \"
Backslash to be replaced with \\
Backslash to be replaced with \\
JSONObject.escape() method can be used to escape such reserved keywords in a JSON String. Following is the example −
import org.json.simple.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      JSONObject jsonObject = new JSONObject();
      String text = "Text with special character /\"\'\b\f\t\r\n.";
      System.out.println(text);
      System.out.println("After escaping.");
      text = jsonObject.escape(text);
      System.out.println(text);
   }
}
Text with special character /"'
.
After escaping.
Text with special character \/\"'\b\f\t\r\n.


    20 Lectures 
     1 hours 

 Laurence Svekis

    16 Lectures 
     1 hours 

 Laurence Svekis

    10 Lectures 
     1 hours 

 Laurence Svekis

    23 Lectures 
     2.5 hours 

 Laurence Svekis

    9 Lectures 
     48 mins

 Nilay Mehta

    18 Lectures 
     2.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
C++ Algorithm Library - copy_n() Function

The C++ function std::algorithm::copy_n() copies first n numbers to a new location. If value of n is negative then function does nothing.
Following is the declaration for std::algorithm::copy_n() function form std::algorithm header.
template <class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);

first − Input iterators to the initial positions of the searched sequence.
first − Input iterators to the initial positions of the searched sequence.
n − Number of elements to copy.
n − Number of elements to copy.
result − Output iterator to the initial position in the new sequence.
result − Output iterator to the initial position in the new sequence.
Returns an iterator to the end of the destination range where elements have been copied.
Throws an exception if either element assignment or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear in the distance between first to last.
The following example shows the usage of std::algorithm::copy_n() function.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(void) {
   vector<int> v1 = {1, 2, 3, 4, 5};
   vector<int> v2(3);

   copy_n(v1.begin(), 3, v2.begin());

   cout << "Vector v2 contains following elements" << endl;

   for (auto it = v2.begin(); it != v2.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Vector v2 contains following elements
1
2
3

 Print
 Add Notes
 Bookmark this page
How to stop all instances of the process in PowerShell?

To stop running all the instances of the process in PowerShell Stop-Process command is used. For example, in the below example, we have two running instances of notepad.exe process.
PS C:\WINDOWS\system32> Get-Process notepad
PS C:\WINDOWS\system32> Get-Process notepad

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    228      13     3160      13448       0.14  15564   1 notepad
    228      14     3148      13668       0.17  22644   1 notepad
To stop all the instances of the running process, below command will be used.
Stop-Process -Name notepad

You can also pipeline the Stop-Process to end the process.
Get-Process -Name notepad | Stop-Process
To stop multiple processes, provide different process names separated by comma (,)
Get-Process SkypeApp,notepad |Stop-Process -Confirm:$false
How to check the permissions of a file using Python?

You can use os.access(path, mode) to check the file permission with modes for reading, writing and execution permissions. For example,
>>> import os
>>> os.access('my_file', os.R_OK) # Check for read access
True
>>> os.access('my_file', os.W_OK) # Check for write access
True
>>> os.access('my_file', os.X_OK) # Check for execution access
False
>>> os.access('my_file', os.F_OK) # Check for existance of file
True
You can also use os.stat to get the status of a file or a file descriptor. It is quite complex to interpret as it uses bitmasks to identify the permissions. You can read mode about it here: https://docs.python.org/3/library/os.html#os.stat
Alert Dialog box in Flutter - GeeksforGeeks

15 Feb, 2021
Alert Dialog box informs the user about the situation that requires acknowledgment. Alert Box is a prompt that takes user confirmation. The very basic use of the alert box is used when we close the app, usually, we are notified with a prompt whether you want to exit or not. That’s an alert box.
The below-added code shows how to perform alert Dialog box in flutter. I have used a button (Raised Button in flutter ) to trigger the alert dialog box. In its on the pressed property, we have to use the showDialog widget of flutter. It takes context and a builder. In builder, we provide the AlertDialog widget with title, content(Description of a title), and actions (Yes or no buttons), and our alert dialog box is ready to use.
actions: The set of actions that are displayed at the bottom of the dialog
title: The title of the dialog is displayed in a large font at the top of the dialog.
content: This gives a message/ description about the title which you have provided to the Alert Dialog box.
backgroundColor: It provides the background color to the widget which is being used in.
elevation: Elevation provided height to the widget, It gives a default shadow to the widget.
Flutter provides its own show Dialog widget which is used to show Dialog box.
Example:
Dart
import 'package:flutter/material.dart';  void main() => runApp(MyApp());  class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return MaterialApp(      home: HomePage(),    );  }}  class HomePage extends StatefulWidget {  @override  _HomePageState createState() => _HomePageState();}  class _HomePageState extends State<HomePage> {  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title: Text("GeeksForGeeks"),        backgroundColor: Colors.green,      ),      body: Container(        child: Center(          child: RaisedButton(            onPressed: () {              return showDialog(                context: context,                builder: (ctx) => AlertDialog(                  title: Text("Alert Dialog Box"),                  content: Text("You have raised a Alert Dialog Box"),                  actions: <Widget>[                    FlatButton(                      onPressed: () {                        Navigator.of(ctx).pop();                      },                      child: Text("okay"),                    ),                  ],                ),              );            },            child: Text("Show alert Dialog box"),          ),        ),      ),    );  }}
Output:
android
Flutter
Flutter UI-components
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
What is widgets in Flutter?
Flutter - Stack Widget
ListView Class in Flutter
Flutter - Flexible Widget
Flutter Tutorial
Flutter - Custom Bottom Navigation Bar
Flutter - Stack Widget
Format Dates in Flutter
Flutter - Flexible Widget
How to position text to top left position on an image with CSS

To position text to top left, use the left and top property. You can try to run the following code to position text to left position on an image −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .box {
            position: relative;
         }
         img {
            width: 100%;
            height: auto;
            opacity: 0.6;
         }
         .direction {
            position: absolute;
            top: 10px;
            left: 19px;
            font-size: 13px;
         }
      </style>
   </head>
   <body>
      <h1>Heading One</h1>
      <p>Below image has text in the top left:</p>
      <div class = "box">
         <img src = "https://www.tutorialspoint.com/python/images/python_data_science.jpg" alt = "Tutorial" width = "800" height = "400">
         <div class = "direction">Top Left Corner</div>
      </div>
   </body>
</html>
Create Three Equal Columns with Bootstrap grid Layout

To create three equal columns layout with Bootstrap Grid Layout, you can try to run the following code −
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel="stylesheet" ref="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container-fluid">
         <h2>Bootstrap Grid</h2>
         <div class = "row">
            <div class = "col-sm-4" style = "background-color:green; color: white;">Column One</div>
            <div class = "col-sm-4" style = "background-color:orange; color: white;">Column Two</div>
            <div class = "col-sm-4" style = "background-color:gray; color: white;">Column Three</div>
         </div>
      </div>
   </body>
</html>
Tryit Editor v3.7

CSS User Interface
Tryit: The outline-offset property
How to get unique elements in nested tuple in Python

When it is required to get the unique elements in a nested tuple, a nested loop and the 'set' operator can be used.
Python comes with a datatype known as 'set'. This 'set' contains elements that are unique only.
The set is useful in performing operations such as intersection, difference, union and symmetric difference.
Below is a demonstration of the same −
Live Demo
my_list_1 = [(7, 8, 0), (0 ,3, 45), (3, 2, 22), (45, 12, 9)]

print ("The list of tuple is : " )
print(my_list_1)

my_result = []
temp = set()
for inner in my_list_1:
   for elem in inner:
      if not elem in temp:
         temp.add(elem)
         my_result.append(elem)
print("The unique elements in the list of tuples are : ")
print(my_result)
The list of tuple is :
[(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)]
The unique elements in the list of tuples are :
[7, 8, 0, 3, 45, 2, 22, 12, 9]
A list of tuple is defined, and is displayed on the console.
An empty list is created, and an empty set is created.
The list is iterated through, and checked to see if it is present in the list.
If not, it is added to the list as well as the empty set.
This result is assigned to a value.
It is displayed as output on the console.
How to add a new row in a table using jQuery?

Use event delegations to include both add a new and delete a table row on a web page using jQuery.
Firstly, set a button in HTML to add new row
<button id="newbtn">
   Add new Row
</button>
Now under the button click event, set the code:
$("#newbtn").click(function () {
}
 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(){
      var x = 1;
      $("#newbtn").click(function () {
         $("table tr:first").clone().find("input").each(function () {
            $(this).val('').attr({
               'id': function (_, id) {
                  return id + x
               },
               'name': function (_, name) {
                  return name + x
               },
               'value': ''
            });
         }).end().appendTo("table");
         x++;
      });

      $(document).on('click', 'button.deletebtn', function () {
         $(this).closest('tr').remove();
         return false;
      });
   });
</script>
</head>
<body>
<table>
<tr>
<td>
<button type="button" class="deletebtn" title="Remove row">X</button>
</td>
<td>
<input type="text" id="txtTitle" name="txtTitle">
</td>
<td>
<input type="text" id="txtLink" name="txtLink">
</td>
</tr>
</table>
<button id="newbtn">Add new Row</button>
</body>
</html>
How to get dates using LocalDate.datesUntil() method in Java 9?

The LocalDate.datesUntil() method creates a stream between two local date
instances and allows us to optionally specify a step size. This method has two variations, the first one takes end date and gives a list of dates between the current date and end date whereas the second one takes a Period object as a parameter that provides a way to skip dates and stream only a select subset of the dates between start and end dates.
public Stream<LocalDate> datesUntil(LocalDate end)
public Stream<LocalDate> datesUntil(LocalDate end, Period step)
import java.time.LocalDate;
import java.time.Period;
import java.time.Month;
import java.util.stream.Stream;

public class DatesUntilMethodTest {
   public static void main(String args[]) {
      final LocalDate myBirthday = LocalDate.of(1980, Month.AUGUST, 8);
      final LocalDate christmas = LocalDate.of(1980, Month.DECEMBER, 25);

      System.out.println("Day-Stream:\n");
      final Stream<LocalDate> daysUntil = myBirthday.datesUntil(christmas);
      daysUntil.skip(50).limit(10).forEach(System.out::println);

      System.out.println("\nMonth-Stream:\n");
      final Stream monthsUntil = myBirthday.datesUntil(christmas, Period.ofMonths(1));
      monthsUntil.limit(5).forEach(System.out::println);
   }
}
Day-Stream:

1980-09-27
1980-09-28
1980-09-29
1980-09-30
1980-10-01
1980-10-02
1980-10-03
1980-10-04
1980-10-05
1980-10-06

Month-Stream:

1980-08-08
1980-09-08
1980-10-08
1980-11-08
1980-12-08
Suppressing duplicate entries in classical and ALV report in SAP ABAP

To delete adjacent duplicate entries in an internal table, you can use the below command −
DELETE ADJACENT DUPLICATE ENTRIES FROM <itab>
                     [COMPARING <f1> <f 2> ...
                         |ALL FIELDS].
Also, consider the below points −
The system deletes all adjacent duplicate entries from the internal table <itab>. Entries are duplicate if they fulfill one of the following compare criteria:
Without the COMPARING addition, the contents of the key fields of the table must be identical in both lines.
If you use the addition COMPARING <f1> <f 2> ... the contents of the specified fields <f 1 > <f 2 > ... must be identical in both lines. You can also specify a field <f i > dynamically as the contents of a field <n i > in the form (<n i >). If <n i > is empty when the statement is executed, it is ignored. You can restrict the search to partial fields by specifying offset and length.
If you use the addition COMPARING ALL FIELDS the contents of all fields of both lines must be identical.
You can use this statement to delete all duplicate entries from an internal table if the table is sorted by the specified compare criterion.
If at least one line is deleted, the system sets SY-SUBRC to 0, otherwise to 4.
DATA: BEGIN OF LINE,
COL1 TYPE I,
COL2 TYPE I,
END OF LINE.
DATA ITAB LIKE HASHED TABLE OF LINE WITH UNIQUE KEY COL1.
DO 4 TIMES.
   LINE-COL1 = SY-INDEX.
   LINE-COL2 = SY-INDEX ** 2.
INSERT LINE INTO TABLE ITAB.
ENDDO.
LINE-COL1 = 1.
DELETE TABLE ITAB: FROM LINE,
WITH TABLE KEY COL1 = 3.
LOOP AT ITAB INTO LINE.
   WRITE: / LINE-COL1, LINE-COL2.
ENDLOOP.
The output is −
2        4
4       16
The program fills a hashed table with a list of square numbers. The DELETE statement deletes the lines from the table where the key field COL1 has the contents 1 or 3.
DATA: BEGIN OF LINE,
COL1 TYPE I,
COL2 TYPE I,
END OF LINE.
DATA ITAB LIKE HASHED TABLE OF LINE WITH UNIQUE KEY COL1.
DO 4 TIMES.
  LINE-COL1 = SY-INDEX.
  LINE-COL2 = SY-INDEX ** 2.
INSERT LINE INTO TABLE ITAB.
ENDDO.
DELETE ITAB WHERE ( COL2 > 1 ) AND ( COL1 < 4 ).
LOOP AT ITAB INTO LINE.
  WRITE: / LINE-COL1, LINE-COL2.
ENDLOOP.
The output is −
1        1
4       16
The program fills a hashed table with a list of square numbers. The DELETE statement deletes the lines of the table where the content of field COL2 is greater than 1 and the content of field COL1 is less than 4.
Python | Pandas DatetimeIndex.strftime()

24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.strftime() function convert to Index using specified date_format. The function return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library.
Syntax: DatetimeIndex.strftime(date_format)
Parameters :date_format : Date format string (e.g. “%Y-%m-%d”).
Return : Index of formatted strings
Example #1: Use DatetimeIndex.strftime() function to convert the given DatetimeIndex object to the specified format.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'Q' represents quarter end frequency didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='Q',                            periods = 4, tz ='Asia/Calcutta')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to convert the given DatetimeIndex object to ('%B %d, %Y, %r') format.
# change the datetime format.didx.strftime('% B % d, % Y, % r')
Output :As we can see in the output, the function has changed the format of the DatetimeIndex object to the desired format. Example #2: Use DatetimeIndex.strftime() function to convert the given DatetimeIndex object to the specified format.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'MS' represents month start frequency didx = pd.date_range(pd.Timestamp("2000-01-15 08:00"),                              periods = 5, freq ='MS')  # Print the DatetimeIndexprint(didx)
Output :
Now we want to convert the given DatetimeIndex object to ('%B %Y, %r') format.
# change the datetime format.didx.strftime('% B % Y, % r')
Output :As we can see in the output, the function has changed the format of the DatetimeIndex object to the desired format.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to calculate log base 2 of an Integer in Java?

11 Mar, 2022
Given an integer N, the task is to calculate its log to the base 2, i.e. log2 N in Java.
Examples: 
Input: N = 2
Output: 1

Input: 1024
Output: 10
Approach: 
Math class in Java (java.lang.Math) is a library which holds the functions to calculate such values, like sin(), cos(), log() etc. But the log() method in Math class calculates the log to the base e. Hence there is no direct method in Java to calculate log to the base 2.  
But as we know that
        loga b = loge b / loge a
Therefore we can calculate log2 N indirectly as:
        log2 N = loge N / loge 2
Below is the implementation of the above approach:
Java
// Java code to Calculate log base 2 of an integer import java.io.*;import java.lang.*; class GFG {     // Function to calculate the    // log base 2 of an integer    public static int log2(int N)    {         // calculate log2 N indirectly        // using log() method        int result = (int)(Math.log(N) / Math.log(2));         return result;    }     // Driver code    public static void main(String[] args)    {         int N = 1024;         System.out.println("Log " + N + " to the base 2 = " + log2(N));    }}
Log 1024 to the base 2 = 10
 
dsairam17
kundankumardec16
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
D3.js | d3.timeDay() Function

24 Jul, 2019
The d3.timeDay() function in D3.js is used to return date in “YYYY-MM-DD” format.
Syntax:
d3.timeDay(Date);
Parameters: This function accepts a parameter “Date”.
Return Value: This function returns the given date in a specific format.
Below programs illustrate the d3.timeDay() function in D3.js:Example 1:
<!DOCTYPE html><html>  <head>    <script src=        "https://d3js.org/d3.v4.min.js">  </script></head>  <body>      <script>        // Initialising a current date        var now = new Date;          // calling d3.timeDay()        var day = d3.timeDay(now);          // Getting the date        console.log(day);    </script></body>  </html>
Output:
"2019-07-19T18:30:00.000Z"

Example 2: Below code calculates the difference between two given dates.
<!DOCTYPE html><html>  <head>    <script src=            "https://d3js.org/d3.v4.min.js">  </script></head>  <body>      <script>        // Initialising start and end date        var start = new Date(2015, 02, 01);        var end = new Date(2015, 02, 04);          // Calling the timeDay() function to        // calculate the difference between two dates        var a = d3.timeDay.count(start, end);          // Getting the calculated dates        console.log(a);    </script></body>  </html>
Output:
3

D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to increase plt.title font size in Matplotlib?

To increase plt.title font size, we can initialize a variable fontsize and can use it in the title() method's argument.
Create x and y data points using numpy.
Create x and y data points using numpy.
Use subtitle() method to place the title at the center.
Use subtitle() method to place the title at the center.
Plot the data points, x and y.
Plot the data points, x and y.
Set the title with a specified fontsize.
Set the title with a specified fontsize.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-1, 1, 10)
y = x ** 2
fontsize = 12
plt.suptitle("Quadratic Equation", fontsize=fontsize)
plt.plot(x, y)
plt.title("y=x$^{2}$", fontdict={'fontsize': fontsize})
plt.show()
DAX Logical - IFERROR function

Evaluates an expression and returns a specified value if the expression returns an error. Otherwise, returns the value of the expression itself.
IFERROR (<value>, <value_if_error>) 

value
Any value or expression.
value_if_error
Any value or expression.
The value returned by the expression, if error is not returned.
The value returned by the expression, if error is not returned.
The alternative value provided, if error is returned.
The alternative value provided, if error is returned.
You can use the function IFERROR to trap the errors returned by expressions and have meaningful values returned without abruptly stopping the evaluation.
Both value and value_if_error must be of the same data type. Hence, the column or expression used for value and the value returned for value_if_error must be of the same data type.
Both value and value_if_error must be of the same data type. Hence, the column or expression used for value and the value returned for value_if_error must be of the same data type.
If either value or value_if_error is an empty cell, IFERROR treats it as an empty string value ("").
If either value or value_if_error is an empty cell, IFERROR treats it as an empty string value ("").
= IFERROR (5/0,"Div by zero") returns Div by zero. 
= IFERROR (5/1,"Div by zero") returns 5. 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to serialize a lambda function in Java?

The Serialization is a process for writing the state of an object into a byte stream so that we can transfer it over the network. We can serialize a lambda expression if its target type and its captured arguments have serialized. However, like inner classes, the serialization of lambda expressions is strongly discouraged.
In the below example, we can serialize and deserialize a lambda function using a Function interface.
import java.io.*;
import java.util.function.Function;

interface MyInterface {
   void hello(String name);
}
class MyImpl implements MyInterface {
   public void hello(String name) {
      System.out.println("Hello " + name);
   }
}

public class SerializeDeSerializeLambdaTest {
   public static void main(String[] args) throws Exception {
      serializeAndDeserializeFunction();
   }
   private static void serializeAndDeserializeFunction() throws Exception {
      Function<String, String> fn = (Function<String, String> & Serializable) (n)
-> "Hello " + n; // serialize a lambda function
      System.out.println("Run original function: " + fn.apply("Raja"));

      String path = "./serialized-fn";
      serialize((Serializable) fn, path);
      System.out.println("Serialized function to " + path);

      Function<Strng, String> deserializedFn = (Function<String, String>) deserialize(path);
      System.out.println("Deserialized function from " + path);
      System.out.println("Run deserialized function: " + deserializedFn.apply("Raja"));
   }
   private static void serialize(Serializable obj, String outputPath) throws IOException {
      File outputFile = new File(outputPath);
      if(!outputFile.exists()) {
         outputFile.createNewFile();
      }
      try(ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(outputFile))) {
         outputStream.writeObject(obj);
      }
   }
   private static Object deserialize(String inputPath) throws IOException, ClassNotFoundException {
      File inputFile = new File(inputPath);
      try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(inputFile))) {
         return inputStream.readObject();
      }
   }
}
Run original function: Hello Raja
Serialized function to ./serialized-fn
Deserialized function from ./serialized-fn
Run deserialized function: Hello Raja
Lodash - join method

_.join(array, [separator=','])

Converts all elements in array into a string separated by separator.
array (Array) − The array to convert.
array (Array) − The array to convert.
[separator=','] (string) − The element separator.
[separator=','] (string) − The element separator.
(string) − Returns the joined string.
(string) − Returns the joined string.
var _ = require('lodash');
var list = [1, 2, 3, 4, 5, 6];

var result = _.join(list,'~')
console.log(result);
Save the above program in tester.js. Run the following command to execute this program.
\>node tester.js

1~2~3~4~5~6

 Print
 Add Notes
 Bookmark this page
Metasploit - Discovery Scans

The first phase of penetration involves scanning a network or a host to gather information and create an overview of the target machine.
Discovery Scan is basically creating an IP list in the target network, discovering services running on the machines. To do this in Metasploit, we will use the command promp which are NMAP commands incorporated in Metasploit. For more information on NMAP and its commands, go to https://nmap.org/
Now let’s see in practice how it exactly works. We started the target machine (Metasploitable) and the Windows Server 2003 machine with the IP 192.168.1.101.
Next, we will start Metasploit. Here, we are using Kali Linux. Hence, the commands will always start with nmap.
Let’s start to scan the network with range 192.168.0.0/24 and discover the machines.
As can be seen in the above screenshot, there are 5 hosts up in the network with details. Now that we found the hosts that are alive, we will try to find the OS they are running on and their background services.
We will try to attack the vulnerable machine with the IP 192.168.1.101. To do so, we will run the following command −
Nmap –sV-O –T4 192.168.1.101

–sV parameter will detect the services with their version details.
–sV parameter will detect the services with their version details.
–O is to detect the version of OS which in our case is Linux 2.6.X
–O is to detect the version of OS which in our case is Linux 2.6.X
–T4 is the time that we let the scan to finish
–T4 is the time that we let the scan to finish
You will get the following screen as an output of using the above command.
 Print
 Add Notes
 Bookmark this page
How to add a line break in an android textView?

This example demonstrates how do I add a line break in an android textView.
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">
   <TextView
      android:id="@+id/textView"
      android:layout_centerInParent="true"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:textSize="24sp"
      android:text="@string/Questions" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      textView.setTextColor(Color.RED);
   }
}
Step 4 – Open strings.xml and add the following code −
<resources>
   <string name="app_name">Sample</string>
   <string name="Questions">
      <br>
         1. What is your Favourite food? \n
      </br>
      <br>
         2. Which is your favourite sport?\n
      </br>
      <br>
         3. Whats your bucket list?
      </br>
   </string>
</resources>
Step 5 - 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.sample">
   <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 Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
R - Nonlinear Least Square

When modeling real world data for regression analysis, we observe that it is rarely the case that the equation of the model is a linear equation giving a linear graph. Most of the time, the equation of the model of real world data involves mathematical functions of higher degree like an exponent of 3 or a sin function. In such a scenario, the plot of the model gives a curve rather than a line. The goal of both linear and non-linear regression is to adjust the values of the model's parameters to find the line or curve that comes closest to your data. On finding these values we will be able to estimate the response variable with good accuracy.
In Least Square regression, we establish a regression model in which the sum of the squares of the vertical distances of different points from the regression curve is minimized. We generally start with a defined model and assume some values for the coefficients. We then apply the nls() function of R to get the more accurate values along with the confidence intervals.
The basic syntax for creating a nonlinear least square test in R is −
nls(formula, data, start)

Following is the description of the parameters used −
formula is a nonlinear model formula including variables and parameters.
formula is a nonlinear model formula including variables and parameters.
data is a data frame used to evaluate the variables in the formula.
data is a data frame used to evaluate the variables in the formula.
start is a named list or named numeric vector of starting estimates.
start is a named list or named numeric vector of starting estimates.
We will consider a nonlinear model with assumption of initial values of its coefficients. Next we will see what is the confidence intervals of these assumed values so that we can judge how well these values fir into the model.
So let's consider the below equation for this purpose −
a = b1*x^2+b2

Let's assume the initial coefficients to be 1 and 3 and fit these values into nls() function.
xvalues <- c(1.6,2.1,2,2.23,3.71,3.25,3.4,3.86,1.19,2.21)
yvalues <- c(5.19,7.43,6.94,8.11,18.75,14.88,16.06,19.12,3.21,7.58)

# Give the chart file a name.
png(file = "nls.png")


# Plot these values.
plot(xvalues,yvalues)


# Take the assumed values and fit into the model.
model <- nls(yvalues ~ b1*xvalues^2+b2,start = list(b1 = 1,b2 = 3))

# Plot the chart with new data by fitting it to a prediction from 100 data points.
new.data <- data.frame(xvalues = seq(min(xvalues),max(xvalues),len = 100))
lines(new.data$xvalues,predict(model,newdata = new.data))

# Save the file.
dev.off()

# Get the sum of the squared residuals.
print(sum(resid(model)^2))

# Get the confidence intervals on the chosen values of the coefficients.
print(confint(model))
When we execute the above code, it produces the following result −
[1] 1.081935
Waiting for profiling to be done...
       2.5%    97.5%
b1 1.137708 1.253135
b2 1.497364 2.496484

We can conclude that the value of b1 is more close to 1 while the value of b2 is more close to 2 and not 3.