code-rag-bench/online-tutorials huggingface dataset:
Decryption of files

In this chapter, let us discuss decryption of files in cryptography using Python. Note that for decryption process, we will follow the same procedure, but instead of specifying the output path, we will focus on input path or the necessary file which is encrypted.
The following is a sample code for decrypting files in cryptography using Python −
#!/usr/bin/python
# ---------------- READ ME ---------------------------------------------
# This Script is Created Only For Practise And Educational Purpose Only
# This Script Is Created For http://bitforestinfo.blogspot.in
# This Script is Written By
#
#
##################################################
######## Please Don't Remove Author Name #########
############### Thanks ###########################
##################################################
#
#
# =================Other Configuration================
# Usages :
usage = "usage: %prog [options] "
# Version
Version="%prog 0.0.1"
# ====================================================
# Import Modules
import optparse, sys,os
from toolkit import processor as ps
def main():
   parser = optparse.OptionParser(usage = usage,version = Version)
   parser.add_option(
      '-i','--input',type = 'string',dest = 'inputfile',
      help = "File Input Path For Encryption", default = None)
   
   parser.add_option(
      '-o','--output',type = "string",dest = 'outputfile',
      help = "File Output Path For Saving Encrypter Cipher",default = ".")
   
   parser.add_option(
      '-p','--password',type = "string",dest = 'password',
      help = "Provide Password For Encrypting File",default = None)
      (options, args) =  parser.parse_args()
      # Input Conditions Checkings
      if not options.inputfile or not os.path.isfile(options.inputfile):
         print " [Error] Please Specify Input File Path"
         exit(0)
      if not options.outputfile or not os.path.isdir(options.outputfile):
         print " [Error] Please Specify Output Path"
         exit(0)
      if not options.password:
         print " [Error] No
         exit(0)
      inputfile = options.inputfile
      outputfile = options.outputfile
      password = options.password
      work = "D"
      ps.FileCipher(inputfile,outputfile,password,work)
      return
if __name__ == '__main__':
   main()
You can use the following command for executing the above code −
python pyfilecipher-decrypt.py -i encrypted_file_path -p password

You can observe the following code when you execute the command shown above −
Note − The output specifies the hash values before encryption and after decryption, which keeps a note that the same file is encrypted and the process was successful.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Jackson - First Application

Before going into the details of the jackson library, let's see an application in action. In this example, we've created Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
   
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
      
      //map json to student
      try{
         Student student = mapper.readValue(jsonString, Student.class);
         
         System.out.println(student);
         
         jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
         
         System.out.println(jsonString);
      }
      catch (JsonParseException e) { e.printStackTrace();}
      catch (JsonMappingException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 21 ]
{
  "name" : "Mahesh",
  "age" : 21
}

Following are the important steps to be considered here.
Create ObjectMapper object. It is a reusable object.
ObjectMapper mapper = new ObjectMapper();
Use readValue() method to get the Object from the JSON. Pass json string/ source of json string and object type as parameter.
//Object to JSON Conversion
Student student = mapper.readValue(jsonString, Student.class);
Use writeValueAsString() method to get the JSON string representation of an object.
//Object to JSON Conversion		
jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
 Print
 Add Notes
 Bookmark this page
POP3 protocol client in Python

The poolib module from Python's standard library defines POP3 and POP3_SSL classes. POP3 class encapsulates a connection to a POP3 server and implements the protocol as defined in RFC 1939. POP3_SSL classsupports POP3 servers that use SSL as an underlying protocol layer.
POP3 protocolis obsolescent as its implementation quality of POP3 servers is quite poor. If your mailserver supports IMAP, it is recommended to use the imaplib.IMAP4 class.
Both classes have following methods defined −
Returns the greeting string sent by the POP3 server.
Send user command, response should indicate that a password is required.
Send password.
Get mailbox status. The result contains 2 integers: (message count, mailbox size).
Request message list, result is in the form (response, ['mesg_num octets', ...], octets).
Retrieve message of specified index, and set its seen flag.
Flag message number which for deletion.
Retrieves the message header plus number of lines of the message after the header of message
commit changes, unlock mailbox, drop connection.
Following code retrieves all unread messages from gmail’s POP server.
import poplib
box = poplib.POP3_SSL('pop.googlemail.com', '995')
box.user("YourGmailUserName")
box.pass_('YourPassword')
N = len(box.list()[1])
for i in range(N):
   for msg in box.retr(i+1)[1]:
      print (msg)
box.quit()
Before running above script ensure that your gmail account is configure to allow less secure apps.
How to combine two rows in R matrix by addition?

To combine two rows in R matrix by addition, we can follow the below steps −
First of all, create a matrix.
First of all, create a matrix.
Then, using plus sign (+) to add two rows and store the addition in one of the rows.
Then, using plus sign (+) to add two rows and store the addition in one of the rows.
After that, remove the row that is not required by subsetting with single square brackets.
After that, remove the row that is not required by subsetting with single square brackets.
Let’s create a matrix as shown below −
M<-matrix(sample(1:5,100,replace=TRUE),ncol=4)
M
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
     [,1] [,2] [,3] [,4]
[1,]  4    4    2    1
[2,]  5    4    4    4
[3,]  1    1    5    3
[4,]  1    4    4    4
[5,]  5    1    1    3
[6,]  3    1    2    1
[7,]  4    4    5    2
[8,]  3    4    2    1
[9,]  2    2    4    4
[10,] 4    1    1    2
[11,] 5    3    1    2
[12,] 3    1    2    4
[13,] 3    3    2    3
[14,] 3    3    1    1
[15,] 5    5    5    5
[16,] 4    1    2    5
[17,] 4    2    5    1
[18,] 3    4    1    5
[19,] 5    3    4    4
[20,] 2    5    1    1
[21,] 5    3    5    5
[22,] 2    4    2    3
[23,] 5    5    2    5
[24,] 3    5    4    1
[25,] 4    1    2    5
Add two rows
Using plus sign to add row 1 and row 2 then storing the sum in row 1 −
M<-matrix(sample(1:5,100,replace=TRUE),ncol=4)
M[1,]<-M[1,]+M[2,]
M
     [,1] [,2] [,3] [,4]
[1,]  9    8    6    5
[2,]  5    4    4    4
[3,]  1    1    5    3
[4,]  1    4    4    4
[5,]  5    1    1    3
[6,]  3    1    2    1
[7,]  4    4    5    2
[8,]  3    4    2    1
[9,]  2    2    4    4
[10,] 4    1    1    2
[11,] 5    3    1    2
[12,] 3    1    2    4
[13,] 3    3    2    3
[14,] 3    3    1    1
[15,] 5    5    5    5
[16,] 4    1    2    5
[17,] 4    2    5    1
[18,] 3    4    1    5
[19,] 5    3    4    4
[20,] 2    5    1    1
[21,] 5    3    5    5
[22,] 2    4    2    3
[23,] 5    5    2    5
[24,] 3    5    4    1
[25,] 4    1    2    5
Remove the row which is not required
Using single square subsetting to remove 2nd row from matrix M −
M<-matrix(sample(1:5,100,replace=TRUE),ncol=4)
M[1,]<-M[1,]+M[2,]
M[-2,]
     [,1] [,2] [,3] [,4]
[1,]  9    8    6    5
[2,]  1    1    5    3
[3,]  1    4    4    4
[4,]  5    1    1    3
[5,]  3    1    2    1
[6,]  4    4    5    2
[7,]  3    4    2    1
[8,]  2    2    4    4
[9,]  4    1    1    2
[10,] 5    3    1    2
[11,] 3    1    2    4
[12,] 3    3    2    3
[13,] 3    3    1    1
[14,] 5    5    5    5
[15,] 4    1    2    5
[16,] 4    2    5    1
[17,] 3    4    1    5
[18,] 5    3    4    4
[19,] 2    5    1    1
[20,] 5    3    5    5
[21,] 2    4    2    3
[22,] 5    5    2    5
[23,] 3    5    4    1
[24,] 4    1    2    5
Design Patterns - Memento Pattern 

Memento pattern is used to restore state of an object to a previous state. Memento pattern falls under behavioral pattern category.
Memento pattern uses three actor classes. Memento contains state of an object to be restored. Originator creates and stores states in Memento objects and Caretaker object is responsible to restore object state from Memento. We have created classes Memento, Originator and CareTaker. 

MementoPatternDemo, our demo class, will use CareTaker and Originator objects to show restoration of object states.
Create Memento class.
Memento.java
public class Memento {
   private String state;

   public Memento(String state){
      this.state = state;
   }

   public String getState(){
      return state;
   }	
}
Create Originator class
Originator.java
public class Originator {
   private String state;

   public void setState(String state){
      this.state = state;
   }

   public String getState(){
      return state;
   }

   public Memento saveStateToMemento(){
      return new Memento(state);
   }

   public void getStateFromMemento(Memento memento){
      state = memento.getState();
   }
}
Create CareTaker class
CareTaker.java
import java.util.ArrayList;
import java.util.List;

public class CareTaker {
   private List<Memento> mementoList = new ArrayList<Memento>();

   public void add(Memento state){
      mementoList.add(state);
   }

   public Memento get(int index){
      return mementoList.get(index);
   }
}
Use CareTaker and Originator objects.
MementoPatternDemo.java
public class MementoPatternDemo {
   public static void main(String[] args) {
   
      Originator originator = new Originator();
      CareTaker careTaker = new CareTaker();
      
      originator.setState("State #1");
      originator.setState("State #2");
      careTaker.add(originator.saveStateToMemento());
      
      originator.setState("State #3");
      careTaker.add(originator.saveStateToMemento());
      
      originator.setState("State #4");
      System.out.println("Current State: " + originator.getState());		
      
      originator.getStateFromMemento(careTaker.get(0));
      System.out.println("First saved State: " + originator.getState());
      originator.getStateFromMemento(careTaker.get(1));
      System.out.println("Second saved State: " + originator.getState());
   }
}
Verify the output.
Current State: State #4
First saved State: State #2
Second saved State: State #3


    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
TypeScript - String Constructor Property

Returns a reference to the String function that created the object.
var str = new String( "This is string" ); 
console.log("str.constructor is:" + str.constructor)

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
str.constructor is:function String() { [native code] }


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
What is the best way to remove an item from a Python dictionary?

You can use the del function to delete a specific key or loop through all keys and delete them. For example,
my_dict = {'name': 'foo', 'age': 28}
keys = list(my_dict.keys())
for key in keys:
   del my_dict[key]
print(my_dict)
This will give the output:
{}
You can also use the pop function to delete a specific key or loop through all keys and delete them. For example,
my_dict = {'name': 'foo', 'age': 28}
keys = list(my_dict.keys())
for key in keys:
my_dict.pop(key)
print(my_dict)
This will give the output:
{}
SQL Tryit Editor v1.6

SELECT * FROM Products
WHERE Price <> 18;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Crontab – Running a Python script with parameters

18 Jul, 2021
Scheduling python scripts with crontab is fundamental when it comes to automating tasks using python. We will see how to schedule python scripts and pass the necessary parameters as well.
The Cron job utility is a time-based job scheduler in Unix. It allows the user to run the file at a given time and date. And crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. 
First, let’s create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the product of all parameters passed and prints them to STDOUT along with the time the script was run.
Python
#! /usr/bin/python3  import sysfrom datetime import datetime  def main(args):    ans = 1    for arg in args[1:]:        ans *= int(arg)    print("calculated result as: {} on: {} ".format(ans,                                                    datetime.now()))  if __name__ == '__main__':    main(sys.argv)
Note: #!/usr/bin/python3 (specifying the path of script interpreter) is necessary if you wish to make the script executable.
Assuming we have saved this script as  my_script.py under our home directory, we can make it executable by entering the following command in our terminal:
$ sudo chmod +x my_script.py
We can test our script if it is working properly.
./my_script.py 1 2 3 4 5
calculated result as: 120 on: 2021-07-01 12:19:48.856184
The crontab scheduling expression has the following parts:
Crontab also accepts special characters for creating a more complex time schedule:
To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:
crontab -e
You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:
*/2 * * * * /home/$(USER)/my_script.py 1 2 3 4 5 >> /home/$(USER)/output.txt
where $(USER) can be replaced with your username. Save changes and exit. This will schedule our Python script to run every 2 minutes with 1 2 3 4 5 as command-line arguments and write the output to /home/$(USER)/ouput.txt.
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Increase the capacity (size) of ArrayList? - GeeksforGeeks

02 Dec, 2020
ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList without the need to create a new array.
Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold. However, ensureCapacity() method of java.util.ArrayList class can be used to increase the capacity of an ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
Syntax:
public void ensureCapacity(int minCapacity)
Parameters: This method takes the desired minimum capacity as a parameter.
Return Type: This method does not return any value.
Example:
Java
// Java program to demonstrate// ensureCapacity() method for String values  import java.util.ArrayList;  public class GFG {    public static void main(String[] arg) throws Exception    {        try {              // Creating object of ArrayList of String of            // size = 3            ArrayList<String> numbers                = new ArrayList<String>(3);              // adding element to Arrlist numbers            numbers.add("10");            numbers.add("20");            numbers.add("30");              // Print the ArrayList            System.out.println("ArrayList: " + numbers);              // using ensureCapacity() method to            // increase the capacity of ArrayList            // numbersto hold 500 elements.            System.out.println(                "Increasing the capacity of ArrayList numbers to store upto 500 elements.");              numbers.ensureCapacity(500);              System.out.println(                "ArrayList numbers can now store upto 500 elements.");        }          catch (NullPointerException e) {            System.out.println("Exception thrown : " + e);        }    }}
ArrayList: [10, 20, 30]
Increasing the capacity of ArrayList numbers to store upto 500 elements.
ArrayList numbers can now store upto 500 elements.
Java-ArrayList
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
PHP - Static Variables

Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −
Local variables
Function parameters
Global variables
Static variables.
The final type of variable scoping that I discuss is known as static. In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.
<?php
   function keep_track() {
      STATIC $count = 0;
      $count++;
      print $count;
      print "<br />";
   }
   
   keep_track();
   keep_track();
   keep_track();
?>
This will produce the following result −
1
2
3


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

HTML Input types
Tryit: input type = tel
JavaScript | Object.defineProperty() Method - GeeksforGeeks

16 Apr, 2020

The Object.defineProperty() method in JavaScript is a Standard built-in objects which defines a new property directly on an object and returns the object.
Syntax:
Object.defineProperty(obj, prop, descriptor)
Parameter: This method accept three parameters as mentioned above and described below:
Obj: This parameter holds the Object on which user is going to be define the property.
Prop: This parameter holds the name of a property which is going to be defined or modified.
Descriptor: This parameter holds the descriptor for the property being defined or modified.
Return Value: This method returns the object which is passed as the argument to the function.
Below examples illustrate the Object.defineProperty() method in JavaScript:
Example 1:
 

 
 










<script> 
const geek1 = {}; 
Object.defineProperty(geek1, 'prop1', { 
  value: 65, 
  writable: false
}); 
geek1.prop1 = 7; 
console.log(geek1.prop1); 
  
const geek2 = {};   
Object.defineProperty(geek2, 'prop2', {   
      
  value: 54,   
  value: 23,   
  value: 12*9,   
  });   
geek2.prop2 ;   
console.log(geek2.prop2);  
</script>  






Output:
65
108
Example 2:
 

 
 










<script> 
function gfg() { 
} 
  
var result; 
Object.defineProperty(gfg.prototype, "valx", { 
  get() { 
    return result; 
  }, 
  set(valx) { 
    result = valx; 
  } 
}); 
  
var vala = new gfg(); 
var valb = new gfg(); 
vala.valx = 6; 
console.log(valb.valx); 
  
function gfg1() { 
} 
  
gfg1.prototype.valx = 4; 
Object.defineProperty(gfg1.prototype, "valy", { 
  writable: false, 
  value: 8 
}); 
  
var vala = new gfg1(); 
vala.valx = 4; 
console.log(vala.valx);  
console.log(gfg1.prototype.valx);  
vala.valy = 2; 
console.log(vala.valy); 
console.log(gfg1.prototype.valy); 
</script>  






Output:
6
4
4
8
8
Supported Browsers: The browsers supported by Object.defineProperty() method are listed below:
Google Chrome
Firefox
Opera
Safari
Edge

javascript-functions


JavaScript


Web Technologies

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to filter object array based on attributes?
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 get column count in a ResultSet in JDBC?

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.
//Retrieving the ResultSetMetaData object
ResultSetMetaData rsmd = rs.getMetaData();
//getting the column type
int column_count = rsmd.getColumnCount();
Let us create a table with name employee_data in MySQL database using CREATE statement as shown below −
CREATE TABLE employee_data(
   id INT,
   Name VARCHAR(255),
   DOB date,
   Location VARCHAR(40)
);
Following JDBC program establishes connection with the database, retrieves the ResultSetMetaData object of the employee_data table, and prints the number of columns in it.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class NumberOfColumns {
   public static void main(String args[])throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from employee_data");
      //Retrieving the ResultSetMetaData object
      ResultSetMetaData rsmd = rs.getMetaData();
      //getting the column type
      int column_count = rsmd.getColumnCount();
      System.out.println("Number of columns in the table : "+column_count);
   }
}
Connection established......
Number of columns in the table : 4
Java - cos() Method

The method returns the cosine of the specified double value.
double cos(double d)

Here is the detail of parameters −
d − This method accepts a value of double data type.
d − This method accepts a value of double data type.
This method returns the cosine of the specified double value.
public class Test { 

   public static void main(String args[]) {
      double degrees = 45.0;
      double radians = Math.toRadians(degrees);

      System.out.format("The value of pi is %.4f%n", Math.PI);
      System.out.format("The cosine of %.1f degrees is %.4f%n", degrees, Math.cos(radians));
   }
}
This will produce the following result −
The value of pi is 3.1416
The cosine of 45.0 degrees is 0.7071


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Difference between Compile-time and Run-time Polymorphism in Java

23 Jun, 2022
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. In this article, we will see the difference between two types of polymorphisms, compile time and run time. 
Compile Time Polymorphism: Whenever an object is bound with its functionality at the compile time, this is known as the compile-time polymorphism. At compile-time, java knows which method to call by checking the method signatures. So this is called compile-time polymorphism or static or early binding. Compile-time polymorphism is achieved through method overloading. Method Overloading says you can have more than one function with the same name in one class having a different prototype. Function overloading is one of the ways to achieve polymorphism but it depends on technology and which type of polymorphism we adopt. In java, we achieve function overloading at compile-Time. The following is an example where compile-time polymorphism can be observed. 
Java
// Java program to demonstrate// compile-time polymorphismpublic class GFG {     // First addition function    public static int add(int a, int b)    {        return a + b;    }     // Second addition function    public static double add(        double a, double b)    {        return a + b;    }     // Driver code    public static void main(String args[])    {        // Here, the first addition        // function is called        System.out.println(add(2, 3));         // Here, the second addition        // function is called        System.out.println(add(2.0, 3.0));    }}
5
5.0
 
Run-Time Polymorphism: Whenever an object is bound with the functionality at run time, this is known as runtime polymorphism. The runtime polymorphism can be achieved by method overriding. Java virtual machine determines the proper method to call at the runtime, not at the compile time. It is also called dynamic or late binding. Method overriding says the child class has the same method as declared in the parent class. It means if the child class provides the specific implementation of the method that has been provided by one of its parent classes then it is known as method overriding. The following is an example where runtime polymorphism can be observed.
Java
// Java program to demonstrate// runtime polymorphism // Implementing a classclass Test {     // Implementing a method    public void method()    {        System.out.println("Method 1");    }} // Defining a child classpublic class GFG extends Test {     // Overriding the parent method    public void method()    {        System.out.println("Method 2");    }     // Driver code    public static void main(String args[])    {        Test test = new GFG();         test.method();    }}
Method 2
 
The following table demonstrates the difference between runtime polymorphism and compile-time polymorphism:
pnbali4141
suyashdashputre
Java-Object Oriented
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Check if given string is numeric or not

25 Jun, 2022
Given a string, write a Python program to check if the string is numeric or not. 
Examples: 
Input:  28
Output: digit

Input: a
Output: not a digit. 

Input: 21ab
Output: not a digit. 
Code #1: Using Python regex 
re.search(): This method either returns None (if the pattern doesn’t match) or a re.MatchObject contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.  
Python3
# Python program to identify the Digit # import re module # re module provides support# for regular expressionsimport re # Make a regular expression# for identifying a digitregex = '^[0-9]+$'     # Define a function for# identifying a Digitdef check(string):      # pass the regular expression     # and the string in search() method    if(re.search(regex, string)):        print("Digit")             else:        print("Not a Digit")      # Driver Codeif __name__ == '__main__' :         # Enter the string    string = "28"         # calling run function    check(string)     string = "a"    check(string)     string = "21ab"    check(string)     string = "12ab12"    check(string)
Digit
Not a Digit
Not a Digit
Not a Digit
 
  Code #2: Using string.isnumeric() function
Python3
# Python code to check if string is numeric or not     # checking for numeric charactersstring = '123ayu456'print(string.isnumeric())    string = '123456'print(string.isnumeric())
False
True
 
Code #3 : Without any built-in methods
Python3
# Python code to check if string is numeric or not     # checking for numeric charactersnumerics="0123456789"string = "123456"c=0for i in string:    if i in numerics:        c+=1res=Falseif(c==len(string)):    res=Trueprint(res)
True
varshagumber28
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Custom Sort in SQL ORDER BY Clause?

28 Oct, 2021
By default SQL ORDER BY sort, the column in ascending order but when the descending order is needed ORDER BY DESC can be used. In case when we need a custom sort then we need to use a CASE statement where we have to mention the priorities to get the column sorted.
In this article let us see how we can custom sort in a table using order by using MSSQL as a server.
Syntax:
SELECT * FROM table_name
ORDER BY CASE 
     WHEN column_field = "value1" THEN priority1
     WHEN column_field = "value2" THEN priority2
     WHEN column_field = "value3" THEN priority3
     .
     ELSE priorityn 
     END ASC
Step 1: We are creating a Database. For this use the below command to create a database named GeeksforGeeks.
Query:
CREATE DATABASE GeeksforGeeks;
Step 2: To use the GeeksforGeeks database use the below command.
Query:
USE GeeksforGeeks
Step 3: Now we are creating a table. Create a table student_marks with 4 columns using the following SQL query.
Query:
CREATE TABLE student_marks(
stu_id VARCHAR(20),
stu_name VARCHAR(20),
stu_branch VARCHAR(20),
total_marks INT
)
Step 4: View the description of the table.
Query:
EXEC sp_columns student_marks
Step 5: The query for Inserting rows into the Table. Insert rows into the student_marks  table using the following SQL query.
Query:
INSERT INTO student_marks
VALUES( '1001','PRADEEP','E.C.E', 550),
( '1002','KIRAN','E.C.E', 540),
( '5001','PRANAV','I.C.E', 450),
( '2001','PADMA','C.S.E', 570),
( '2002','SRUTHI','C.S.E', 480),
( '2003','HARSITHA','C.S.E', 534),
( '3001','SAI','I.T', 560),
( '3002','HARSH','I.T', 510),
( '4001','HARSHINI','E.E.E', 500) 
Step 6: Viewing the inserted data
Query:
SELECT * FROM student_marks
Query to custom sort based on branch order of C.S.E, I.T, E.C.E, I.C.E, E.E.E also show the difference between the default sort using ORDER BY.
Default sort by ORDER BY :
SELECT * FROM student_marks
ORDER BY stu_branch 
Output:
Custom sort by ORDER BY:
SELECT * FROM student_marks
ORDER BY CASE
         WHEN stu_branch = 'C.S.E' then 1
         WHEN stu_branch = 'I.T' then 2 
         WHEN stu_branch = 'E.C.E' then 3
         WHEN stu_branch = 'I.C.E' then 4
         WHEN stu_branch = 'E.E.E' then 5
         END ASC  
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sort an array of dates in PHP

08 Mar, 2018
We are given an array which consists of multiple dates in (Y-m-d) format. We have to write a program in PHP to sort all the dates present in the array in decreasing order.
Examples :
Input : array("2018-06-04", "2014-06-08", "2018-06-05")
Output : 2018-06-05  2018-06-04  2014-06-08

Input : array("2016-09-12", "2009-09-08", "2009-09-09")
Output : 2016-09-12  2009-09-09  2009-09-08

To solve this problem in C/C++/Java or any other general purpose programming language we have to either compare dates based on year then month and finally according to days either by storing them in any structure or any other desired data structure. But in PHP this problem seems to be very easy if we apply strtotime() function. The strtotime() function is a PHP function which changes a given date in any format into a timestamp which is a large integer in nature and then while sorting the array we can easily use the PHP | usort() function by defining a comparator function. The comparator function will accept two date arguments which will be converted to integer timestamp using strtotime() function and then compared to sort date based on integer timestamp value.
Inbuilt Functions used :
strtotime() : This function changes a given date string into timestamp (large int value).
usort() : This function sorts the given array as per a user defined comparison function.
Below is the PHP implementation of above idea:
<?php// PHP program to sort array of dates   // user-defined comparison function // based on timestampfunction compareByTimeStamp($time1, $time2){    if (strtotime($time1) < strtotime($time2))        return 1;    else if (strtotime($time1) > strtotime($time2))         return -1;    else        return 0;}  // Input Array$arr = array("2016-09-12", "2009-09-06", "2009-09-09");  // sort array with given user-defined functionusort($arr, "compareByTimeStamp");  print_r($arr);  ?>
Output :
Array
(
    [0] => 2016-09-12
    [1] => 2009-09-09
    [2] => 2009-09-06
)

date-time-program
PHP-array
PHP-basics
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NPDA for accepting the language L = {an bm cn | m,n>=1}

15 Jun, 2022
Prerequisite – Pushdown automata, Pushdown automata acceptance by final state 
Problem – – Design a non deterministic PDA for accepting the language L = {[Tex]b^m  [/Tex]| m, n>=1}, i.e.,
 L = { abc, abbc, abbbc,  aabbcc, aaabccc, aaaabbbcccc, ...... } 
In each of the string, the number of a’s is equal to number of c’s. And the number of b’s is independent of the number of a’s and c’s. This problem is quite similar to the NPDA for accepting the language L = {[Tex]b^n  [/Tex]| m, n>=1}. The only difference is that here we use instead of . 
Explanation – Here, we need to maintain the order of a’s, b’s and c’s.That is, all the a’s  are coming first and then all the b’s and then c’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and c’s is maintained by the stack. The number of a’s is exactly equal to the number of c’s We will take 2 stack alphabets:
 = { a, z }
Where, = set of all the stack alphabet z = stack start symbol 
Approach used in the construction of PDA – As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. And, when ‘c’ comes then pop one ‘a’ from the stack each time . And for ‘b’, we will do nothing in the stack only change the state in state diagram. So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA. Stack transition functions –
(q0, a, z)  (q0, az)(q0, a, a)  (q0, aa)(q0, b, a)  (q1, a)(q1, b, a)  (q1, a)(q1, c, a)  (q2,  )(q2, c, a)  (q2,  )(q2, , z)  (qf, z )        
Where, q0 = Initial state qf = Final state = indicates pop operation  
So, this is our required non deterministic PDA for accepting the language L = { [Tex]b^m  [/Tex]| m, n>=1 }.
simmytarika5
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the value of a textarea in jQuery ?

03 Aug, 2021
We can get the value of textarea in jQuery with the help of val() method . The val() method is used to get the values from the elements such as textarea, input and select. This method simply returns or sets the value attribute of the selected elements and is mostly used with the form elements.   When called on empty collection or when the input is not given, it returns undefined or blank output.
HTML
<!DOCTYPE html><html>    <head>        <title>How to get the value of textArea</title>        <script src="https://code.jquery.com/jquery-1.12.4.min.js">        </script>    </head>    <body>        <center>            <h1 style="color: green;">GeeksforGeeks</h1>            <textarea id="txtArea"></textarea><br><br>            <button id="btn">Show Text</button>        </center>    </body>      <script>        $(document).ready(function () {                        //This function called when the button is clicked            $("#btn").click(function () {                                // val() method is used to get the values from                // textarea and stored in txt variable                var txt = $("#txtArea").val();                alert(txt);            });        });    </script></html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
toordinal() Function Of Datetime.date Class In Python

23 Aug, 2021
The toordinal() function is used to return the proleptic Gregorian ordinal of a specified datetime instance.
Note: The Proleptic Gregorian ordinal gives the number of days elapsed from the date 01/Jan/0001. And here ordinal is called Proleptic since the Gregorian calendar itself is followed from October 1582.
Syntax: toordinal()
Parameters: This function does not accept any parameter.
Return values: This function returns the proleptic Gregorian ordinal of a datetime instance.
Example 1: Using today’s date.
Python3
# Python3 code to demonstrate# Getting the proleptic Gregorian# ordinal of a datetime instance  # importing datetime and time moduleimport datetimeimport time  # Getting today's datetodays_Date = datetime.date.fromtimestamp(time.time());  # Calling the toordinal() function over the# today's datedate = todays_Date.toordinal();  # Printing the proleptic Gregorian ordinal# for the today's dateprint("Proleptic Ordinal for today's date: %s"%date);
Output:
Proleptic Ordinal for today's date: 737998
Example 2: Using today’s date and time.
Python3
# Python3 code to demonstrate# Getting the proleptic Gregorian# ordinal of a datetime instance  # importing datetime and time moduleimport datetimeimport time  # Getting today's date and timetodays_DateTime = datetime.datetime.now();  # Calling the toordinal() function over the# today's date and timeDateTime = todays_DateTime.toordinal();  # Printing the proleptic Gregorian ordinal# for the today's date and timeprint("Proleptic Ordinal for today's date and time: %s"%DateTime);
Output:
Proleptic Ordinal for today's date and time: 737998
Example 3: Using a specific date.
Python3
# Python3 code to demonstrate# Getting the proleptic Gregorian# ordinal of a datetime instance  # importing datetime and time moduleimport datetimeimport time  # Initializing a date and timeDateTime = datetime.datetime(1358, 8, 12, 1, 3, 4, 9);  # Calling the toordinal() function over the# above date and timeDate_Time = DateTime.toordinal();  # Printing the proleptic Gregorian ordinal# for the above given date and timeprint("Proleptic Ordinal for today's date and time: %s"%Date_Time);
Output:
Proleptic Ordinal for today's date and time: 495858
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sklearn.Binarizer() in Python

29 Jun, 2021
sklearn.preprocessing.Binarizer() is a method which belongs to preprocessing module. It plays a key role in the discretization of continuous feature values. Example #1: A continuous data of pixels values of an 8-bit grayscale image have values ranging between 0 (black) and 255 (white) and one needs it to be black and white. So, using Binarizer() one can set a threshold converting pixel values from 0 – 127 to 0 and 128 – 255 as 1.Example #2: One has a machine record having “Success Percentage” as a feature. These values are continuous ranging from 10% to 99% but a researcher simply wants to use this data for prediction of pass or fail status for the machine based on other given parameters.Syntax :  
sklearn.preprocessing.Binarizer(threshold, copy)
 
Parameters :threshold :[float, optional] Values less than or equal to threshold is mapped to 0, else to 1. By default threshold value is 0.0. copy :[boolean, optional] If set to False, it avoids a copy. By default it is True.  
Return :  
Binarized Feature values
 
Download the dataset: Go to the link and download Data.csvBelow is the Python code explaining sklearn.Binarizer()  
Python3
# Python code explaining how# to Binarize feature values  """ PART 1    Importing Libraries """  import numpy as npimport matplotlib.pyplot as pltimport pandas as pd # Sklearn libraryfrom sklearn import preprocessing """ PART 2    Importing Data """  data_set = pd.read_csv(        'C:\\Users\\dell\\Desktop\\Data_for_Feature_Scaling.csv')data_set.head() # here Features - Age and Salary columns# are taken using slicing# to binarize valuesage = data_set.iloc[:, 1].valuessalary = data_set.iloc[:, 2].valuesprint ("\nOriginal age data values : \n",  age)print ("\nOriginal salary data values : \n",  salary) """ PART 4    Binarizing values """ from sklearn.preprocessing import Binarizer x = agex = x.reshape(1, -1)y = salaryy = y.reshape(1, -1) # For age, let threshold be 35# For salary, let threshold be 61000binarizer_1 = Binarizer(35)binarizer_2 = Binarizer(61000) # Transformed featureprint ("\nBinarized age : \n", binarizer_1.fit_transform(x)) print ("\nBinarized salary : \n", binarizer_2.fit_transform(y))
Output :  
   Country  Age  Salary  Purchased
0   France   44   72000          0
1    Spain   27   48000          1
2  Germany   30   54000          0
3    Spain   38   61000          0
4  Germany   40    1000          1

Original age data values : 
 [44 27 30 38 40 35 78 48 50 37]

Original salary data values : 
 [72000 48000 54000 61000  1000 58000 52000 79000 83000 67000]

Binarized age : 
 [[1 0 0 1 1 0 1 1 1 1]]

Binarized salary : 
 [[1 0 0 0 0 0 0 1 1 1]]
 
ManasChhabra2
sagar0719kumar
python-modules
Advanced Data Structure
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
std::plus in c++

26 Jul, 2017
It is a Function object for performing addition. The object class whose call returns the result of adding its two arguments (as returned by operator + ).
Syntax :
template  struct plus : binary_function  
{
  T operator() (const T& x, const T& y) const { return x + y; }
};

Template parameters :
T - Type of the arguments and return type of the functional call.
    The type shall support the operation (operator+).

Member types :
x : Type of the first argument in member operator()
y : Type of the second argument in member operator()
result_type : Type returned by member operator()

// C++ program to illustrate std::plus// by adding the respective elements of 2 arrays#include <iostream> // std::cout#include <functional> // std::plus#include <algorithm> // std::transform  int main(){    // First array    int first[] = { 1, 2, 3, 4, 5 };      // Second array    int second[] = { 10, 20, 30, 40, 50 };      // Result array    int results[5];      // std::transform applies std::plus to the whole array    std::transform(first, first + 5, second, results, std::plus<int>());      // Printing the result array    for (int i = 0; i < 5; i++)        std::cout << results[i] << " ";      return 0;}
Output:
11 22 33 44 55 

Another example:
// C++ program to illustrate std::plus// by adding all array elements with a number#include <bits/stdc++.h>  int main(){    // Array with elements to be added    int arr[] = { 10, 20, 30 };      // size of array    int size = sizeof(arr) / sizeof(arr[0]);      // Variable with which array is to be added    int num = 100;      // Variable to store result    int result;      // using std::accumulate to perform addition on array with num    // using std::plus    result = std::accumulate(arr, arr + size, num, std::plus<int>());      // Printing the result    std::cout << "The result of 100 + 10 + 20 + 30 is " << result;      return 0;}
Output:
The result of 100 + 10 + 20 + 30 is 160
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.