code-rag-bench/online-tutorials huggingface dataset:
What is boxing and unboxing in Java?

Wrapper classes are those whose objects wraps a primitive data type within them. In the java.lang package java provides a separate class for each of the primitive data type namely Byte, Character, Double, Integer, Float, Long, Short.
Converting primitive datatype to object is called boxing.
Integer obj = new Integer ("2526");
Whereas, converting an object into corresponding primitive datatype is known as unboxing.
Live Demo
public class Sample {
   public static void main (String args[]){
      Integer obj = new Integer("2526");
      int i = obj.intValue();
      System.out.println(i);
   }
}
2526
Introduction to Sequelize in NodeJS

Sequelize follows a promise-based Node.js ORM structure for different databases like – Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. Sequelize have multiple features which makes it easy to implement and use.
Some of the main features of sequelize are as follows −
Sequelize is a third-party package.
Sequelize is a third-party package.
It uses an Object-Relational Mapping to map objects. That's why its called an ORM.
It uses an Object-Relational Mapping to map objects. That's why its called an ORM.
Sequelize supports solid transaction support along with eager and lazy loading concept.
Sequelize supports solid transaction support along with eager and lazy loading concept.
It can also perform read replication on databases.
It can also perform read replication on databases.
Sequelize follows standardization, which means it has a single schema definition in the code. Standardization makes the schema easy to read and understand along with making changes.
Sequelize follows standardization, which means it has a single schema definition in the code. Standardization makes the schema easy to read and understand along with making changes.
In sequelize, the queries are written in plain Javascript. Therefore, you don't need to learn SQL.
In sequelize, the queries are written in plain Javascript. Therefore, you don't need to learn SQL.
Before installing sequelize, please check if the Node.js server is properly initialized on the system using the following command.
Before installing sequelize, please check if the Node.js server is properly initialized on the system using the following command.
>> npm init -y
The MySQL dependency needs to be installed for sequelize. For Sequelize, you need to install mysql2 as it does not works on myql. Therefore install the mysql dependency by using the following command −
The MySQL dependency needs to be installed for sequelize. For Sequelize, you need to install mysql2 as it does not works on myql. Therefore install the mysql dependency by using the following command −
>> npm install mysql2
After installing MySQL, we will now install Sequelize by using the following command −
After installing MySQL, we will now install Sequelize by using the following command −
>> npm install sequelize
You need to add the following statement in every project to include sequelize.
const Sequelize = require('sequelize');
// Including the Sequelize module
const Sequelize = require('sequelize')

// Creating a sequelize object for DB connection
const sequelize = new Sequelize(
   'YOUR_DB_NAME',
   'YOUR_DB_USER_NAME',
   'YOUR_DB_PASSWORD', {

      dialect: 'mysql',
      // Defining the default host
      host: 'localhost'
   }
);

// Exporting the sequelize object.
// To use it in other files as well.
module.exports = sequelize
Convert key-values list to flat dictionary in Python

When it is required to convert a dictionary, that contains pairs of key values into a flat list, dictionary comprehension can be used.
It iterates through the dictionary and zips them using the ‘zip’ method.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
Below is a demonstration of the same −
 Live Demo
from itertools import product

my_dict = {'month_num' : [1, 2, 3, 4, 5, 6], 'name_of_month' : ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']}

print("The dictionary is : ")
print(my_dict)

my_result = dict(zip(my_dict['month_num'], my_dict['name_of_month']))

print("The flattened dictionary is: ")
print(my_result)
The dictionary is :
{'month_num': [1, 2, 3, 4, 5, 6], 'name_of_month': ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']}
The flattened dictionary is:
{1: 'Jan', 2: 'Feb', 3: 'March', 4: 'Apr', 5: 'May', 6: 'June'}
The required packages are imported into the environment.
The required packages are imported into the environment.
A dictionary is defined, and is displayed on the console.
A dictionary is defined, and is displayed on the console.
The ‘zip’ method is used to bind the key and value of a dictionary, and it is again converted to a dictionary.
The ‘zip’ method is used to bind the key and value of a dictionary, and it is again converted to a dictionary.
This is assigned to a variable.
This is assigned to a variable.
It is displayed as output on the console.
It is displayed as output on the console.
Convert number to list of integers in Python

As part of data manipulation in Python we may sometimes need to convert a given number into a list which contains the digits from that number. In this article we'll see the approaches to achieve this.
In the below approach we apply the str function to the given number and then convert into integer through identity function. Finally we wrap the result into a list.
 Live Demo
numA = 1342
# Given number
print("Given number : \n", numA)
res = [int(x) for x in str(numA)]
# Result
print("List of number: \n",res)
Running the above code gives us the following result −
Given number :
1342
List of number:
[1, 3, 4, 2]
We fast apply the str function to the given number. Then apply the in function repeatedly using map. Finally keep the result inside a list function.
 Live Demo
numA = 1342
# Given number
print("Given number : \n", numA)
res = list(map(int, str(numA)))
# Result
print("List of number: \n",res)
Running the above code gives us the following result −
Given number :
1342
List of number:
[1, 3, 4, 2]
HTTP - Caching

HTTP is typically used for distributed information systems, where performance can be improved by the use of response caches. The HTTP/1.1 protocol includes a number of elements intended to make caching work.
The goal of caching in HTTP/1.1 is to eliminate the need to send requests in many cases, and to eliminate the need to send full responses in many other cases. 
The basic cache mechanisms in HTTP/1.1 are implicit directives to caches where server-specifies expiration times and validators. We use the Cache-Control header for this purpose.
The Cache-Control header allows a client or server to transmit a variety of directives in either requests or responses. These directives typically override the default caching algorithms. The caching directives are specified in a comma-separated list. For example:
Cache-control: no-cache

The following cache request directives can be used by the client in its HTTP request:
A cache must not use the response to satisfy a subsequent request without successful revalidation with the origin server.
The cache should not store anything about the client request or server response.
Indicates that the client is willing to accept a response whose age is not greater than the specified time in seconds.
Indicates that the client is willing to accept a response that has exceeded its expiration time. If seconds are given, it must not be expired by more than that time.
Indicates that the client is willing to accept a response whose freshness lifetime is not less than its current age plus the specified time in seconds.
Does not convert the entity-body.
Does not retrieve new data. The cache can send a document only if it is in the cache, and should not contact the origin-server to see if a newer copy exists.
The following cache response directives can be used by the server in its HTTP response:
Indicates that the response may be cached by any cache.
Indicates that all or part of the response message is intended for a single user and must not be cached by a shared cache. 
A cache must not use the response to satisfy a subsequent request without successful re-validation with the origin server.
The cache should not store anything about the client request or server response.
Does not convert the entity-body.
The cache must verify the status of stale documents before using it and expired ones should not be used.
The proxy-revalidate directive has the same meaning as the must- revalidate directive, except that it does not apply to non-shared user agent caches.
Indicates that the client is willing to accept a response whose age is not greater than the specified time in seconds.
The maximum age specified by this directive overrides the maximum age specified by either the max-age directive or the Expires header. The s-maxage directive is always ignored by a private cache.
 Print
 Add Notes
 Bookmark this page
How to handle a python exception within a loop?

We can the exception in the code by rewriting it as follows
a=[]
foo = 'redbullz'
try:
for i in foo:
a.append(i)
print a[8]
except Exception as e:
print e
We get following output
list index out of range
Process finished with exit code 0
pthread_cancel() in C

The threa_cancel() is used to cancel one particular thread by the thread id. This function sends one cancellation request to the thread for termination. The syntax of the pthread_cancel() is like below −
int pthread_cancel(pthread_t th);
Now, let us see how to cancel threads using this function.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
int count = 0;
pthread_t sample_thread;
void* thread_one_func(void* p) {
   while (1) {
      printf("This is thread 1\n");
      sleep(1); // wait for 1 seconds
      count++;
      if (count == 5) {
         //if the counter is 5, then request to cancel thread two and exit from current thread
         pthread_cancel(sample_thread);
         pthread_exit(NULL);
      }
   }
}
void* thread_two_func(void* p) {
   sample_thread = pthread_self(); //store the id of thread 2
   while (1) {
      printf("This is thread 2\n");
      sleep(2); // wit for 2 seconds
   }
}
main() {
   pthread_t t1, t2;
   //create two threads
   pthread_create(&t1, NULL, thread_one_func, NULL);
   pthread_create(&t2, NULL, thread_two_func, NULL);
   //wait for completing threads
   pthread_join(t1, NULL);
   pthread_join(t2, NULL);
}
This is thread 2
This is thread 1
This is thread 1
This is thread 2
This is thread 1
This is thread 1
This is thread 1
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
Octal literals in C - GeeksforGeeks

19 Aug, 2018
When we initialize a value by putting ‘0’ before a number, the number is treated as octal. For instance ’10’ is read as 10 but ‘010’ is read as 8.
Examples:
Input : 0101
Output : 65

Input : 01010
Output : 520

#include<iostream>using namespace std;int main(){      int x = 0101;     cout << x;     return 0;}
65

#include<iostream>using namespace std;int main(){      int x = 020;     cout << x;     return 0;}
16

#include<iostream>using namespace std;int main(){      int x = 090;     cout << x;     return 0;}
Output :
Compiler Error : 9 is not a valid digit in octal number.

cpp-data-types
C Language
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Substring in C++
Header files in C/C++ and its uses
cin in C++
Sorting a Map by value in C++ STL
C Program to Swap two Numbers
Program to print ASCII Value of a character
org.json - JSONObject

JSONObject class is a unordered collection of key-value pairs. It provides methods to access values by key and to put values. Following types are supported −
Boolean
Boolean
JSONArray
JSONArray
JSONObject
JSONObject
Number
Number
String
String
JSONObject.NULL object
JSONObject.NULL object
import org.json.JSONArray;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", new Double(1000.21));
      jsonObject.put("Active", new Boolean(true));
      jsonObject.put("Other Details", JSONObject.NULL);

      JSONArray list = new JSONArray();
      list.put("foo");
      list.put(new Integer(100));
      jsonObject.put("list",list);
      System.out.println(jsonObject);
   }
}
{"Active":true,"Other Details":null,"ID":1,"Fees":1000.21,"list":["foo",100],"Name":"Robert"}


    18 Lectures 
     1.5 hours 

 Dr. Saatya Prasad

    107 Lectures 
     13.5 hours 

 Arnab Chakraborty

    75 Lectures 
     5 hours 

 Revathi Ramachandran

    14 Lectures 
     44 mins

 Zach Miller

    12 Lectures 
     54 mins

 Prof. Paul Cline, Ed.D

    54 Lectures 
     4 hours 

 Gilad James, PhD
 Print
 Add Notes
 Bookmark this page
Ethical Hacking - TCP/IP Hijacking

TCP/IP Hijacking is when an authorized user gains access to a genuine network connection of another user. It is done in order to bypass the password authentication which is normally the start of a session.
In theory, a TCP/IP connection is established as shown below −
To hijack this connection, there are two possibilities −
Find the seq which is a number that increases by 1, but there is no chance to predict it.
Find the seq which is a number that increases by 1, but there is no chance to predict it.
The second possibility is to use the Man-in-the-Middle attack which, in simple words, is a type of network sniffing. For sniffing, we use tools like Wireshark or Ethercap.
The second possibility is to use the Man-in-the-Middle attack which, in simple words, is a type of network sniffing. For sniffing, we use tools like Wireshark or Ethercap.
An attacker monitors the data transmission over a network and discovers the IP’s of two devices that participate in a connection.
When the hacker discovers the IP of one of the users, he can put down the connection of the other user by DoS attack and then resume communication by spoofing the IP of the disconnected user.
In practice, one of the best TCP/IP hijack tools is Shijack. It is developed using Python language and you can download it from the following link − https://packetstormsecurity.com/sniffers/shijack.tgz
Here is an example of a Shijack command −
root:/home/root/hijack# ./shijack eth0 192.168.0.100 53517 192.168.0.200 23

Here, we are trying to hijack a Telnet connection between the two hosts.
Hunt is another popular tool that you can use to hijack a TCP/IP connection. It can be downloaded from − https://packetstormsecurity.com/sniffers/hunt/
All unencrypted sessions are vulnerable to TCP/IP session hijacking, so you should be using encrypted protocols as much as possible. Or, you should use double authentication techniques to keep the session secured.

    36 Lectures 
     5 hours 

 Sharad Kumar

    31 Lectures 
     3.5 hours 

 Abhilash Nelson

    22 Lectures 
     3 hours 

 Blair Cook

    74 Lectures 
     4.5 hours 

 199courses

    75 Lectures 
     4.5 hours 

 199courses

    148 Lectures 
     28.5 hours 

 Joseph Delgadillo
 Print
 Add Notes
 Bookmark this page
How to plot a function with ggplot2 in R?

Plotting a function is very easy with curve function but we can do it with ggplot2 as well. Since ggplot2 provides a better-looking plot, it is common to use it for plotting instead of other plotting functions. To plot a function, we should specify the function under stat_function in ggplot.
Consider the below data frame −
> x<-1:10
> df<-data.frame(x)
Loading ggplot2 package −
> library(ggplot2)
Plotting of functions is as shown below:
> ggplot(df,aes(x))+
+ stat_function(fun=function(x) log(x))
> ggplot(df,aes(x))+
+ stat_function(fun=function(x) log(x)/x)
> ggplot(df,aes(x))+
+ stat_function(fun=function(x) log(x)/(x-3))
> ggplot(df,aes(x))+
+ stat_function(fun=function(x) (exp(x)^2)*2)
Ruby | Array intersection operation - GeeksforGeeks

07 Jan, 2020
Array#&() is a Array class method which performs set intersection operation on the arrays. And returns the common of the two arrays.
Syntax: Array.&()
Parameter: Arrays for performing the intersection operation.
Return: Common elements from both the arrays.
Example #1 :
# Ruby code for &() method# showing intersection operation   # declaration of arraya = [18, 22, 33, 4, 5, 6]   # declaration of arrayb = [5, 4, 22, 1, 88, 9]   # declaration of arrayc = [18, 22, 33, 40, 50, 6]   # a intersecting bputs "intersection of a and b : #{a & b}\n\n"   # a intersecting cputs "intersection of a and c : #{a & c}\n\n"   # b intersecting cputs "intersection of b and c : #{b & c}\n\n"
Output :
intersection of a and b : [22, 4, 5]

intersection of a and c : [18, 22, 33, 6]

intersection of b and c : [22]

Example #2 :
# Ruby code for &() method# showing intersection operation   # declaration of arraya = ["abc", "xyz", "dog"]   # declaration of arrayb = ["cow", "cat", "dog"]   # declaration of arrayc = ["cat", "1", "dog"]   # a intersecting bputs "intersection of a and b : #{a & b}\n\n"   # a intersecting cputs "intersection of a and c : #{a & c}\n\n"   # b intersecting cputs "intersection of b and c : #{b & c}\n\n"
Output :
intersection of a and b : ["dog"]

intersection of a and c : ["dog"]

intersection of b and c : ["cat", "dog"]
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Array select() function
Ruby | Case Statement
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Data Types
Java Examples - Merge two arrays

How to merge two arrays ?
This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
   public static void main(String args[]) {
      String a[] = { "A", "E", "I" };
      String b[] = { "O", "U" };
      List list = new ArrayList(Arrays.asList(a));
      list.addAll(Arrays.asList(b));
      Object[] c = list.toArray();
      System.out.println(Arrays.toString(c));
   }
}
The above code sample will produce the following result.
[A, E, I, O, U]

Another sample example of Arrays Merge.
public class HelloWorld {
   public static void main(String[] args) {
      int[]a = {1,2,3,4};
      int[]b = {4,16,1,2,3,22};
      int[]c = new int[a.length+b.length];
      int count = 0;
      
      for(int i = 0; i < a.length; i++) { 
         c[i] = a[i];
         count++;
      } 
      for(int j = 0; j < b.length;j++) { 
         c[count++] = b[j];
      } 
      for(int i = 0;i < c.length;i++) System.out.print(c[i]+" ");
   } 
}
The above code sample will produce the following result.
1,2,3,4,4,16,1,2,3,22

 Print
 Add Notes
 Bookmark this page
Create a sticky navbar with CSS

To create a sticky navbar, use the position: sticky; property. You can try to run the following code to create a sticky navbar,
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         ul {
            list-style-type: none;
            position: sticky;
            overflow: hidden;
            top: 0;
            width: 100%;
         }
         li {
            float: left;
            border-right: 1px solid white;
         }
         li a {
            display: block;
            padding: 8px;
            background-color: orange;
         }
         li:last-child {
            border-right: none;
         }
         div {
            padding:5px;
            margin-top:5px;
            background-color:white;
            height:1000px;
         }
      </style>
   </head>

   <body>
      <ul>
         <li><a href = "#home">Home</a></li>
         <li><a href = "#news">News</a></li>
         <li><a href = "#contact">Contact</a></li>
         <li><a href = "#about">About</a></li>
      </ul>
      <div>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
         <p>Adding demo text to check fixed menu.</p>
      </div>
   </body>
</html>
Perl Quote-like Operators Example

There are following Quote-like operators supported by Perl language. In the following table, a {} represents any pair of delimiters you choose.
q{ }
Encloses a string with-in single quotes
Example − q{abcd} gives 'abcd'
qq{ }
Encloses a string with-in double quotes
Example − qq{abcd} gives "abcd"
qx{ }
Encloses a string with-in invert quotes
Example − qx{abcd} gives `abcd`
Try the following example to understand all the quote-like operators available in Perl. Copy and paste the following Perl program in test.pl file and execute this program.
#!/usr/local/bin/perl

$a = 10;
 
$b = q{a = $a};
print "Value of q{a = \$a} = $b\n";

$b = qq{a = $a};
print "Value of qq{a = \$a} = $b\n";

# unix command execution
$t = qx{date};
print "Value of qx{date} = $t\n";
When the above code is executed, it produces the following result −
Value of q{a = $a} = a = $a
Value of qq{a = $a} = a = 10
Value of qx{date} = Thu Feb 14 08:13:17 MST 2013


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
HTML DOM Input DatetimeLocal step Property

The HTML DOM Input DatetimeLocal step property determines the legal intervals for seconds or milliseconds.
Following is the syntax −
Returning number value
inputDatetimeLocalObject.step
Setting step attribute to a number value
inputDatetimeLocalObject.step = number
Parameter number values −
Let us see an example of Input DatetimeLocal step property −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Input DatetimeLocal step</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Datetime-Local-step</legend>
<label for="datetimeLocalSelect">Local Date Time :
<input type="datetime-local" id="datetimeLocalSelect" step="2">
</label>
<input type="button" onclick="changeStep('10')" value="Step Seconds to 10">
<input type="button" onclick="changeStep('.10')" value="Step milliseconds to .10">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
   var divDisplay = document.getElementById("divDisplay");
   var inputDatetimeLocal = document.getElementById("datetimeLocalSelect");
   function changeStep(myStep) {
      inputDatetimeLocal.step = myStep;
      if(inputDatetimeLocal.step.indexOf('.') === -1)
         divDisplay.textContent = 'Seconds step: '+inputDatetimeLocal.step;
      else
         divDisplay.textContent = 'Milli-seconds step: '+inputDatetimeLocal.step;
   }
</script>
</body>
</html>
This will produce the following output −
Clicking “Step Seconds to 10” button
Clicking “Step millseconds to .10” button −
Private and final methods in Java Programming

In Java private methods are the methods having private access modifier and are restricted to be access in the defining class only and are not visible in their child class due to which are not eligible for overridden. However, we can define a method with the same name in the child class and could access in parent class.
Like private methods final methods in Java are the methods having final non-access modifier instead of private and are again restricted to be accessed in the defining class only and are not visible in their child class due to which are not eligible for overridden. The only difference between private and final methods is that in case of final methods we even can't define a method with the same name in child class while in case of private methods we could define.
In Java as both private and final methods do not allow the overridden functionality so no use of using both modifiers together with same method.
 Live Demo
public class PrivateFinalMethods {
   private void print() {
      System.out.println("in parent print");
   }
   public static void main(String[] args) {

      PrivateFinalMethods obj = new PrivateFinalMethodsChild();
      obj.print();
      PrivateFinalMethodsChild obj1 = new PrivateFinalMethodsChild();
      obj1.print();
   }
}
class PrivateFinalMethodsChild extends PrivateFinalMethods {
   public void print(){
      System.out.println("in child print method");
   }
}
in parent print
in child print method
How to read a text file in Selenium with python?

We can read a text file in Selenium with python by first creating a txt file and having a content on it.
First of all, we need to open the file and mention the path of the location of the text file as an argument. There are multiple reading methods to perform these operations.
read() – It reads the entire content of the file.
read() – It reads the entire content of the file.
read(n) – It reads n characters of the text file.
read(n) – It reads n characters of the text file.
readline() – It reads character line by line at a time. If we need to read the first two lines, the readline() method is to be used twice.
readline() – It reads character line by line at a time. If we need to read the first two lines, the readline() method is to be used twice.
readlines() – it reads line by line and stores them in a list.
readlines() – it reads line by line and stores them in a list.
Code Implementation with read()
#open the file for read operation
f = open('pythontext.txt')
#reads the entire file content and prints in console
print(f.read())
#close the file
f.close()
Code Implementation with read(n)
#open the file for read operation
f = open('pythontext.txt')
#reads 4 characters as passed as parameter and prints in console
print(f.read(4))
#close the file
f.close()
Code Implementation with readline()
#open the file for read operation
f = open('pythontext.txt')
# reads line by line
l = f.readline()
while l!= "":
print(l)
l = f.readline()
#close the file
f.close()
Code Implementation with readlines()
#open the file for read operation
f = open('pythontext.txt')
# reads line by line and stores them in list
for l in f.readlines():
print(l)
#close the file
f.close()
How useEffect works in ReactJS ? - GeeksforGeeks

26 May, 2021
When we want to perform something after each render of component then we can use the useEffect() hook. By using this Hook, we tell React that our component needs to do something after render by passing a function. React remember the function we passed in useEffect() hook and call it later after performing the DOM updates.
By default, the useEffect hook runs after the first render and after every update. React updates the DOM by the time it runs the effects.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. 
App.js
import React, { useState, useEffect } from 'react';  function App() {      const [count, setCount] = useState(0);    useEffect(() => {    alert(`You clicked ${count} times`)  });    const handleUpdate = ()=> {    setCount (count + 1)  }      return (    <div>        <div>You have clicked {count} times</div>      <button onClick={ handleUpdate} >        Click me      </button>    </div>  );}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Explanation: As we can from the above example whenever we update the state, React re-render the component, and just after that useEffect() hook call function that we have passed.
Picked
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to render as emphasized text using HTML ? - GeeksforGeeks

31 Dec, 2020
The <em> tag in HTML is a phrase tag and used to emphasize the text content. It is similar to <italic> tag. The main difference between these two tag is the <em> tag semantically emphasizes on the important word or section of words while <i> tag is just offset text conventionally styled in italic to show alternative mood or voice.
Note: This effect can be achieved by using CSS property.
Syntax:
<em> Contents... </em>
Example 1: This example uses <em> tag to create emphasized text.
HTML
<!DOCTYPE html><html> <head>    <title>        How to render as emphasized        text using HTML?    </title></head> <body style="text-align: center;">    <h1 style="color:green;">        GeeksforGeeks    </h1>     <h3>        How to render as emphasized        text using HTML?    </h3>     <em>Emphasized text content</em></body> </html>
Output:
Example 2: This example uses <em> tag with title attribute to create emphasized text.
HTML
<!DOCTYPE html><html> <head>    <title>        How to render as emphasized        text using HTML?    </title></head> <body style="text-align: center;">    <h1 style="color:green;">        GeeksforGeeks    </h1>     <h3>        How to render as emphasized        text using HTML?    </h3>     <em title="Emphasized text">        Emphasized text content    </em></body> </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
C++ Fstream Library - Close Function

Closes the file currently associated with the object, disassociating it from the stream. If the stream is currently not associated with any file (i.e., no file has successfully been open with it), calling this function fails.
Following is the declaration for fstream::close.
void close();
none
If the operation fails (including if no file was open before the call), the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).
Basic guarantee − if an exception is thrown, the stream is in a valid state.
Any exception thrown by an internal operation is caught by the function and rethrown after closing the file.
It throws an exception of member type failure if the function fails (setting the failbit state flag) and member exceptions was set to throw for that state.
Modifies the fstream object.
Concurrent access to the same stream may introduce data races.
In below example explains about fstream close function.
#include <fstream>      

int main () {

   std::fstream fs;
   fs.open ("test.txt", std::fstream::in | std::fstream::out | std::fstream::app);

   fs << " more lorem ipsum";

   fs.close();

   return 0;
}
 Print
 Add Notes
 Bookmark this page
Create Scatter plot from CSV in R - GeeksforGeeks

27 Aug, 2021
In R Programming Language we use plot() function to display scatterplot. It takes eight parameters.
Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes)
Parameters:
x: sets variable to be used for horizontal coordinates.
y: sets variable to be used for vertical coordinates.
xlab: label for horizontal axis.
ylab: label for vertical axis.
main: title of the chart.
xlim: limits of x for plotting values of x.
ylim: limits of y for plotting values of y.
axes: it indicates whether both axes should be drawn on the plot.
To set attributes of scatter plot like color and shape of scatter plot points we use “col” attribute to set the color of scatter plot and to set shape we use “pch”, where pch takes numeric values between 0 and 25.
Here we are going to create dataframe from this dataset. We use read.csv() to read csv file and store that data in a variable.
R
csv_data<-read.csv("diamonds.csv")print(csv_data)
 
 
Output:
 
 
Example 1: In this example we create a simple scatter plot, where x is set to carat and y, is set to price. We label the plot as Price vs Carat.
 
Syntax: plot(x, y, main, xlab, ylab, col, pch) 
Where x is carat data, y is price data, xlab is label for x as “Carat” and ylab is label for y as “Price”. 
 
R
plot(x = csv_data$carat,     y = csv_data$price,     xlab = "Carat",     ylab = "Price",     main = "Price vs Carat")
 
 
Output:
 
 
Example 2: In this example we try to set attributes of scatter plot like color and shape of scatter plot points. We set pch value 4 where value 4 is represented as “x” and color is set to green.
 
R
plot(x = csv_data$carat,     y = csv_data$price,     xlab = "Carat",     ylab = "Price",     col = "green",     pch = 4,     main = "Price vs Carat")
 
 
Output:
 
 
Example 3: We can also add a regression line to our scatter plot by using abline() function. We pass 2 parameters in which first we pass lm() function(lm() function is used to fit linear models.) where we specify x and y of our dataset and name of our data and, the second parameter is color of the line.
 
R
plot(x = csv_data$carat,     y = csv_data$price,     xlab = "Carat",     ylab = "Price",     col = "green",     pch = 4,     main = "Price vs Carat") abline(lm(csv_data$price ~ csv_data$carat,          data = csv_data), col = "black")
Output:
anikakapoor
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
How to change font color of textView in android?

This example demonstrates how do I change font color of TextView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="My color is Blue"
      android:layout_centerInParent="true"
      android:textStyle="bold"
      android:textSize="36sp"/>
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/textView1"
      android:layout_marginBottom="10dp"
      android:text="My color is Green"
      android:textStyle="bold"
      android:layout_centerInParent="true"
      android:textSize="36sp" />
</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 {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView1 = findViewById(R.id.textView1);
      textView1.setTextColor(Color.BLUE);
      TextView textView2 = findViewById(R.id.textView2);
      textView2.setTextColor(Color.parseColor("#006400"));
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.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.
response.elapsed – Python requests

01 Mar, 2020
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.elapsed out of a response object. response.elapsed returns a timedelta object with the time elapsed from sending the request to the arrival of the response. It is often used to stop the connection after a certain point of time is “elapsed”.
To illustrate use of response.elapsed, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
response.elapsed# import requests moduleimport requests  # Making a get requestresponse = requests.get('https://api.github.com')  # print responseprint(response)  # print elapsed timeprint(response.elapsed)
Save above file as request.py and run using
Python request.py

Check that 0:00:00.347420 at the start of output, it shows the elapsed time since the request is made.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2015 (Set 3) | Question 65

28 Jun, 2021
Consider the following relation
  Cinema (theater, address, capacity) 
Which of the following options will be needed at the end of the SQL query
SELECT P1. address
FROM Cinema P1 
Such that it always finds the addresses of theaters with maximum capacity?(A) WHERE P1. Capacity> = All (select P2. Capacity from Cinema P2)(B) WHERE P1. Capacity> = Any (select P2. Capacity from Cinema P2)(C) WHERE P1. Capacity > All (select max(P2. Capacity) from Cinema P2)(D) WHERE P1. Capacity > Any (select max (P2. Capacity) from Cinema P2)Answer: (A)Explanation: When the ALL condition is followed by a list, the optimizer expands the initial condition to all elements of the list and strings them together with AND operators.
When the ANY condition is followed by a list, the optimizer expands the initial condition to all elements of the list and strings them together with OR operators, as shown below.
Source: http://oracle-base.com/articles/misc/all-any-some-comparison-conditions-in-sql.phpQuiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashSet clear() Method in Java

26 Nov, 2018
The Java.util.HashSet.clear() method is used to remove all the elements from a HashSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing HashSet.
Syntax:
Hash_Set.clear()
Parameters: The method does not take any parameter
Return Value: The function does not returns any value.
Below program illustrate the Java.util.HashSet.clear() method:
// Java code to illustrate clear()import java.io.*;import java.util.HashSet;  public class HashSetDemo{    public static void main(String args[])    {        // Creating an empty HashSet        HashSet<String> set = new HashSet<String>();          // Use add() method to add elements into the Set        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("4");        set.add("Geeks");          // Displaying the HashSet        System.out.println("HashSet: " + set);          // Clearing the HashSet using clear() method        set.clear();          // Displaying the final Set after clearing;        System.out.println("The final set: " + set);    }}
HashSet: [4, Geeks, Welcome, To]
The final set: []

Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Sympy Plane.equation() method

22 Apr, 2020
Syntax :  Plane.equation(x, y, z)

Parameters :
x :  optional
y :  optional
z :  optional

Returns : Equation of Plane

Example #1:
# import sympy, Point3D and Planefrom sympy import Point3D, Plane  # using Plane()  p1 = Plane(Point3D(1, 2, 3), Point3D(4, 5, 6), Point3D(0, 2, 0))p2 = p1.equation()  print(p2)
Output:
-9*x + 6*y + 3*z - 12
Example #2:
# import sympy, Point3D and Planefrom sympy import Point3D, Plane  # using Plane()  p3 = Plane(Point3D(1, 2, 3), normal_vector =(2, 2, 2))p4 = p3.equation()  print(p4)
Output:
2*x + 2*y + 2*z - 12
Python SymPy-Geometry
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Finding Difference between Images using PIL

14 Feb, 2022
Python interpreter in itself doesn’t contain the ability to process images and making out a conclusion to it. So, PIL(Python Imaging Library) adds image processing powers to the interpreter. PIL is an open-source library that provides python with external file support and efficiency to process images and their representations. Basically, PIL is designed to access data in the form of images (pixels) to make the analysis faster.
PIL supports image formats like-
jpeg
tiff
png
jpg
gif
There are a lot of functions that can be performed using PIL, they are-
1) Uploading images
Using PIL, we can load an image and display it. 
Code: After installing the PIL library, run the following code to display any image say abc–
Python3
from PIL import Image  img1 = Image.open('abc.jpg')img1.show()
Output:
The image will display like this after running the code
2) Saving images
Code: For saving image 
Python3
from PIL import Image  img1 = Image.open('flower.png')img1.save('flower.png')
Note: Other functions using PIL – Image processing, difference using ImageChops, downloading, Reading pixels, etc.
To find the difference, upload 2 images in the interpreter and then using ImageChops find the difference between both of them, output will be self-explanatory.
Images used for difference:
r.jpg
p.jpg
Python3
from PIL import Image, ImageChops  img1 = Image.open('p.jpg')img2 = Image.open('r.jpg') diff = ImageChops.difference(img1, img2) if diff.getbbox():    diff.show()
Output: 
The extra portions / difference between both image is green in colour.
sumitgumber28
Python-pil
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.