code-rag-bench/online-tutorials huggingface dataset:
Groovy - Unit Testing

The fundamental unit of an object-oriented system is the class. Therefore unit testing consists of testig within a class. The approach taken is to create an object of the class under testing and use it to check that selected methods execute as expected. Not every method can be tested, since it is not always pratical to test each and every thing. But unit testing should be conducted for key and critical methods.
JUnit is an open-source testing framework that is the accepted industry standard for the automated unit testing of Java code. Fortunately, the JUnit framework can be easily used for testing Groovy classes. All that is required is to extend the GroovyTestCase class that is part of the standard Groovy environment. The Groovy test case class is based on the Junit test case.
Let assume we have the following class defined in a an application class file −
class Example {
   static void main(String[] args) {
      Student mst = new Student();
      mst.name = "Joe";
      mst.ID = 1;
      println(mst.Display())
   } 
} 
 
public class Student {
   String name;
   int ID;
	
   String Display() {
      return name +ID;
   }  
}
The output of the above program is given below.
Joe1

And now suppose we wanted to write a test case for the Student class. A typical test case would look like the one below. The following points need to be noted about the following code −
The test case class extends the GroovyTestCase class
We are using the assert statement to ensure that the Display method returns the right string.
class StudentTest extends GroovyTestCase {
   void testDisplay() {
      def stud = new Student(name : 'Joe', ID : '1')
      def expected = 'Joe1'
      assertToString(stud.Display(), expected)
   }
}
Normally as the number of unit tests increases, it would become difficult to keep on executing all the test cases one by one. Hence Groovy provides a facility to create a test suite that can encapsulate all test cases into one logicial unit. The following codesnippet shows how this can be achieved. The following things should be noted about the code −
The GroovyTestSuite is used to encapsulate all test cases into one.
The GroovyTestSuite is used to encapsulate all test cases into one.
In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing.
In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing.
import groovy.util.GroovyTestSuite 
import junit.framework.Test 
import junit.textui.TestRunner 

class AllTests { 
   static Test suite() { 
      def allTests = new GroovyTestSuite() 
      allTests.addTestSuite(StudentTest.class) 
      allTests.addTestSuite(EmployeeTest.class) 
      return allTests 
   } 
} 

TestRunner.run(AllTests.suite())

    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
HTML DOM Anchor target Property

The HTML DOM target property associated with the anchor tag (<a>) specifies where the new web page will open after clicking the URL. It can have the following values −
_blank − This will open the linked document in a new window.
_parent − This will open the linked document in the parent frameset.
_top − This will open the linked document in the full body window.
_self − This will open the linked document in the same window. This is the default behavior
framename − This will open the linked document in the specified framename.
Following is the syntax for −
Returning the target property −
anchorObject.target
Setting the target property −
anchorObject.target = "_blank|_self|_parent|_top|framename"
Let us see an example of anchor target property −
Live Demo
<!DOCTYPE html>
<html>
<body>
<p><a id="Anchor" target="_self" href="https://www.examplesite.com">example site</a></p>
<p><a id="Anchor2" href="https://www.examplesite.com">example site</a></p>
<p>Click the button to see the value of the target attribute.</p>
<button onclick="getTarget1()">GetTarget</button>
<button onclick="setTarget2()">SetTarget</button>
<p id="Target1"></p>
<script>
   function getTarget1() {
      var x = document.getElementById("Anchor").target;
      document.getElementById("Target1").innerHTML = x;
   }
   function setTarget2(){
      document.getElementById("Anchor2").innerHTML="Target has been set";
      document.getElementById("Target1").target="newframe";
   }
</script>
</body>
</html>
This will produce the following output −
After clicking on “GetTarget” button −
After clicking on “SetTarget” button −
In the above example −
We have taken one anchor tag with target attribute and with a value _self and another one with default _blank −
<p><a id="Anchor" target="_self" href="https://www.examplesite.com">example site</a></p>
<p><a id="Anchor2" href="https://www.examplesite.com">example site</a></p>
We have then created two buttons named GetTarget and SetTarget to execute the getTarget1() and setTarget2() functions respectively.
<button onclick="getTarget1()">GetTarget</button>
<button onclick="setTarget2()">SetTarget</button>
The getTarget1() will get the target value from the first link and display in the paragraph tag with id=”Target1”. The setTarget2() will set the target value of link2 from default _blank to custom frame “newframe”.
function getTarget1() {
   var x = document.getElementById("Anchor").target;
   document.getElementById("Target1").innerHTML = x;
}
function setTarget2(){
   document.getElementById("Target1").innerHTML="Target has been set";
   document.getElementById("Anchor2").target="_blank";
}
Can we add null elements to a Set in Java?

A Set is a collection that cannot contain duplicate elements. It models the mathematical set abstraction.
It does not allow duplicate elements and allow one null value at most.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
There are three classes implementing this interface −
HashSet − Set implementation based on hash table.
LinkedHashSet − HashSet implementation based on linked list.
TreeSet − Set implementation based on trees.
As per the definition a set object does not allow duplicate values but it does allow at most one null value.
Null values in HashSet − The HashSet object allows null values but, you can add only one null element to it. Though you add more null values if you try to print its contents, it displays only one null.
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
   public static void main(String args[]) {
      Set<Integer> hashSet = new HashSet<Integer>();
      //Populating the HashSet
      hashSet.add(1124);
      hashSet.add(3654);
      hashSet.add(7854);
      hashSet.add(9945);
      System.out.println(hashSet);
      //Adding null elements
      hashSet.add(null);
      hashSet.add(null);
      hashSet.add(null);
      System.out.println(hashSet);
   }
}
[1124, 3654, 9945, 7854]
[null, 1124, 3654, 9945, 7854]
Null values in LinkedHashSet: Just like the HashSet object, this also allows null values but, you can add only one null element to it. Though you add more null values if you try to print its contents, it displays only one null.
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetExample {
   public static void main(String args[]) {
      Set<Integer> linkedHashSet = new LinkedHashSet<Integer>();
      //Populating the HashSet
      linkedHashSet.add(1124);
      linkedHashSet.add(3654);
      linkedHashSet.add(7854);
      linkedHashSet.add(9945);
      System.out.println(linkedHashSet);
      //Adding null elements
      linkedHashSet.add(null);
      linkedHashSet.add(null);
      linkedHashSet.add(null);
      System.out.println(linkedHashSet);
   }
}
[1124, 3654, 9945, 7854]
[null, 1124, 3654, 9945, 7854]
Null values in TreeSet − The TreeSet object doesn’t allows null values but, If you try to add them, a runtime exception will be generated at.
import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
   public static void main(String args[]) {
      Set<Integer> treeSet = new TreeSet<Integer>();
      //Populating the HashSet
      treeSet.add(1124);
      treeSet.add(3654);
      treeSet.add(7854);
      treeSet.add(9945);
      System.out.println(treeSet);
      //Adding null elements
      treeSet.add(null);
      treeSet.add(null);
      treeSet.add(null);
      System.out.println(treeSet);
   }
}
[1124, 3654, 7854, 9945]
Exception in thread "main" java.lang.NullPointerException
   at java.util.TreeMap.put(Unknown Source)
   at java.util.TreeSet.add(Unknown Source)
   at MyPackage.TreeSetExample.main(TreeSetExample.java:16)
How can we implement a custom iterable in Java?

An Iterable interface is defined in java.lang package and introduced with Java 5 version. An object that implements this interface allows it to be the target of the "for-each" statement. This for-each loop is used for iterating over arrays and collections. An Iterable interface can also be implemented to create custom behavior.
public interface Iterable<T>
import static java.lang.String.format;
import java.util.*;
// Person class
class Person {
   private String firstName, lastName;
   private int age;
   public Person(){ }
   public Person(String firstName, String lastName, int age) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getAge() {
      return age;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public void setAge(int age) {
      this.age = age;
   }
   @Override
   public String toString() {
      return format("First Name:\t%s\tLast Name:\t%s\tAge:\t%d", firstName, lastName, age);
   }
}
// PersonArrayList class
public class PersonArrayList implements Iterable<Person> {
   private List<Person> persons;
   private static final int MIN_AGE = 10;
   public PersonArrayList() {
      persons = new ArrayList<Person>(MIN_AGE);
   }
   public PersonArrayList(int age) {
      persons = new ArrayList<Person>(age);
   }
   public void addPerson(Person p) {
      persons.add(p);
   }
   public void removePerson(Person p) {
      persons.remove(p);
   }
   public int age() {
      return persons.size();
   }
   @Override
   public Iterator<Person> iterator() {
      return persons.iterator();
   }
   public static void main(String[] args) {
      Person p1 = new Person("Adithya", "Sai", 20);
      Person p2 = new Person("Jai","Dev", 30);
      PersonArrayList pList = new PersonArrayList();
      pList.addPerson(p1);
      pList.addPerson(p2);
      for (Person person : pList) {
         System.out.println(person);
      }
   }
}
First Name:  Adithya   Last Name:   Sai   Age:   20
First Name:  Jai       Last Name:   Dev   Age:   30
Perl kill Function

This function sends a signal to a list of processes. Returns the number of processes successfully signaled.
If SIGNAL is zero, no signal is sent to the process. This is a useful way to check that a child process is alive and hasn't changed its UID. The precise list of signals supported is entirely dependent on the system implementation −
Name 		   Effect
SIGABRT		Aborts the process
SIGARLM		Alarm signal
SIGFPE		Arithmetic exception
SIGHUP 		Hang up.
SIGILL 		Illegal instruction
SIGINT 		Interrupt
SIGKILL 	 Termination signal
SIGPIPE 	 Write to a pipe with no readers.
SIGQUIT		Quit signal.
SIGSEGV		Segmentation fault
SIGTERM		Termination signal
SIGUSER1	 Application-defined signal 1
SIGUSER2	 Application-defined signal 2

Following is the simple syntax for this function −
kill EXPR, LIST

This function returns the number of processes successfully signaled.
Following is the example code showing its basic usage −
#!/usr/bin/perl

$cnt = kill 0, getppid(), getpgrp(), 2000;

print "Signal sent to $cnt process\n";
When above code is executed, it produces the following result −
Signal sent to 2 process


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to set new id attribute with jQuery?

To implement this, extract id from attr() and use replace() to replace the id attribute.
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <div id="first-name">
</body>
<script>
   $('[id*="-"]').each(function () {
      console.log('Previous Id attribute: ' + $(this).attr('id'));
      $(this).attr('id', $(this).attr('id').replace('-', '----'));
      console.log('Now Id Attribute: ' + $(this).attr('id'));
   });
</script>
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Following is the value on console −
How to use PowerShell as a Calculator? Or How to use PowerShell for arithmetic operations?

You can use the PowerShell console to perform arithmetic operations, the same way the calculator does.
You can use the PowerShell console to perform arithmetic operations, the same way the calculator does.
To do the addition operation,
2+3
Output − 5
For complex, additional operations as well it is too quick.
For complex, additional operations as well it is too quick.
10024455 + 554668 + 9964455
Output − 20543578
Floating numbers operation,
Floating numbers operation,
5569899.65 + 554886.32
Output − 6124785.97
To perform subtract operation,
To perform subtract operation,
55564488556 - 55141256665

Output − 423231891
With Integer and floating number subtraction,
With Integer and floating number subtraction,
5569899 - 554886.32
Output − 5015012.68
Divide Operation,
Divide Operation,
556989 / 554
Output − 1005.39530685921
Multiplication operation,
Multiplication operation,
5533 * 445
Output − 2462185
Multiple Operations,
Multiple Operations,
(445 + 5443) * 332 / 32

Output − 61088
When you perform any arithmetic operation, when values separated by command, it will give the wrong values. For example,
When you perform any arithmetic operation, when values separated by command, it will give the wrong values. For example,
5,4 + 2
Output −
5
4
2
The above output is wrong because the comma(,) creates an array.
Powershell also works with Units like MB, GB, and KB. When you specify number and unit, there should not be space in between them. For example, 12mb is valid but 12 mb is invalid. It is case insensitive, so you can use MB or mb, GB or gb or KB or kb.
Powershell also works with Units like MB, GB, and KB. When you specify number and unit, there should not be space in between them. For example, 12mb is valid but 12 mb is invalid. It is case insensitive, so you can use MB or mb, GB or gb or KB or kb.
1gb / 1mb
Output − 1024
2gb * 6
Output − 12884901888
5GB - 2GB

Output − 3221225472
PowerShell also understands the hexadecimal values.
PowerShell also understands the hexadecimal values.
15 + 0xAF
Output − 190
0xAFF
Output − 2815
How to prevent Serialization to break a Singleton Class Pattern?

A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using serialization, we can still create multiple instance of a class. See the example below −
 Live Demo
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Tester{
   public static void main(String[] args)
   throws ClassNotFoundException, IOException{

      A a = A.getInstance();
      A b = (A) getSerializedCopy(a);

      System.out.println(a.hashCode());
      System.out.println(b.hashCode());
   }

   public static Object getSerializedCopy(Object sourceObject)
   throws IOException, ClassNotFoundException {
      ObjectOutputStream objectOutputStream = null;
      ObjectInputStream objectInputStream = null;
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
      objectOutputStream.writeObject(sourceObject);
      objectOutputStream.flush();
      objectInputStream = new ObjectInputStream(

      new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
      return objectInputStream.readObject();
   }
}

class A implements Serializable {
   private static A a;
   private A(){}

   public static A getInstance(){
      if(a == null){
         a = new A();
      }
      return a;
   }
}
1550089733
865113938
Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −
Override readResolve() method in the singleton class.
// implement readResolve method
protected Object readResolve() {
   return a;
}
1550089733
1550089733
Scala List take() method with example - GeeksforGeeks

13 Aug, 2019
The take() method belongs to the value member of the class List. It is utilized to take the first n elements from the list.
Method Definition: deftake(n: Int): List[A]
Where, n is the number of elements to be taken from the list.
Return Type:It returns a list containing only the first n elements from the stated list or returns the whole list if n is more than the number of elements in the given list.
Example #1:
// Scala program of take()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a List         val list = List(1, 2, 3, 4, 5, 6, 7)                  // Applying take method         val result = list.take(4)                  // Displays output        println(result)          }}
List(1, 2, 3, 4)

Example #2:
// Scala program of take()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a List         val list = List("a", "b", "c", "d", "e", "f")                  // Applying take method         val result = list.take(4)                  // Displays output        println(result)          }}
List(a, b, c, d)

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Operators in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Constructors
Scala String substring() method with example
Scala | Arrays
How to get the first element of List in Scala
Scala String replace() method with example
JavaScript | Intl.DateTimeFormat.prototype.resolvedOptions() Method - GeeksforGeeks

20 Nov, 2021
The Intl.DateTimeFormat.prototype.resolvedOptions() method is an inbuilt method in JavaScript which returns a new object with properties reflecting the locale, date and time formatting options computed during initialization of this DateTimeFormat object.Syntax:  
dateTimeFormat.resolvedOptions()
Parameters: This method does not accept any parameters.Return value: This method returns a new object with properties reflecting the locale and date and time.Below examples illustrate the Intl.DateTimeFormat.prototype.resolvedOptions() method in JavaScript:Example 1:  
javascript
const geeks = new Intl.DateTimeFormat('zh-CN', { timeZone: 'UTC' });const result = geeks.resolvedOptions();console.log(result.locale);console.log(result.calendar);console.log(result.timeZone); const geeks1 = new Intl.DateTimeFormat('LT');const result1 = geeks1.resolvedOptions();console.log(result1.locale);console.log(result1.calendar);
Output:  
"zh-CN"
"gregory"
"UTC"
"lt"
"gregory"
Example 2:  
javascript
var geeks = new Intl.DateTimeFormat('de-XX', { timeZone: 'UTC' });var result = geeks.resolvedOptions(); console.log(result.locale);      console.log(result.calendar);      console.log(result.numberingSystem);console.log(result.timeZone);       console.log(result.month);
Output:  
"de"
"gregory"
"latn"
"UTC"
"numeric"
Supported Browsers: The browsers supported by Intl.DateTimeFormat.prototype.resolvedOptions() method are listed below:  
Google Chrome 24 and above
Edge 12 and above
Firefox 29 and above
Opera 15 and above
Safari 10 and above
 
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to Find the Percentage of Two Cells in Microsoft Excel? - GeeksforGeeks

18 Jul, 2021
If you want to find the percentage of two cells in Microsoft Excel, Simply select an empty cell, where you want to display the percentage of the two cells.
Type in the following formula in the selected cell :
=address of cell1/address of cell2
For example, I want to print out the percentage of C2 and C3, so the formulae will be: =C2/C3, in an empty cell C4.
As soon as you click on the return key, You will get your percentage calculated in cell C4.
However, if a decimal value is displayed in the cell. Like 0.10, Simply press the shortcut key Ctrl+Shift+% to format as a percent or convert the numeric value into the percentage style and press the Return key.
The Decimal value will be converted to a percentage.
Before
After
You can also go to the Number section under the Home tab and press the % Symbol to convert to percentage format.
% symbol under the Number listbox
Microsoft
Picked
Excel
Microsoft
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
Macros in Excel
How to Get Length of Array in Excel VBA?
How to Remove Duplicates From Array Using VBA in Excel?
How to Extract the Last Word From a Cell in Excel?
Using CHOOSE Function along with VLOOKUP in Excel
Introduction to Excel Spreadsheet
How to Show Percentages in Stacked Column Chart in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
Docker - Installation

Let’s go through the installation of each product.
Once the installer has been downloaded, double-click it to start the installer and then follow the steps given below.
Step 1 − Click on the Agreement terms and then the Install button to proceed ahead with the installation.
Step 2 − Once complete, click the Finish button to complete the installation.
Once the installer has been downloaded, double-click it to start the installer and then follow the steps given below.
Step 1 − Click the Next button on the start screen.
Step 2 − Keep the default location on the next screen and click the Next button.
Step 3 − Keep the default components and click the Next button to proceed.
Step 4 − Keep the Additional Tasks as they are and then click the Next button.
Step 5 − On the final screen, click the Install button.
Let’s now look at how Docker Toolbox can be used to work with Docker containers on Windows. The first step is to launch the Docker Toolbox application for which the shortcut is created on the desktop when the installation of Docker toolbox is carried out.
Next, you will see the configuration being carried out when Docker toolbox is launched.
Once done, you will see Docker configured and launched. You will get an interactive shell for Docker.
To test that Docker runs properly, we can use the Docker run command to download and run a simple HelloWorld Docker container.
The working of the Docker run command is given below −
docker run 

This command is used to run a command in a Docker container.
docker run image

Image − This is the name of the image which is used to run the container.
Image − This is the name of the image which is used to run the container.
The output will run the command in the desired container.
sudo docker run hello-world
This command will download the hello-world image, if it is not already present, and run the hello-world as a container.
When we run the above command, we will get the following result −
If you want to run the Ubuntu OS on Windows, you can download the Ubuntu Image using the following command −
Docker run –it ubuntu bash

Here you are telling Docker to run the command in the interactive mode via the –it option.
In the output you can see that the Ubuntu image is downloaded and run and then you will be logged in as a root user in the Ubuntu container.

    70 Lectures 
     12 hours 

 Anshul Chauhan

    41 Lectures 
     5 hours 

 AR Shankar

    31 Lectures 
     3 hours 

 Abhilash Nelson

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    33 Lectures 
     4 hours 

 Mumshad Mannambeth

    13 Lectures 
     53 mins

 Musab Zayadneh
 Print
 Add Notes
 Bookmark this page
Transmission Modes in Computer Networks (Simplex, Half-Duplex and Full-Duplex) - GeeksforGeeks

10 Mar, 2022
Transmission mode means transferring data between two devices. It is also known as a communication mode. Buses and networks are designed to allow communication to occur between individual devices that are interconnected. There are three types of transmission mode:-   
 
These are explained as following below.
1. Simplex Mode –In Simplex mode, the communication is unidirectional, as on a one-way street. Only one of the two devices on a link can transmit, the other can only receive. The simplex mode can use the entire capacity of the channel to send data in one direction. Example: Keyboard and traditional monitors. The keyboard can only introduce input, the monitor can only give the output. 
 
2. Half-Duplex Mode –In half-duplex mode, each station can both transmit and receive, but not at the same time. When one device is sending, the other can only receive, and vice versa. The half-duplex mode is used in cases where there is no need for communication in both directions at the same time. The entire capacity of the channel can be utilized for each direction. Example: Walkie-talkie in which message is sent one at a time and messages are sent in both directions. 
Channel capacity=Bandwidth * Propagation Delay
3. Full-Duplex Mode –In full-duplex mode, both stations can transmit and receive simultaneously. In full_duplex mode, signals going in one direction share the capacity of the link with signals going in another direction, this sharing can occur in two ways: 
Either the link must contain two physically separate transmission paths, one for sending and the other for receiving.
Or the capacity is divided between signals traveling in both directions.  
Full-duplex mode is used when communication in both directions is required all the time. The capacity of the channel, however, must be divided between the two directions. Example: Telephone Network in which there is communication between two persons by a telephone line, through which both can talk and listen at the same time. 
Channel Capacity=2* Bandwidth*propagation Delay
References- Data Communication and Network,5th Edition, Behrouz A.Forouzan. 
This article is contributed by Saloni Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
yeeshaj
Pushpender007
vaibhavsinghtanwar
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
Caesar Cipher in Cryptography
UDP Server-Client implementation in C
Socket Programming in Java
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Cryptography and its Types
Wireless Sensor Network (WSN)
Python | Group and count similar records - GeeksforGeeks

11 Nov, 2019
Sometimes, while working with records, we can have a problem in which we need to collect and maintain the counter value inside records. This kind of application is important in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + Counter() + set()The combination of above functionalities can be employed to achieve this task. In this, we run a loop to capture each tuple and add to set and check if it’s already existing, then increase and add a counter value to it. The cumulative count is achieved by using Counter().
# Python3 code to demonstrate working of# Group and count similar records# using Counter() + loop + set()from collections import Counter  # initialize listtest_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ),                       ('is', ), ('for', ), ('geeks', )]  # printing original listprint("The original list : " + str(test_list))  # Group and count similar records# using Counter() + loop + set()res = []temp = set()counter = Counter(test_list)for sub in test_list:    if sub not in temp:        res.append((counter[sub], ) + sub)        temp.add(sub)  # printing resultprint("Grouped and counted list is : " + str(res))
The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ), (‘for’, ), (‘geeks’, )]Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1, ‘for’), (1, ‘geeks’)]
 
Method #2 : Using Counter() + list comprehension + items()
This is one liner approach and recommended to use for programming. The task of loops is handled by list comprehension and items() is used to access all the elements of Counter converted dictionary to allow computations.
# Python3 code to demonstrate working of# Group and count similar records# using Counter() + list comprehension + items()from collections import Counter  # initialize listtest_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ),                       ('is', ), ('for', ), ('geeks', )]  # printing original listprint("The original list : " + str(test_list))  # Group and count similar records# using Counter() + list comprehension + items()res = [(counter, ) + ele for ele, counter in Counter(test_list).items()]  # printing resultprint("Grouped and counted list is : " + str(res))
The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ), (‘for’, ), (‘geeks’, )]Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1, ‘for’), (1, ‘geeks’)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
GATE | GATE-CS-2017 (Set 1) | Question 14 - GeeksforGeeks

16 Sep, 2021
Consider the following intermediate program in three address code
p  = a - b
q = p * c
p = u * v
q = p + q

Which one of the following corresponds to a static single assignment from the above code
A)
p1 = a - b
q 1 = p1 * c
p1 = u * v
q1 = p1 + q1  

B)
p3 = a - b
q4 = p3 * c
p4 = u * v
q5 = p4 + q4

C)
p 1 = a - b
q1 = p2   * c
p3 = u * v
q2 = p4 + q3

D)
p1 = a - b
q1 = p * c
p2 = u * v
q2 = p + q

(A) A(B) B(C) C(D) DAnswer: (B)Explanation: According to Static Single Assignment
A variable cannot be used more than once in the LHSA variable should be initialized atmost once.
A variable cannot be used more than once in the LHS
A variable should be initialized atmost once.
Now looking at the given options
a – code violates condition 1 as p1 is initialized again in this statement: p1 = u * v
c- code is not valid as  q1 = p2 * c , q2 = p4 + q3 – In these statements p2, p4, q3 are not initialized anywhere
d- code is invalid as  q2 = p + q is incorrect without moving it to register
Therefore, option B is only correct option.
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:55 / 59:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4ab8S2Qs7h8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Java Program to convert integer to boolean - GeeksforGeeks

02 Jan, 2020
Given a integer value, the task is to convert this integer value into a boolean value in Java.
Examples:
Input: int = 1
Output: true

Input: int = 0
Output: false

Approach:
Get the boolean value to be converted.
Check if boolean value is true or false
If the integer value is greater than equal to 1, set the boolean value as true.
Else if the integer value is greater than 1, set the boolean value as false.
Example 1:
// Java Program to convert integer to boolean  public class GFG {      public static void main(String[] args)    {          // The integer value        int intValue = 1;          // The expected boolean value        boolean boolValue;          // Check if it's greater than equal to 1        if (intValue >= 1) {            boolValue = true;        }        else {            boolValue = false;        }          // Print the expected integer value        System.out.println(            intValue            + " after converting into boolean = "            + boolValue);    }}
1 after converting into boolean = true

Example 2:
// Java Program to convert integer to boolean  public class GFG {      public static void main(String[] args)    {          // The integer value        int intValue = 0;          // The expected boolean value        boolean boolValue;          // Check if it's greater than equal to 1        if (intValue >= 1) {            boolValue = true;        }        else {            boolValue = false;        }          // Print the expected integer value        System.out.println(            intValue            + " after converting into boolean = "            + boolValue);    }}
0 after converting into boolean = false

Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List 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
Template Inheritance in Flask - GeeksforGeeks

05 Sep, 2020
Template inheritance is a very good feature of Jinja templating . Jinja is a web template engine for the Python programming language . We have seen that webpages of a website contains same footer , navigation bar etc.  So instead of making same footer and navigation bar in all webpages separately , we make use of template inheritance , which allows us to create the part which is same in all webpages (eg. footer,navigation bar) only once and we also don’t need to write the html , head , title tag again and again . Lets define the common structure of web pages in base.html file. First of all we will render  template using flask from main.py file .
Prerequisite –  Flask – (Creating first simple application)
 
Step 1 – Create a flask app to render the main template 
Python3
from flask import Flask, render_template  # Setting up the applicationapp = Flask(__name__)  # making route    @app.route('/')def home():    return render_template('home.html')    # running applicationif __name__ == '__main__':    app.run(debug=True)
Step 2 – Create HTML Files
Now we will set up our base.html file in which we have one heading which will be common in all webpages. 
Syntax : 
{% block content %}
{% endblock %}
The code above and below these lines will be the same for every web pages and the code between them will be for a specific web page . 
HTML
<!DOCTYPE html><html lang="en"><head>    <title>Template Inheritance</title></head><body>    <h1> This heading is common in all webpages </h1>    {% block content %}    {% endblock %}  </body></html>
  
Now we will set up our home.html file in which we will inherit template from “base.html” file and will write some code for 
home page also . 
Syntax :
  {% extends "base.html" %}
        {% block content %}
          write code here for home page only 
        {% endblock %}
HTML
{%extends "base.html" %}{%block content%}  <h1>Welcome to Home</h1>  {% endblock %}
      
Run your main.py file . 
Output – 
Below is the output.
        
This article is just a simple example. We can also add navigation bar , footer , etc to base.html file and can inherit to home.html file and many others .
Python Flask
Python
Web Technologies
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 ?
Different ways to create Pandas Dataframe
Python String | replace()
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python | Harmonic Mean of List - GeeksforGeeks

14 Jan, 2020
While working with Python, we can have a problem in which we need to find harmonic mean of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding harmonic mean and perform using loop shorthands. This is the most basic approach to solve this problem.
# Python3 code to demonstrate working of# Harmonic Mean of List# using loop + formula  # initialize listtest_list = [6, 7, 3, 9, 10, 15]  # printing original listprint("The original list is : " + str(test_list))  # Harmonic Mean of List# using loop + formulasum = 0for ele in test_list:    sum += 1 / ele    res = len(test_list)/sum  # printing resultprint("The harmonic mean of list is : " + str(res))
The original list is : [6, 7, 3, 9, 10, 15]
The harmonic mean of list is : 6.517241379310345

 
Method #2 : Using statistics.harmonic_mean()This task can also be performed using inbuilt function of harmonic_mean(). This is new in Python versions >= 3.8.
# Python3 code to demonstrate working of# Harmonic Mean of List# using statistics.harmonic_mean()import statistics   # initialize listtest_list = [6, 7, 3, 9, 10, 15]  # printing original listprint("The original list is : " + str(test_list))  # Harmonic Mean of List# using statistics.harmonic_mean()res = statistics.harmonic_mean(test_list)  # printing resultprint("The harmomin mean of list is : " + str(res))
The original list is : [6, 7, 3, 9, 10, 15]
The harmonic mean of list is : 6.517241379310345

Python list-programs
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
How to create Abstract Model Class in Django? - GeeksforGeeks

16 Feb, 2021
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
Model Inheritance in Django works almost identically to the way normal class inheritance works in python. In this article we will revolve around how to create abstract base class in Django Models.
Abstract Base Class :-
Abstract Base Class are useful when you want to put some common information into a number of other models. You write your base class and put abstract = True in the Meta Class. Suppose you have two model Student and Teacher.
models.py
Python3
from django.db import models    class Student(models.Model):  # STUDENT    name = models.CharField(max_length=100)    rollno = models.IntergerField()    class Teacher(models.Model):  # TEACHER    name = models.CharField(max_length=100)    ID = models.IntergerField()
So have you notice that one field name is common on  both models.
So instead of adding common fields in both models ,we have create a another model and put those common fields in that model.
models.py
Python3
from django.db import models    class common(models.Model):  # COMM0N    name = models.CharField(max_length=100)      class Meta:        abstract = True
So here I create a model common and put the common fields in that model.
Put abstract = True in the Meta class. After set abstract True, now it becomes an abstract class not a model,so now you can’t generate a database table.
Python3
class Student(common):  # STUDENT    rollno = models.IntegerField()    class Teacher(common):  # TEACHER    ID = models.IntegerField()
Ubuntu
python3 manage.py makemigrations
python3 manage.py migrate
Now you can inherit the common name field in both Student and Teacher. Just like normal python inheritance.
Output :
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Range Structure in C# 8.0 - GeeksforGeeks

09 Jul, 2021
C# 8.0 introduced a new predefined structure that is known as Range struct. This struct is used to represent a range that has a start and end indexes. It provides a new style to create a range using .. operator. This operator is used to create a range that has a starting and ending index. Also with the help of the Range struct you are allowed to create a variable of the range type.
C#
// C# program to illustrate how to create rangesusing System; namespace range_example { class GFG {     // Main Method    static void Main(string[] args)    {        int[] marks = new int[] {23, 45, 67, 88, 99,                            56, 27, 67, 89, 90, 39};         // Creating variables of range type        // And initialize the range        // variables with a range        // Using .. operator        Range r1 = 1..5;        Range r2 = 6..8;         var a1 = marks[r1];        Console.Write("Marks List 1: ");        foreach(var st_1 in a1)            Console.Write($" {st_1} ");         var a2 = marks[r2];        Console.Write("\nMarks List 2: ");        foreach(var st_2 in a2)            Console.Write($" {st_2} ");         // Creating a range        // Using .. operator        var a3 = marks[2..4];        Console.Write("\nMarks List 3: ");        foreach(var st_3 in a3)            Console.Write($" {st_3} ");         var a4 = marks[4..7];        Console.Write("\nMarks List 4: ");        foreach(var st_4 in a4)            Console.Write($" {st_4} ");    }}}
Output:
Marks List 1:  45  67  88  99 
Marks List 2:  27  67 
Marks List 3:  67  88 
Marks List 4:  99  56  27
 
gabaa406
rajeev0719singh
CSharp-8.0
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
Extension Method in C#
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Arrays
How to display a JFrame to the center of a screen in Java?

A JFrame is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. We can add the components to a JFrame to use its contentPane instead. A JFrame is like a Window with border, title, and buttons. We can implement most of the java swing applications using JFrame.
By default, a JFrame can be displayed at the top-left position of a screen. We can display the center position of JFrame using the setLocationRelativeTo() method of Window class.
public void setLocationRelativeTo(Component c)
import javax.swing.*;
import java.awt.*;
public class JFrameCenterPositionTest extends JFrame {
   public JFrameCenterPositionTest() {
      setTitle("JFrameCenter Position");
      add(new JLabel("JFrame set to center of the screen", SwingConstants.CENTER),                BorderLayout.CENTER);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null); // this method display the JFrame to center position of a screen
      setVisible(true);
   }
   public static void main (String[] args) {
      new JFrameCenterPositionTest();
   }
}