code-rag-bench/online-tutorials huggingface dataset:
Passing array to method in Java

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array -
public static void printArray(int[] array) {
   for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
   }
}
You can invoke it by passing an array. For example, the following statement invokes the print Array method to display 3, 1, 2, 6, 4, and 2 -
printArray(new int[]{3, 1, 2, 6, 4, 2});
Difference between super() and this() in Java

Following are the notable differences between super() and this() methods in Java.
 Live Demo
class Animal {
   String name;
   Animal(String name) {
      this.name = name;
   }
   public void move() {
      System.out.println("Animals can move");
   }
   public void show() {
      System.out.println(name);
   }
}
class Dog extends Animal {
   Dog() {
      //Using this to call current class constructor
      this("Test");
   }
   Dog(String name) {
      //Using super to invoke parent constructor
      super(name);
   }
   public void move() {
      // invokes the super class method
      super.move();
      System.out.println("Dogs can walk and run");
   }
}
public class Tester {
   public static void main(String args[]) {
      // Animal reference but Dog object
      Animal b = new Dog("Tiger");
      b.show();
      // runs the method in Dog class
      b.move();
   }
}
Tiger
Animals can move
Dogs can walk and run
How to implement Bootstrap 4 .flex-*-nowrap class

The flex-*-nowrap class works like flex-no-wrap class to avoid wrapping of flex items.
However, if you want to avoid wrapping on different screen sizes, then use the flex-*-no-wrap class like −
flex-lg-nowrap: Avoid wrapping on large screen size
flex-sm-nowrap: Avoid wrapping on small screen size
flex-md-nowrap: Avoid wrapping on medium screen size
The following is an example to implement the flex-*-nowrap class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>
<body>
  <div class="container mt-3">
    <p>Flex items will wrap</p>
    <div class="d-flex flex-wrap bg-warning">
      <div class="p-2 border">One</div>
      <div class="p-2 border">Two</div>
      <div class="p-2 border">Three</div>
      <div class="p-2 border">Four</div>
      <div class="p-2 border">Five</div>
      <div class="p-2 border">Six</div>
      <div class="p-2 border">Seven</div>
      <div class="p-2 border">Eight</div>
      <div class="p-2 border">Nine</div>
      <div class="p-2 border">Ten</div>
      <div class="p-2 border">Eleven</div>
      <div class="p-2 border">Twelve</div>
      <div class="p-2 border">Thirteen</div>
      <div class="p-2 border">Fourteen</div>
    </div><br>
    <p>Flex items won't wrap (small screen size)</p>
    <div class="d-flex flex-sm-nowrap bg-danger">
      <div class="p-2 border">One</div>
      <div class="p-2 border">Two</div>
      <div class="p-2 border">Three</div>
      <div class="p-2 border">Four</div>
      <div class="p-2 border">Five</div>
      <div class="p-2 border">Six</div>
      <div class="p-2 border">Seven</div>
      <div class="p-2 border">Eight</div>
      <div class="p-2 border">Nine</div>
      <div class="p-2 border">Ten</div>
      <div class="p-2 border">Eleven</div>
      <div class="p-2 border">Twelve</div>
      <div class="p-2 border">Thirteen</div>
     <div class="p-2 border">Fourteen</div>
    </div><br>
    <p>Flex items won't wrap (medium screen size)</p>
    <div class="d-flex flex-md-nowrap bg-success">
      <div class="p-2 border">One</div>
      <div class="p-2 border">Two</div>
      <div class="p-2 border">Three</div>
      <div class="p-2 border">Four</div>
      <div class="p-2 border">Five</div>
      <div class="p-2 border">Six</div>
      <div class="p-2 border">Seven</div>
      <div class="p-2 border">Eight</div>
      <div class="p-2 border">Nine</div>
      <div class="p-2 border">Ten</div>
      <div class="p-2 border">Eleven</div>
      <div class="p-2 border">Twelve</div>
      <div class="p-2 border">Thirteen</div>
      <div class="p-2 border">Fourteen</div>
    </div>
 </div>

</body>
</html>
Calculate average from JSON data based on multiple filters JavaScript

Suppose, we have an array of objects like this −
const arr = [
   { "SupplierName" : "John", "Category " : "A", "Points" : 3 },
   { "SupplierName" : "John", "Category " : "A", "Points" : 11 },
   { "SupplierName" : "John", "Category " : "A", "Points" : undefined },
   { "SupplierName" : "John", "Category " : "B", "Points" : 2 },
   { "SupplierName" : "John", "Category " : "B", "Points" : 6 },
   { "SupplierName" : "Praveen", "Category " : "A", "Points" : 3 },
   { "SupplierName" : "Praveen", "Category " : "A", "Points" : 7 }
];
We are required to write a JavaScript function that takes in one such array.
The function should do the following things −
Group repeating suppliers into one unique separate object (by repeating, we mean objects with same "SupplierName" and "Category" field).
Add up their points together
Add a new "average field to each object, containing the average points of that supplier.
So, finally the output should look like −
const output = [
   { "SupplierName" : "John", "Category " : "A", "Points" : 14, "Average" : 7 },
   { "SupplierName" : "John", "Category " : "B", "Points" : 8, "Average" : 4 },
   { "SupplierName" : "Praveen", "Category " : "A", "Points" : 10, "Average" : 5 }
];
const arr = [
   { "SupplierName" : "John", "Category " : "A", "Points" : 3 },
   { "SupplierName" : "John", "Category " : "A", "Points" : 11 },
   { "SupplierName" : "John", "Category " : "A", "Points" : undefined },
   { "SupplierName" : "John", "Category " : "B", "Points" : 2 },
   { "SupplierName" : "John", "Category " : "B", "Points" : 6 },
   { "SupplierName" : "Praveen", "Category " : "A", "Points" : 3 },
   { "SupplierName" : "Praveen", "Category " : "A", "Points" : 7 }
];
const groupAndAverage = (arr = []) => {
   const groups = arr.reduce((acc, obj) => {
       const name = obj.SupplierName + obj.Category;
      if (acc[name]) {
         if (obj.Points) (acc[name].Points += obj.Points) && ++acc[name].Average;
      }
      else { acc[name] = obj;
         acc[name].Average = 1;
         // taking 'Average' attribute as an items counter(on the first phase)
      };
      return acc;
   }, {});
   // getting "average of Points" const res = Object.keys(groups).map( name => {       groups[name].Average = Math.round(groups[name].Points/groups[name].Average);
      return groups[name];
   });
   return res;
}; console.log(JSON.stringify(groupAndAverage(arr), undefined, 4));
And the output in the console will be −
[
   {
      "SupplierName": "John",
      "Category ": "A",
      "Points": 22,
      "Average": 6
   },
   {
      "SupplierName": "Praveen",
      "Category ": "A",
      "Points": 10,
      "Average": 5
   }
]
Regex to ignore a specific character in MongoDB?

You can use regular expression along with $not operator to ignore a specific character and display rest of them. Let us first create a collection with documents −
> db.regexDemo.insertOne({"CustomerId":"Customer#1234","CustomerName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7428f8f9e6ff3eb0ce436")
}
> db.regexDemo.insertOne({"CustomerId":"Customer5678","CustomerName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7429e8f9e6ff3eb0ce437")
}
> db.regexDemo.insertOne({"CustomerId":"Customer#777","CustomerName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc742ae8f9e6ff3eb0ce438")
}
> db.regexDemo.insertOne({"CustomerId":"Customer777","CustomerName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc742bc8f9e6ff3eb0ce439")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.regexDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cc7428f8f9e6ff3eb0ce436"),
   "CustomerId" : "Customer#1234",
   "CustomerName" : "Chris"
}
{
   "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"),
   "CustomerId" : "Customer5678",
   "CustomerName" : "Robert"
}
{
   "_id" : ObjectId("5cc742ae8f9e6ff3eb0ce438"),
   "CustomerId" : "Customer#777",
   "CustomerName" : "Carol"
}
{
   "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"),
   "CustomerId" : "Customer777",
   "CustomerName" : "David"
}
Case 1 − Here is the query to avoid using a specific character in MongoDB. The character is # −
> db.regexDemo.find({CustomerId: /^[^#]*$/}).pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"),
   "CustomerId" : "Customer5678",
   "CustomerName" : "Robert"
}
{
   "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"),
   "CustomerId" : "Customer777",
   "CustomerName" : "David"
}
Case 2 − Here is another query to avoid using a specific character in MongoDB. The character is # −
> db.regexDemo.find({CustomerId: {$not: /#/}}).pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cc7429e8f9e6ff3eb0ce437"),
   "CustomerId" : "Customer5678",
   "CustomerName" : "Robert"
}
{
   "_id" : ObjectId("5cc742bc8f9e6ff3eb0ce439"),
   "CustomerId" : "Customer777",
   "CustomerName" : "David"
}
Can an ArrayList Contain Multiple References to the Same Object in Java? - GeeksforGeeks

22 Oct, 2021
ArrayList class in Java is basically a resizable array i.e. it can grow and shrink in size dynamically according to the values that we add or remove to/from it. It is present in java.util package.
We will discuss if an ArrayList can contain multiple references to the same object in Java.
The ArrayList in java does not provide the checks for duplicate references to the same object. Therefore, we can insert the same object or reference to a single object as many times as we want. If we wish we can check if an element already exists in ArrayList or not with the help of the contains() method. 
Below is the code implementation of the above problem statement:
Java
// Java program to demonstrate some functionalities// of ArrayList import java.util.ArrayList; class Employee{    private String name;    private String designation;     // Parameterized constructor for Employee class    public Employee(String name, String designation) {        this.name = name;        this.designation = designation;    }     // Creating getters for Employee class    public String getName() {        return name;    }     public String getDesignation() {        return designation;    }} public class GFG {    public static void main(String[] args) {         // Creating Objects of Employee class        Employee e1 = new Employee("Raj","Manager");        Employee e2 = new Employee("Simran", "CEO");        Employee e3 = new Employee("Anish", "CTO");         // Creating an ArrayList of Employee type        ArrayList<Employee> employeeList= new ArrayList<>();         // Inserting the employee objects in the ArrayList        employeeList.add(e1);        employeeList.add(e2);        employeeList.add(e3);         // e1 will be inserted again as ArrayList can store multiple        // reference to the same object        employeeList.add(e1);         // Checking if e2 already exists inside ArrayList        // if it exists then we don't insert it again        if(!employeeList.contains(e2))            employeeList.add(e2);         // ArrayList after insertions: [e1, e2, e3, e1]         // Iterating the ArrayList with the help of Enhanced for loop        for(Employee employee: employeeList){            System.out.println(employee.getName() + " is a " + employee.getDesignation());        }    }}
Raj is a Manager
Simran is a CEO
Anish is a CTO
Raj is a Manager
gabaa406
ruhelaa48
Java-ArrayList
Java-Collections
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
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?
Get current thread in Java

A thread can be created by implementing the Runnable interface and overriding the run() method.
The current thread is the currently executing thread object in Java. The method currentThread() of the Thread class can be used to obtain the current thread. This method requires no parameters.
A program that demonstrates this is given as follows −
 Live Demo
public class Demo extends Thread {
   public void run() {
      for (int i = 0; i < 5; i++) {
         System.out.println("The Thread name is " + Thread.currentThread().getName());
      }
   }
   public static void main(String[] args) {
      Demo t1 = new Demo();
      t1.setName("Main Thread");
      t1.start();
      Thread t2 = currentThread();
      t2.setName("Current Thread");
      for (int i = 0; i < 5; i++) {
         System.out.println("The Thread name is " + t1.currentThread().getName());
      }
   }
}
The output of the above program is as follows −
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Current Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread
The Thread name is Main Thread
Scikit Learn - Multi-task LASSO

It allows to fit multiple regression problems jointly enforcing the selected features to be same for all the regression problems, also called tasks. Sklearn provides a linear model named MultiTaskLasso, trained with a mixed L1, L2-norm for regularisation, which estimates sparse coefficients for multiple regression problems jointly. In this the response y is a 2D array of shape (n_samples, n_tasks).
The parameters and the attributes for MultiTaskLasso are like that of Lasso. The only difference is in the alpha parameter. In Lasso the alpha parameter is a constant that multiplies L1 norm, whereas in Multi-task Lasso it is a constant that multiplies the L1/L2 terms.
And, opposite to Lasso, MultiTaskLasso doesn’t have precompute attribute.
Following Python script uses MultiTaskLasso linear model which further uses coordinate descent as the algorithm to fit the coefficients.
from sklearn import linear_model
MTLReg = linear_model.MultiTaskLasso(alpha=0.5)
MTLReg.fit([[0,0], [1, 1], [2, 2]], [[0, 0],[1,1],[2,2]])
MultiTaskLasso(alpha = 0.5, copy_X = True, fit_intercept = True, max_iter = 1000,
   normalize = False, random_state = None, selection = 'cyclic', tol = 0.0001,
   warm_start = False)

Now, once fitted, the model can predict new values as follows −
MTLReg.predict([[0,1]])
array([[0.53033009, 0.53033009]])

For the above example, we can get the weight vector with the help of following python script −
MTLReg.coef_
array([[0.46966991, 0. ],
[0.46966991, 0. ]])

Similarly, we can get the value of intercept with the help of following python script −
MTLReg.intercept_
array([0.53033009, 0.53033009])

We can get the total number of iterations to get the specified tolerance with the help of following python script −
MTLReg.n_iter_
2

We can change the values of parameters to get the desired output from the model.

    11 Lectures 
     2 hours 

 PARTHA MAJUMDAR
 Print
 Add Notes
 Bookmark this page
How to set file permissions in Java?

In general, whenever you create a file you can restrict/permit certain users from reading/writing/executing a file.
In Java files (their abstract paths) are represented by the Files class of the java.io package. This class provides various methods to perform various operations on files such as read, write, delete, rename etc.
In addition, this class also provides the following methods −
setExecutble() − This method is sued to set the execute permissions to the file represented by the current (File) object.
setWritable() − This method is used to set the write permissions to the file represented by the current (File) object.
setReadable() − This method is used to set the read permissions to the file represented by the current (File) object.
Following Java program creates a file writes some data into It and set read, write and execute permission to it.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FilePermissions {
   public static void main(String args[]) throws IOException {
      String directoryPath = "D:/SampleDirectory";
      String fileName = "example.txt";
      //Creating a directory
      new File(directoryPath).mkdir();
      System.out.println("Directory created.........");
      //Creating a file
      File file = new File(directoryPath+fileName);
      System.out.println("File created.........");
      //Writing data into the file
      FileWriter writer = new FileWriter(file);
      String data = "Hello welcome to Tutorialspoint";
      writer.write(data);
      System.out.println("Data entered.........");
      //Setting permissions to the file
      file.setReadable(true); //read
      file.setWritable(true); //write
      file.setExecutable(true); //execute
      System.out.println("Permissions granted.........");
   }
}
Directory created.........
File created.........
Data entered.........
Permissions granted.........
Java Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.
Like we specified in the previous chapter; 
Inheritance lets us 
inherit attributes and methods from another class. Polymorphism 
uses those methods to perform different tasks. This allows us to perform a single 
action in different ways.
For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):
class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.
Now we can create Pig and 
Dog objects and call the animalSound() method on both of them:
class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}


Try it Yourself »

- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
MySQL query to calculate the total amount from column values with Cost and Quantity?

Let us first create a table −
mysql> create table DemoTable
(
   Cost int,
   Quantity int
);
Query OK, 0 rows affected (0.80 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(65,2);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values(290,4);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(40,3);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+----------+
| Cost | Quantity |
+------+----------+
| 65   |        2 |
| 290  |        4 |
| 40   |        3 |
+------+----------+
3 rows in set (0.00 sec)
Following is the query to calculate the total amount −
mysql> select Cost,Quantity,Cost*Quantity AS Total_Amount from DemoTable;
This will produce the following output −
+------+----------+--------------+
| Cost | Quantity | Total_Amount |
+------+----------+--------------+
|   65 |        2 |          130 |
|  290 |        4 |         1160 |
|   40 |        3 |          120 |
+------+----------+--------------+
3 rows in set (0.02 sec)
What is strrev() Function in C language?

An array of characters is called a string.
The syntax for declaring an array is as follows −
char stringname [size];
For example − char string[50]; string of length 50 characters
Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
This function is used for reversing a string.
The reversed string is stored in the same string.
The syntax for strrev() function is as follows −
strrev (string)
The following program shows the usage of strrev() function.
#include<stdio.h>
main ( ){
   char a[50] ;
   clrscr( );
   printf ("enter a string");
   gets (a);
   strrev (a);
   printf("reversed string = %s",a)
   getch ( );
}
When the above program is executed, it produces the following result −
enter a string Hello
Reverse string = olleH
Let’s see another example to know more about string reverse.
The C program to reverse a string using strrev library function is given below −
#include<stdio.h>
#include<string.h>
void main(){
   char string[25];
   printf("Enter String to be reversed : ");
   gets(string);
   printf("String before strrev(): %s\n",string);
   strrev(string);
   printf("The string after strrev(): ");
   puts(string);
}
When the above program is executed, it produces the following result −
Enter String to be reversed : Tutorials Point
String before strrev(): Tutorials Point
The string after strrev(): tnioP slairotuT
How to declare a variable in MySQL?

We can declare a variable in MySQL with the help of SELECT and SET command. Before
declaring a variable we need to prefix the symbol ‘@’
The syntax is as follows −
SELECT @ yourVariableName;
The symbol ‘@’ tells that it is a user defined variable or not. If there is no symbol, that would
mean it is a local variable. Prefix with two ‘@@’ tells about the server system variables.
Here, we will learn about user defined variable. We can set some value to the variable with the help of SET command.
The syntax is as follows −
SET @yourVariableName=value;
Note − In the SELECT statement, the “yourVariableName” contains the NULL value and after using the SET command it contains the value which we have given.
Now, we will check by applying the above query. Firstly, let us declare a variable.
mysql> SELECT @engine;
After executing the above query, the variable gets NULL value initially. The following is the
output −
+---------+
| @engine |
+---------+
| NULL    |
+---------+
1 row in set (0.00 sec)
Set some value to the variable with the help of SET command −
mysql> SET @engine='start';
Query OK, 0 rows affected (0.00 sec)
After that, we can check the value we have given above. For that, use the SELECT statement.
The following is the query −
mysql> SELECT @engine;
After executing the above query, we will get the updated value.
The following is the output −
+---------+
| @engine |
+---------+
| start   |
+---------+
1 row in set (0.00 sec)
Now, we can update the variable value like this −
mysql> set @engine='close';
Query OK, 0 rows affected (0.00 sec)
Check the result is updated or not with the help of SELECT command::
mysql> select @engine;
After executing the above query, we will get the output as shown below −
+---------+
| @engine |
+---------+
| close   |
+---------+
1 row in set (0.00 sec)
From the above output it is clear that the @engine variable is updated with value ‘close’.
Neo4j - Optional Match Clause

The OPTIONAL MATCH clause is used to search for the pattern described in it, while using nulls for missing parts of the pattern.
OPTIONAL MATCH is similar to the match clause, the only difference being it returns null as a result of the missing parts of the pattern.
Following is the syntax of the OPTIONAL MATCH with relationship.
MATCH (node:label {properties. . . . . . . . . . . . . .}) 
OPTIONAL MATCH (node)-->(x) 
RETURN x

Following is a sample Cypher Query which tries to retrieve the relations from the node ICCT2013. Since there are no such nodes, it returns null.
MATCH (a:Tornament {name: "ICC Champions Trophy 2013"}) 
OPTIONAL MATCH (a)-->(x) 
RETURN x 
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result. Here you can observe that since there are no matches for the required pattern, Neo4j returned null.
 Print
 Add Notes
 Bookmark this page
How to implement IDisposable Design Pattern in C#?

We should use an IDisposable design pattern (or Dispose Pattern) when we need to dispose of unmanaged objects.
For implementing the IDisposable design pattern, the class which deals with unmanaged objects directly or indirectly should implement the IDisposable interface.And implement the method Dispose declared inside of the IDisposable interface. We do not directly deal with unmanaged objects. But we deal with managed classes, which deals directly with unmanaged objects. For example, File handlers, connection string, HTTP streams, etc.
Important aspect of this pattern is that it makes easier for inherited classes to follow the IDisposable design pattern. And it is because of the implementation of an overridable Dispose method. This pattern also suggests the use of the Finalizer method (or destructor in c#). However, if we use the Finalizer, it should be managed properly due to its performance implications.
static class Program {
   static void Main(string[] args) {
      using var serviceProxy = new ServiceProxy(null);
      serviceProxy.Get();
      serviceProxy.Post("");
      Console.ReadLine();
   }
}
public class ServiceProxy : System.IDisposable {
   private readonly HttpClient httpClient;
   private bool disposed;

   public ServiceProxy(IHttpClientFactory httpClientFactory) {
      httpClient = httpClientFactory.CreateClient();
   }
   ~ServiceProxy() {
      Dispose(false);
   }
   public void Dispose() {
      Dispose(true);
      GC.SuppressFinalize(this);
   }
   protected virtual void Dispose(bool disposing) {
      if (disposed) {
         return;
      }

      if (disposing) {
         // Dispose managed objects
         httpClient.Dispose();
      }
      // Dispose unmanaged objects
      disposed = true;
   }
   public void Get() {
      var response = httpClient.GetAsync("");
   }
   public void Post(string request) {
      var response = httpClient.PostAsync("", new StringContent(request));
   }
}
Requests - How Http Requests Work?

Python’s Requests is a HTTP library that will help us exchange data between the client and the server. Consider you have a UI with a form, wherein you need to enter the user details, so once you enter it, you have to submit the data which is nothing but a Http POST or PUT request from the client to server to save the data.
When you want the data, you need to fetch it from the server, which is again a Http GET request. The exchange of data between the client when it requests the data and the server responding with the required data, this relationship between the client and the server is very important.
The request is made to the URL given and it could be a secure or non-secure URL.
The request to the URL can be done using GET, POST, PUT, DELETE. The most commonly used is the GET method, mainly used when you want to fetch data from the server.
You can also send data to the URL as a query string for example −
https://jsonplaceholder.typicode.com/users?id=9&username=Delphine
So here, we are passing id = 9 and username = Delphine to the URL. All the values are sent in key/value pair after the question mark(?) and multiple params are passed to the URL separated by &.
Using the request library, the URL is called as follows using a string dictionary.
Wherein the data to the URL is sent as a dictionary of strings. If you want to pass id = 9 and username = Delphine, you can do as follows −
payload = {'id': '9', 'username': 'Delphine'}

The requests library is called as follows −
res = requests.get('https://jsonplaceholder.typicode.com/users', 
params = payload')

res = requests.post('https://jsonplaceholder.typicode.com/users', data =
{'id':'9', 'username':'Delphine'})

res = requests.put('https://jsonplaceholder.typicode.com/users', data =
{'id':'9', 'username':'Delphine'})

res = requests.delete('https://jsonplaceholder.typicode.com/users')

The response from the Http request can be in text encoded form, binary encoded, json format or raw response. The details of the request and response are explained in detail in the next chapters.
 Print
 Add Notes
 Bookmark this page
How to interact with hidden elements in Selenium Webdriver?

We can interact with hidden elements in Selenium Webdriver. The hidden elements are the ones that are present in the DOM but not visible on the page. Mostly the hidden elements are defined by the CSS property style="display:none;". In case an element is a part of the form tag, it can be hidden by setting the attribute type to the value hidden.
Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method. The commands to be run are passed as arguments to the method.
First of all, the getElementById method can be used to identify the element. Next to enter text to the field, the value method is used to set value to the field.
Syntax
executor.executeScript
("document.getElementById('txt').value='Selenium'");
Let’s take an example where there are two buttons Hide and Show. Also there is an edit box below the buttons. Once we click on the Hide button, the edit box disappears from the page.
Now let us enter some text inside the hidden text box.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ElementHidden{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      //URL launch
      driver.get("https://learn.letskodeit.com/p/practice");

      // identify element and click
      driver.findElement(By.id("hide-textbox")).click();

      // Javascript executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor) driver;

      // identify element and set value
      j.executeScript
      ("document.getElementById('displayed-text').value='Selenium';");
      String s = (String) j.executeScript("return
      document.getElementById('displayed-text').value");
      System.out.print("Value entered in hidden field: " +s);
      driver.close()
   }
}
How to Convert Dataframe column into an index in Python-Pandas? - GeeksforGeeks

21 Jul, 2021
Pandas provide a convenient way to handle data and its transformation. Let’s see how can we convert a data frame column to row name or index in Pandas. Create a dataframe first with dict of lists.  
Python3
# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra", "Ramlal"],       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],       'Score':["80", "90", "60", "30", "50"],       'Result': ["Pass", "Pass", "Pass", "Fail", "Fail"]} # creating a dataframedf = pd.DataFrame(data)  df
Output:  
Method #1: Using set_index() method. 
Python3
# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra", "Ramlal"],       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],       'Score':["80", "90", "60", "30", "50"],       'Result': ["Pass", "Pass", "Pass", "Fail", "Fail"]} # Creating a dataframedf = pd.DataFrame(data) # Using set_index() method on 'Name' columndf = df.set_index('Name') df
Output:  
Now, set index name as None.  
Python3
# set the index to 'None' via its name propertydf.index.names = [None] df
Output:  
 Method #2: Using pivot() method.In order to convert a column to row name or index in dataframe, Pandas has a built-in function Pivot. Now, let’s say we want Result to be the rows/index, and columns be name in our dataframe, to achieve this pandas has provided a method called Pivot. Let us see how it works, 
Python3
# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'name':["Akash", "Geeku", "Pankaj", "Sumitra", "Ramlal"],       'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"],       'Score':["80", "90", "60", "30", "50"],       'Result': ["Pass", "Pass", "Pass", "Fail", "Fail"]} df = pd.DataFrame(data) # pivoting the dataframedf.pivot(index ='Result', columns ='name') df
Output:  
 
gabaa406
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
Python - Matrix elements Frequencies Counter - GeeksforGeeks

30 Dec, 2020
Sometimes, while working with python Matrix, we can have a problem in which we need to find frequencies of all elements in Matrix. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using Counter() + sum() + map()The combination of above methods can be used to perform this task. In this, we perform task of counting elements using Counter() and extending the logic to each row is performed using sum() and map().
# Python3 code to demonstrate # Matrix elements Frequencies Counter# using Counter() + sum() + map()from collections import Counter  # Initializing listtest_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]  # printing original listprint("The original list is : " + str(test_list))  # Matrix elements Frequencies Counter# using Counter() + sum() + map()res = dict(sum(map(Counter, test_list), Counter()))  # printing result print ("The frequencies dictionary is : " + str(res))
The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : {2: 1, 4: 2, 5: 3, 6: 2, 7: 1}

 
Method #2 : Using chain() + Counter()The combination of above functions can be used to perform this task. In this, we flatten the matrix using chain() and compute frequency using Counter().
# Python3 code to demonstrate # Matrix elements Frequencies Counter# using Counter() + chain()from collections import Counterimport itertools  # Initializing listtest_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]  # printing original listprint("The original list is : " + str(test_list))  # Matrix elements Frequencies Counter# using Counter() + chain()res = dict(Counter(itertools.chain(*test_list)))  # printing result print ("The frequencies dictionary is : " + str(res))
The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The frequencies dictionary is : {2: 1, 4: 2, 5: 3, 6: 2, 7: 1}

Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python PIL | putdata() method

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
putdata() Copies pixel data to this image. This method copies data from a sequence object into the image, starting at the upper left corner (0, 0), and continuing until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: pixel = value*scale + offset.
Syntax: Image.putdata(data, scale=1.0, offset=0.0)
Parameters:data – A sequence object.scale – An optional scale value. The default is 1.0.offset – An optional offset value. The default is 0.0.
Returns: an image
     # from pure python list datafrom PIL import Image  img = Image.new("L", (104, 104))  # single bandnewdata = list(range(0, 256, 4)) * 104img.putdata(newdata)img.show()
Output:
Another Example:Here changing parameters.
     # from pure python list datafrom PIL import Image  img = Image.new("L", (224, 224))newdata = list(range(0, 256, 4)) * 224img.putdata(newdata)img.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | parseXML() Method

30 Apr, 2020
This parseXML() Method in jQuery is used to parse a string into an XML document.
Syntax:
jQuery.parseXML( data )
Parameters: This method accept single parameter which is mentioned above and described below:
data: This parameter holds the well-formed XML string to be parsedd.
Return Value: It returns the XML document.
Below exa,ples illustrate the parseXML() method in jQuery:Example 1: In this example, the parseXML() method parses a string into an XML document.
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>JQuery | parseXML() method</title>    <script src="https://code.jquery.com/jquery-3.4.1.js">    </script>    <style>        #a {            color: blue;        }                  #b {            color: red;        }    </style></head>  <body style="text-align:center;">      <h1 style="color: green">         GeeksforGeeks     </h1>      <h3>JQuery | parseXML() method</h3>    <p id="a"></p>    <p id="b"></p>      <script>        var xml = "<rss version='2.0'>"+                    "<channel>"+                       "<body>String : parseXML</body>"+                     "</channel>"+                  "</rss>",            xmlDoc = $.parseXML(xml),            $xml = $(xmlDoc),            $body = $xml.find("body");          $("#a").append($body.text());        $body.text("XMLDocument : parseXML");        $("#b").append($body.text());    </script></body>  </html>
Output:
Example 2: .
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>JQuery | parseXML() method</title>    <script src="https://code.jquery.com/jquery-3.4.1.js">    </script>    <style>        #a {            color: blue;        }                  #b {            color: red;        }    </style></head>  <body style="text-align:center;">      <h1 style="color: green">         GeeksforGeeks     </h1>      <h3>JQuery | parseXML() method</h3>    <p id="a"></p>    <p id="b"></p>      <script>        var xml = "<rss version='2.0'>"+                    "<channel>"+                      "<body style='text-align:center;'>"+                        "<h1 style='color: green'>GeeksForGeeks</h1>"+                        "<h3>JQuery | parseXML() method</h3>"+                      "</body>"+                    "</channel>"+                  "</rss>",            xmlDoc = $.parseXML(xml),            $xml = $(xmlDoc),            $val = $xml.find("h3");        $val.text("Parses a string into an XML document.");        $("#a").append($val.text());    </script></body>  </html>    
Output:
jQuery-Methods
JQuery
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
jQuery | children() with Examples
Scroll to the top of the page using JavaScript/jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to get the value in an input text box using jQuery ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
stack top() in C++ STL

21 Jun, 2022
Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end called the top of the stack, and an element is removed from the same end only.
stack::top() top() function is used to reference the top(or the newest) element of the stack.
Syntax :  
stackname.top()
Parameters: No value is needed to pass as the parameter.Return Value: Direct reference to the top element of the stack container.
Examples:  
Input  : stackname.push(5);
         stackname.push(1);
         stackname.top();
Output : 1

Input  : stackname.push(5);
         stackname.push(1);
         stackname.push(2);
         stackname.top();
Output : 2
Errors and Exceptions 
If the stack container is empty, it causes undefined behaviorIt has a no exception throw guarantee if the stack is not empty
If the stack container is empty, it causes undefined behavior
It has a no exception throw guarantee if the stack is not empty
C++
// CPP program to illustrate// Implementation of top() function#include <iostream>#include <stack>using namespace std; int main(){    stack<int> mystack;    mystack.push(5);    mystack.push(1);    mystack.push(2);     // Stack top    cout << mystack.top();    return 0;}
Output:  
2
Time Complexity: O(1)
Auxiliary Space: O(n)
Application : Given a stack of integers, find the sum of the all the integers.  
Input : 1, 8, 3, 6, 2
Output: 20
Algorithm  
Check if the stack is empty, if not add the top element to a variable initialized as 0, and pop the top element.Repeat this step until the stack is empty.Print the final value of the variable.
Check if the stack is empty, if not add the top element to a variable initialized as 0, and pop the top element.
Repeat this step until the stack is empty.
Print the final value of the variable.
C++
// CPP program to illustrate// Application of top() function#include <iostream>#include <stack>using namespace std; int main(){    int sum = 0;    stack<int> mystack;    mystack.push(1);    mystack.push(8);    mystack.push(3);    mystack.push(6);    mystack.push(2);     // Stack becomes 1, 8, 3, 6, 2     while (!mystack.empty()) {        sum = sum + mystack.top();        mystack.pop();    }    cout << sum;    return 0;}
Output:  
20 
Time Complexity: O(n)
Auxiliary Space: O(n)
Vik_24
chhabradhanvi
utkarshgupta110092
cpp-containers-library
CPP-Library
cpp-stack
cpp-stack-functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Object Oriented Programming in C++
The C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
Sorting a vector in C++
Python | os.path.split() method

21 Oct, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is submodule of OS module in Python used for common pathname manipulation.
os.path.split() method in Python is used to Split the path name into a pair head and tail. Here, tail is the last path name component and head is everything leading up to that.
For example consider the following path name:
path name = '/home/User/Desktop/file.txt'

In the above example ‘file.txt’ component of path name is tail and ‘/home/User/Desktop/’ is head.The tail part will never contain a slash; if name of the path ends with a slash, tail will be empty and if there is no slash in path name, head will be empty.
For example:
     path                             head                 tail
'/home/user/Desktop/file.txt'   '/home/user/Desktop/'   'file.txt'
'/home/user/Desktop/'           '/home/user/Desktop/'    {empty}
'file.txt'                           {empty}            'file.txt'

Syntax: os.path.split(path)
Parameter:path: A path-like object representing a file system path. A path-like object is either a str or bytes object representing a path.
Return Type: This method returns a tuple that represents head and tail of the specified path name.
# Python program to explain os.path.split() method     # importing os module import os  # pathpath = '/home/User/Desktop/file.txt'  # Split the path in # head and tail pairhead_tail = os.path.split(path)  # print head and tail# of the specified pathprint("Head of '% s:'" % path, head_tail[0])print("Tail of '% s:'" % path, head_tail[1], "\n")    # pathpath = '/home/User/Desktop/'  # Split the path in # head and tail pairhead_tail = os.path.split(path)  # print head and tail# of the specified pathprint("Head of '% s:'" % path, head_tail[0])print("Tail of '% s:'" % path, head_tail[1], "\n")  # pathpath = 'file.txt'  # Split the path in # head and tail pairhead_tail = os.path.split(path)  # print head and tail# of the specified pathprint("Head of '% s:'" % path, head_tail[0])print("Tail of '% s:'" % path, head_tail[1])
Head of '/home/User/Desktop/file.txt': /home/User/Desktop
Tail of '/home/User/Desktop/file.txt': file.txt 

Head of '/home/User/Desktop/': /home/User/Desktop
Tail of '/home/User/Desktop/':  

Head of 'file.txt': 
Tail of 'file.txt': file.txt

Code #2: If path is empty
# Python program to explain os.path.split() method     # importing os module import os  # pathpath = ''  # Split the path in # head and tail pairhead_tail = os.path.split(path)  # print head and tail# of the specified pathprint("Head of '% s':" % path, head_tail[0])print("Tail of '% s':" % path, head_tail[1])    # os.path.split() function# will return empty# head and tail if # specified path is empty
Head of '': 
Tail of '':

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