code-rag-bench/online-tutorials huggingface dataset:
Difference between Stop and Wait protocol and Sliding Window protocol - GeeksforGeeks

22 Apr, 2020
Both Stop and Wait protocol and Sliding Window protocol are the techniques to the solution of flow control handling. The main difference between Stop-and-wait protocol and Sliding window protocol is that in Stop-and-Wait Protocol, the sender sends one frame and wait for acknowledgment from the receiver whereas in sliding window protocol, the sender sends more than one frame to the receiver and re-transmits the frame(s) which is/are damaged or suspected.
Difference between Stop and Wait protocol and Sliding Window protocol:
1/(1+2*a)
N/(1+2*a)
ethansifferman
Computer Networks
Difference Between
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
RSA Algorithm in Cryptography
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Types of Network Topology
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
SAP Scripts - Standard Text

You can use standard texts in SAP to display the database stored value on the output document and this can be done using Transaction Code: SO10
Let us say you want to print terms and conditions on every invoice and you want each invoice to contain these legal terms and conditions directly. You can create a Standard text and use that in the Invoice.
Step 1 − Run Transaction SO10
You have different text options. This can be checked using the find option.
Step 2 − Select Standard text and click Enter by clicking the green tick mark.
Step 3 − To select any Text, click on Execute. You will see a list of all standard texts.
Step 4 − Select any of the following from the list. Here we have selected FI_CASH_SI and click the Display option.
You can see the following text appear by default.
Step 5 − You have to add this to your script.
                    Signed                                        
Enclosures
Prepared           Approved         Confirmed
Receipts    Expenditures 
&uline(130)&  

&rfcash-anzsb(Z)& &Rfcash-anzhb(Z)& 

Step 6 − Select the form that you want to change. Select and click the change option at the bottom. Then click on Go to → Change Editor.
Step 7 − Enter the text name, object Id, language, etc.
In a similar way, you can insert text symbols, system symbols, documentation, hypertext using the insert option at the top of the screen.
Using SO10 Transaction, you can also create your own standard text and give it a name and later can use it in a script.
You can write something and save it as standard text.
You can directly include this in your form. Open the form and click the Change button. Click Go to → Change Editor.
Using control commands, you can insert standard text created previously in your script.
System symbols are system maintained and their value is provided by the system. Some examples of system symbols are time, date, hours, minutes, seconds, page, etc.
You can maintain standard symbols using Transaction SM30. Examples of standard symbols are thank you, sincerely, etc. They are stored in table TTDG.
They are placeholders for database fields and also act as global program symbols in your Print program.

    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
JavaScript - How to create nested unordered list based on nesting of array?

Suppose, we have a nested array of arrays like this −
const arr = [
   'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'], 'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6' ];
We are required to write a JavaScript program that should map any such nested array of arrays of literals to nested unordered lists of HTML.
The only thing to take care of here is that the nesting of the ul has to be just identical to the nesting of the array.
The code for this will be −
JavaScript Code −
const arr = [
   'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'],
   'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6'
];
const prepareUL = (root, arr) => {
   let ul = document.createElement('ul');
   let li;
   root.appendChild(ul);
   arr.forEach(function(item) {
      if (Array.isArray(item)) {
         prepareUL(li, item);
         return;
      };
      li = document.createElement('li');
      li.appendChild(document.createTextNode(item));
      ul.appendChild(li);
   });
}
const div = document.getElementById('myList');
prepareUL(div, arr);
HTML Code −
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="myList"></div>
</body>
</html>
And the output will be −
Difference Between Keyword and Identifier

In this post, we will understand the difference between a keyword and an identifier.
They define a specific kind of entity.
They define a specific kind of entity.
It always starts with a lower case letter.
It always starts with a lower case letter.
They are pre-defined words that are reserved to work with programs.
They are pre-defined words that are reserved to work with programs.
They can’t be used anywhere else.
They can’t be used anywhere else.
It can only contain alphabetical characters.
It can only contain alphabetical characters.
It helps identify specific property which exists within a language.
It helps identify specific property which exists within a language.
There are special symbols or punctuations used.
There are special symbols or punctuations used.
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while
All of them are not variables.
All of them are not variables.
They are used to name a variable, a function, a class, a structure, a union.
They are used to name a variable, a function, a class, a structure, a union.
It is created to give a unique name to an entity.
It is created to give a unique name to an entity.
They can consist of alphabets, digits, and underscores.
They can consist of alphabets, digits, and underscores.
There is no punctuation or special symbol, except the underscore.
There is no punctuation or special symbol, except the underscore.
It can be upper case or lower case.
It can be upper case or lower case.
It helps locate the name of the entity which is defined along with a keyword.
It helps locate the name of the entity which is defined along with a keyword.
enum geeks_artiles_in {Jan=1, Feb, Mar, Apr, May, June, July}
java.time.YearMonth.format() Method Example

The java.time.YearMonth.format(DateTimeFormatter formatter) method formats this year using the specified formatter.
Following is the declaration for java.time.YearMonth.format(DateTimeFormatter formatter) method.
public String format(DateTimeFormatter formatter)

formatter − the formatter to use, not null.
the formatted date string, not null.
DateTimeException − if an error occurs during printing.
The following example shows the usage of java.time.YearMonth.format(DateTimeFormatter formatter) method.
package com.tutorialspoint;

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

public class YearMonthDemo {
   public static void main(String[] args) {

      YearMonth date = YearMonth.of(2017,12);
      System.out.println(date);  
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yy");
      System.out.println(formatter.format(date));  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-12
12/17

 Print
 Add Notes
 Bookmark this page
Striped Table with Bootstrap

To add a striped table in Bootstrap, use the .table-striped class. You can try to run the following code to implement the .table-striped class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Table</title>
      <meta name = "viewport" content = "width=device-width, initial-scale = 1">
      <link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <table class = "table table-striped">
         <caption>Footballer Rank</caption>
         <thead>
            <tr>
               <th>Footballer</th>
               <th>Rank</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>Amit</td>
               <td>3</td>
            </tr>
            <tr>
               <td>Kevin</td>
               <td>2</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
Django URL patterns | Python - GeeksforGeeks

19 Jul, 2019
In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration)
Let the project name be myProject. The Python module to be used as URLConf is the value of ROOT_URLCONF in myProject/settings.py. By default this is set to 'myProject.urls'. Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view.
Including other URLConf modulesIt is a good practice to have a URLConf module for every app in Django. This module needs to be included in the root URLConf module as follows:
from django.contrib import adminfrom django.urls import path, include  urlpatterns = [    path('admin/', admin.site.urls),    path('', include('books.urls')),]
This tells Django to search for URL patterns in the file books/urls.py.
URL patterns
Here’s a sample code for books/urls.py:
from django.urls import pathfrom . import views  urlpatterns = [    path('books/<int:pk>/', views.book_detail),    path('books/<str:genre>/', views.books_by_genre),    path('books/', views.book_index), ]
For example,
A URL request to /books/crime/ will match with the second URL pattern. As a result, Django will call the function views.books_by_genre(request, genre = "crime").
Similarly a URL request /books/25/ will match the first URL pattern and Django will call the function views.book_detail(request, pk =25).
Here, int and str are path convertors and capture an integer and string value respectively.
Path convertors:The following path convertor types are available in Django
int – Matches zero or any positive integer.
str – Matches any non-empty string, excluding the path separator(‘/’).
slug – Matches any slug string, i.e. a string consisting of alphabets, digits, hyphen and under score.
path – Matches any non-empty string including the path separator(‘/’)
uuid – Matches a UUID(universal unique identifier).
Python Django
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Compound Finite Automata (FA) - GeeksforGeeks

27 May, 2019
Prerequisite – Finite Automata (FA)Compound FA is the resultant DFA formed after performing operation (∪, ∩, -) on given DFAs D1 and D2.
D1 = (Q1, ∑, δ, q1, F1) and D2 = (Q2, ∑, δ, q2, F2) 
Where,Q1 and Q2: Set of finite states of DFA D1 and D2 respectively.∑: Input alphabet contain finite number of input symbols.δ: Transition function (δ:Qx∑->Q)q1 and q2: Initial state of D1 and D2 respectively.F1 and F2: Set of final states of DFA D1 and D2 respectively.
Properties of Compound Finite Automata (FA):
Number of states in compound FA (D1XD2) is equal to m*n, where m is the number of states in D1 and n is the number of states D2.Initial state of compound FA is combination of initial states of D1 and D2.Final state of compound FA depends on the operation performed.
Number of states in compound FA (D1XD2) is equal to m*n, where m is the number of states in D1 and n is the number of states D2.
Initial state of compound FA is combination of initial states of D1 and D2.
Final state of compound FA depends on the operation performed.
Example:
D1 = no. of a's divisible by 2
D2 = no. of b's divisible by 3

D1 ({q1, B}, {a, b}, δ, q1, {q1}), 
D1 ({q2, A, C}, {a, b}, δ, q2, {q2}) 
Construct the minimal FA for:
(D1∪D2), 
(D1∩D2), 
(D1-D2),
(D2-D1) 
Explanation:
DFA D1:
DFA D2:
1. Union (D1∪D2):Any string w which is either belong’s to the language of D1 or the language of D2 is accepted by resultant compound automata.Final state: If final state of D1 or final state of D2 contain in any of the states of compound FA.
2. Intersection (D1∩D2):Any string w which belong’s to both the language of D1 and the language of D2 is accepted by resultant compound automata.Final state: If both final state of D1 and final state of D2 contain in any of the states of compound FA.
3. Difference (D1 – D2):Any string w which is accepted by D1, not by D2.Final state: If final state of D1 and non-final state of D2 contain in any of the states of compound FA.
4. Difference (D2 – D1):Any string w which is accepted by D2, not by D1.Final state: If final state of D2 and non-final state of D1 contain in any of the states of compound FA.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Phases of a Compiler
Preemptive and Non-Preemptive Scheduling
Introduction of Process Synchronization
Differences between IPv4 and IPv6
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation
__call__ in Python - GeeksforGeeks

27 Feb, 2020
Python has a set of built-in methods and __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).
object() is shorthand for object.__call__()
Example 1:
class Example:    def __init__(self):        print("Instance Created")          # Defining __call__ method    def __call__(self):        print("Instance is called via special method")  # Instance createde = Example()  # __call__ method will be callede()
Output :
Instance Created
Instance is called via special method

Example 2:
class Product:    def __init__(self):        print("Instance Created")      # Defining __call__ method    def __call__(self, a, b):        print(a * b)  # Instance createdans = Product()  # __call__ method will be calledans(10, 20)
Output :
Instance Created
200

Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Checking Internet Connectivity using Java - GeeksforGeeks

30 May, 2018
Checking Internet connectivity using Java can be done using 2 methods:1) by using getRuntime() method of java Runtime class.2) by using methods of java URL and URLConnection classes.
#Java Runtime Class:This class is used to interact with java runtime environment (Java virtual machine) in which the application is running. It provides methods/functions to execute a process or a command, invoke garbage collector, get total and free memory in the JVM etc.
#getRuntime():This method of java runtime class returns the runtime object associated with the current java application.you can learn more about this class here
#Java URL Class:This class provides methods that returns various information like protocol, hostname, file Name, port Number etc of the URL.
#Java URLConnection class:It represents a link between URL and application and can be used to read and write data to the specified resource referred by the URL.
#openConnection():This method of java URLConnection class opens the connection to the specified URL.you can learn more about these classes here and here
NOTE: Provided method should be run on a local machine and not on an online compiler.METHOD 1:Output by this method will be 0 if the internet is connected and it will be 1 if the internet is not connected.
// Java program for Checking Internet connectivityimport java.util.*;import java.io.*;  class checking_internet_connectivity {    public static void main(String args[]) throws Exception    {        Process process = java.lang.Runtime.getRuntime().exec("ping www.geeksforgeeks.org");        int x = process.waitFor();        if (x == 0) {            System.out.println("Connection Successful, "                               + "Output was " + x);        }        else {            System.out.println("Internet Not Connected, "                               + "Output was " + x);        }    }}
OUTPUT:
METHOD 2:If Internet is not connected it will throw an exception and catch will execute printing respective message.
// Java program for checking Internet connectivityimport java.util.*;import java.io.*;import java.net.URL;import java.net.URLConnection;  class checking_internet_connectivity {    public static void main(String args[])    {        try {            URL url = new URL("https://www.geeksforgeeks.org/");            URLConnection connection = url.openConnection();            connection.connect();              System.out.println("Connection Successful");        }        catch (Exception e) {            System.out.println("Internet Not Connected");        }    }}
OUTPUT:
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
LinkedList in Java
Collections in Java
What is the use of default methods in Java?

An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
It is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
If you need your class to follow a certain specification you need to implement the required interface and provide body for all the abstract methods in that interface.
If you do not provide the implementation of all the abstract methods of an interface (you, implement) a compile time error is generated.
Suppose we are using certain interface and implemented all the abstract methods in that interface and new methods were added later. Then, all the classes using this interface will not work unless you implement the newly added methods in each of them.
To resolve this issue from Java8 default methods are introduced.
A default method is also known as defender method or virtual extension method. You can define a default method using the default keyword as −
default void display() {
   System.out.println("This is a default method");      
}
Once write a default implementation to a particular method in an interface. there is no need to implement it in the classes that already using (implementing) this interface.
Following Java Example demonstrates the usage of the default method in Java.
Live Demo
interface sampleInterface{  
   public void demo();  
   default void display() {
      System.out.println("This is a default method");      
   }
}
public class DefaultMethodExample implements sampleInterface{
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }  
   public static void main(String args[]) {      
      DefaultMethodExample obj = new DefaultMethodExample();
      obj.demo();
      obj.display();      
   }
}
This is the implementation of the demo method
This is a default method
What are generator functions in JavaScript?

Generator Functions allows execution of code in between when a function is exited and resumed later. So, generators can be used to manage flow control in a code. Cancel asynchronous operations easily since execution can be paused anytime.
Here’s the syntax; do not forget to add an asterisk after the “function” keyword. You can add an asterisk using any of the following −
function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {}
Let’s see how to use a generator function
Live Demo
<html>
   <body>
      <script>
         function* display() {
            var num = 1;
            while (num < 5)
            yield num++;
         }
         var myGenerator = display();

         document.write(myGenerator.next().value);
         document.write("<br>"+myGenerator.next().value);
         document.write("<br>"+myGenerator.next().value);
         document.write("<br>"+myGenerator.next().value);
         document.write("<br>"+myGenerator.next().value);
      </script>
   </body>
</html>
How do you initialize jagged arrays in C#?

A Jagged array is an array of arrays. This is how you can initialize it.
int[][] rank = new int[2][]{new int[]{3,2,7},new int[]{9,4,5,6}};
The following is an example showing how to initialize jagged arrays in C#.
 Live Demo
using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int[][] a = new int[][]{new int[]{0,0},new int[]{1,2}, new int[]{2,4} };
         int i, j;
         for (i = 0; i < 3; i++) {
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
            }
         }
         Console.ReadKey();
      }
   }
}
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
How to replace NA’s to a value of selected columns in an R data frame?

In data analysis, finding some NA values in a data frame is very common but all the NA values do not create problems if the column that contain NA values is not useful for the analysis. We can replace all NA values to 0 or to any other for the columns that are useful.
Consider the below data frame −
> set.seed(99)
> x1<-sample(c(5,10,15,NA),20,replace=TRUE)
> x2<-sample(c(1,2,3,NA),20,replace=TRUE)
> x3<-sample(c(20,21,22,23,24,25,NA),20,replace=TRUE)
> x4<-sample(c(letters[1:10],NA),20,replace=TRUE)
> x5<-sample(c(1:10,NA),20,replace=TRUE)
> df<-data.frame(x1,x2,x3,x4,x5)
> df
  x1   x2   x3   x4    x5
1  NA   NA   25  <NA>  NA
2  5     2   24    f    2
3  NA    2   25    i    7
4  10   NA   23    i   10
5  10    1   21    c    3
6   5   NA   NA    h   NA
7  15    2   20    g   10
8  10   NA   25    d   10
9  10    2   23    c    5
10 10    1   NA    f    8
11 NA    3   25  <NA>   5
12 10    2   NA    h    4
13 NA    3   25    g    1
14 5     2   NA    c    8
15 NA   2   NA  <NA>    3
16 NA   NA  23    f     7
17 15   1   24  <NA>    9
18 NA   NA   NA    b    3
19 5    3    NA    d    3    
20 10   2    20    g    8
Changing NA’s to zero of consecutive columns −
> df[,c("x1","x2")][is.na(df[,c("x1","x2")])] <- 0
> df
x1 x2 x3 x4 x5
1 0 0 25 <NA> NA
2 5 2 24 f 2
3 0 2 25 i 7
4 10 0 23 i 10
5 10 1 21 c 3
6 5 0 NA h NA
7 15 2 20 g 10
8 10 0 25 d 10
9 10 2 23 c 5
10 10 1 NA f 8
11 0 3 25 <NA> 5
12 10 2 NA h 4
13 0 3 25 g 1
14 5 2 NA c 8
15 0 2 NA <NA> 3
16 0 0 23 f 7
17 15 1 24 <NA> 9
18 0 0 NA b 3
19 5 3 NA d 3
20 10 2 20 g 8
Changing NA’s to zero of non-consecutive columns −
> df[,c("x3","x5")][is.na(df[,c("x3","x5")])] <- 0
> df
x1 x2 x3 x4 x5
1 0 0 25 <NA> 0
2 5 2 24 f 2
3 0 2 25 i 7
4 10 0 23 i 10
5 10 1 21 c 3
6 5 0 0 h 0
7 15 2 20 g 10
8 10 0 25 d 10
9 10 2 23 c 5
10 10 1 0 f 8
11 0 3 25 <NA> 5
12 10 2 0 h 4
13 0 3 25 g 1
14 5 2 0 c 8
15 0 2 0 <NA> 3
16 0 0 23 f 7
17 15 1 24 <NA> 9
18 0 0 0 b 3
19 5 3 0 d 3
20 10 2 20 g 8
Make an Ordered list with Bootstrap

For ordered list in Bootstrap, you can try to run the following code −
 Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap lists</title>
      <meta name = "viewport" content = "width=device-width, initial-scale = 1">
      <link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <h1>Lists</h1>
      <h2>Fruits (Ordered List)</h2>
      <ol>
         <li>Kiwi</li>
         <li>Apple</li>
         <li>Mango</li>
      </ol>
   </body>
</html>
PyTorch – How to get the exponents of tensor elements?

To find the exponential of the elements of an input tensor, we can apply
Tensor.exp() or torch.exp(input). Here, input is the input tensor for
which the exponentials are computed. Both the methods return a new
tensor with the exponential values of the elements of the input tensor.
Tensor.exp()
or
torch.exp(input)

We could use the following steps to compute the exponentials of the
elements of an input tensor −
Import the torch library. Make sure you have it already installed.
import torch
Create a tensor and print it.
t1 = torch.rand(4,3)
print("Tensor:", t1)
Compute the exponential of the elements of the tensor. For this, use torch.exp(input) and optionally assign this value to a new variable.
exp_t1 = torch.exp(t1)

Print the resultant tensor.
print("Exponentials of elements:\n", exp_t1)
The following Python program shows how to compute the exponentials of
the elements of an input tensor.
# import torch library
import torch

# create a tensor
t1 = torch.tensor([1,2,3,4,5])

# display the tensor
print("Tensor t1:\n", t1)

# Compute the exponential of the elements of the tensor
exp_t1 = t1.exp()
print("Exponential of t1:\n",exp_t1)

# create another tensor
t2 = torch.randn(2,3)
print("Tensor t2:\n", t2)

# Compute the exponential of the elements of the above tensor
exp_t2 = t2.exp()
print("Exponential of t2:\n",exp_t2)
Tensor t1:
 tensor([1, 2, 3, 4, 5])
Exponential of t1:
 tensor([ 2.7183, 7.3891, 20.0855, 54.5981, 148.4132])
Tensor t2:
 tensor([[ 0.2986, 0.0348, 2.1201],
   [-0.4488, -0.2205, 0.5417]])
Exponential of t2:
 tensor([[1.3480, 1.0354, 8.3319],
   [0.6384, 0.8021, 1.7189]])
# import torch library
import torch

# create a tensor
t1 = torch.tensor([[1,2,3],[4,5,6]])

# display the tensor
print("Tensor t1:\n", t1)

# Other way to compute the exponential of the elements
exp_t1 = torch.exp(t1)
print("Exponential of t1:\n",exp_t1)

# create another tensor
t2 = torch.randn(4,3)
print("Tensor t2:\n", t2)

# compute the exponential of the elements of the tensor
exp_t2 = torch.exp(t2)
print("Exponential of t2:\n",exp_t2)
Tensor t1:
 tensor([[1, 2, 3],
   [4, 5, 6]])
Exponential of t1:
 tensor([[ 2.7183, 7.3891, 20.0855],
   [ 54.5981, 148.4132, 403.4288]])
Tensor t2:
 tensor([[ 1.3574, -0.3132, 0.9117],
   [-0.4421, 1.4100, -0.9875],
   [ 0.1515, 0.1374, -0.6713],
   [ 1.1636, -0.1663, -1.1224]])
Exponential of t2:
 tensor([[3.8862, 0.7311, 2.4884],
   [0.6427, 4.0959, 0.3725],
   [1.1636, 1.1473, 0.5110],
   [3.2014, 0.8468, 0.3255]])
GATE | GATE CS 2012 | Question 8 - GeeksforGeeks

28 Jun, 2021
A process executes the code
fork();
fork();
fork(); 
The total number of child processes created is(A) 3(B) 4(C) 7(D) 8Answer: (C)Explanation: Let us put some label names for the three lines
  fork ();    // Line 1
  fork ();   // Line 2
  fork ();   // Line 3

       L1       // There will be 1 child process created by line 1
    /     \
  L2      L2    // There will be 2 child processes created by line 2
 /  \    /  \
L3  L3  L3  L3  // There will be 4 child processes created by line 3
We can also use direct formula to get the number of child processes. With n fork statements, there are always 2^n – 1 child processes. Also see this post for more details.Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
Java 9 - Process API Improvements

In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process's native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes' liveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits.
import java.time.ZoneId;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.IOException;

public class Tester {
   public static void main(String[] args) throws IOException {
      ProcessBuilder pb = new ProcessBuilder("notepad.exe");
      String np = "Not Present";
      Process p = pb.start();
      ProcessHandle.Info info = p.info();
      System.out.printf("Process ID : %s%n", p.pid());
      System.out.printf("Command name : %s%n", info.command().orElse(np));
      System.out.printf("Command line : %s%n", info.commandLine().orElse(np));

      System.out.printf("Start time: %s%n",
         info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())
         .toLocalDateTime().toString()).orElse(np));

      System.out.printf("Arguments : %s%n",
         info.arguments().map(a -> Stream.of(a).collect(
         Collectors.joining(" "))).orElse(np));

      System.out.printf("User : %s%n", info.user().orElse(np));
   } 
}
You will see the following output.
Process ID : 5800
Command name : C:\Windows\System32\notepad.exe
Command line : Not Present
Start time: 2017-11-04T21:35:03.626
Arguments : Not Present
User: administrator


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
PHP Escaping From HTML

PHP file can have mixed content with code within tags embedded in a HTML document. Code outside tags is ignored by the parser, leaving it to be interpreted by client browser. A HTML document can have multiple blocks of PHP, each inside <?php and ?> tags.
<p>
HTML block
</p>
<?php
//php block
..
..
?>
<p>
HTML block
</p>
<?php
//php block
..
..
?>
<p>
HTML block
</p>
Every time opening PHP tag is encountered, parser starts rendering the output to the client until closing tag is reached. If code consusts of conditional statement, th parser determines which block to be skipped.
Again till another opening tag comes, everything is treated as HTML leaving the browser to process the same.
This description is applicable to all versions of PHP.
Following example shows PHP code embedded in HTML
<html>
<body>
<!..HTML code--!>
<h3>Hello World</h3>
<!-- PHP code --!>
<?php
echo "Hello World in PHP";
?>
<!-- This is HTML code --!>
<p>Hello world again</p>
<?php
echo "Hello World again in PHP";
?>
</body>
</html>
This will produce following result −
Hello World
Hello World in PHP
Hello world again
Hello World again in PHP
Example using mixed HTML and PHP code
<?php $marks=10; ?>
<h1>Using conditional statement</h1>
<?php if ($marks >=50): ?>
<h2 style="color:blue;">Result:pass</p>
<?php else: ?>
<h2 style="color:red;"> Result:Fail</p>
<?php endif; ?>
This will produce following result −
Using conditional statement
Result:Fail
change marks to 60 and run again
Using conditional statement
Result:pass
change marks to 60 and run again
Using conditional statement
Result:pass
How to plot bar graphs with same X coordinates side by side in Matplotlib?

To plot bar graphs with same X coordinates (G1, G2, G3, G4 and G5), side by side in matplotlib, we can take the following steps −
Create the following lists – labels, men_means and women_means with different data elements.
Create the following lists – labels, men_means and women_means with different data elements.
Return evenly spaced values within a given interval, using numpy.arrange() method.
Return evenly spaced values within a given interval, using numpy.arrange() method.
Set the width variable, i.e., width=0.35.
Set the width variable, i.e., width=0.35.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method.
The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method.
Set the Y-axis label using plt.ylabel() method.
Set the Y-axis label using plt.ylabel() method.
Set a title for the axes using set_title() method.
Set a title for the axes using set_title() method.
Get or set the current tick locations and labels of the X-axis using set_xticks() method.
Get or set the current tick locations and labels of the X-axis using set_xticks() method.
Set X-axis tick labels of the grid using set_xticklabels() method.
Set X-axis tick labels of the grid using set_xticklabels() method.
Place a legend on the figure using legend() method.
Place a legend on the figure using legend() method.
Annotate the created bars (rect1 and rect2) with some label using autolabel() method (user-defined method).
Annotate the created bars (rect1 and rect2) with some label using autolabel() method (user-defined method).
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))
width = 0.35

fig, ax = plt.subplots()
rects1 = ax.bar(x - width / 2, men_means, width, label='Men')
rects2 = ax.bar(x + width / 2, women_means, width, label='Women')

ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

def autolabel(rects):
   for rect in rects:
      height = rect.get_height()
      ax.annotate('{}'.format(height),
         xy=(rect.get_x() + rect.get_width() / 2, height),
         xytext=(0, 3), # 3 points vertical offset
         textcoords="offset points",
         ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()
Function overloading and const keyword in C++

In C++, we can overload functions. Some functions are normal functions; some are constant type functions. Let us see one program and its output to get the idea about the constant functions and normal functions.
#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func() const {
         cout << "Calling the constant function" << endl;
      }
      void my_func() {
         cout << "Calling the normal function" << endl;
      }
};
int main() {
   my_class obj;
   const my_class obj_c;
   obj.my_func();
   obj_c.my_func();
}
Calling the normal function
Calling the constant function
Here we can see that the normal function is called when the object is normal. When the object is constant, then the constant functions are called.
If two overloaded method contains parameters, and one parameter is normal, another is constant, then this will generate error.
#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func(const int x) {
         cout << "Calling the function with constant x" << endl;
      }
      void my_func(int x){
         cout << "Calling the function with x" << endl;
      }
};
int main() {
   my_class obj;
   obj.my_func(10);
}
[Error] 'void my_class::my_func(int)' cannot be overloaded
[Error] with 'void my_class::my_func(int)'
But if the arguments are reference or pointer type, then it will not generate error.
#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func(const int *x) {
         cout << "Calling the function with constant x" << endl;
      }
      void my_func(int *x) {
         cout << "Calling the function with x" << endl;
      }
};
int main() {
   my_class obj;
   int x = 10;
   obj.my_func(&x);
}
Calling the function with x
How to draw a star in HTML5 SVG?

SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG.
To draw a polygon in HTML SVG, use the SVG <polygon> element. The <polygon> element creates a graphic containing at least three sides. For drawing a star in HTML5 SVG, you need to set the x and y coordinates properly for each corner.
You can try to run the following code to learn how to draw a star in HTML5 SVG:
<!DOCTYPE html>
   <html>
      <head>
         <style>
            #svgelem {
               position: relative;
               left: 10%;
               -webkit-transform: translateX(-20%);
               -ms-transform: translateX(-20%);
               transform: translateX(-20%);
            }
         </style>
      <title>HTML5 SVG Polygon Star</title>
   </head>
   <body>
      <h2>HTML5 SVG Star</h2>
         <svg id = "svgelem" width = "300" height = "300" xmlns = "http://www.w3.org/2000/svg">
            <polygon points="100,10 40,180 190,60 10,60 160,180" fill="blue"/>
         </svg>
   </body>
</html>
Python - Remove keys with substring values - GeeksforGeeks

31 Jan, 2022
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove keys whose values have substring as argument we pass. This problem can occur in cases of web development and day-day programming. Lets discuss certain ways in which this task can be performed. 
Input : test_dict = {1 : ‘Gfg is best for geeks’} sub_list = [‘love’, ‘good’] ( Strings to check in values ) Output : {1: ‘Gfg is best for geeks’}Input : test_dict = {1 : ‘Gfg is love’, 2: ‘Gfg is good’} sub_list = [‘love’, ‘good’] ( Strings to check in values ) Output : {}  
Method #1 : Using any() + loop The combination of above functionalities can be used to solve this problem. In this, we extract all the items from dictionary which do not have desired values, the filtration is performed using any() and generator expression. 
Python3
# Python3 code to demonstrate working of# Remove keys with substring values# Using any() + generator expression # initializing dictionarytest_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # initializing substringssub_list = ['love', 'good'] # Remove keys with substring values# Using any() + generator expressionres = dict()for key, val in test_dict.items():   if not any(ele in val for ele in sub_list):       res[key] = val        # printing resultprint("Filtered Dictionary : " + str(res))
The original dictionary : {1: ‘Gfg is best for geeks’, 2: ‘Gfg is good’, 3: ‘I love Gfg’} Filtered Dictionary : {1: ‘Gfg is best for geeks’} 
 
 Method #2 : Using dictionary comprehension + any() The combination of above methods provide the shorthand to execute this task. In this, we perform this task in similar way as above method, but in one liner format using comprehension. 
Python3
# Python3 code to demonstrate working of# Remove keys with substring values# Using dictionary comprehension + any() # initializing dictionarytest_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # initializing substringssub_list = ['love', 'good'] # Remove keys with substring values# Using dictionary comprehension + any()res = {key : val for key, val in test_dict.items() if not any(ele in val for ele in sub_list)}        # printing resultprint("Filtered Dictionary : " + str(res))
The original dictionary : {1: 'Gfg is best for geeks', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for geeks'}
 
adnanirshad158
Python dictionary-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 ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
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?
Python | Alternate element summation in list - GeeksforGeeks

29 Mar, 2019
The problem of getting summation of a list is quite generic and we might some day face the issue of getting the summation of alternate elements and get the list of 2 elements containing summation of alternate elements. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + list slicing + sum()List slicing clubbed with list comprehension can be used to perform this particular task. We can have list comprehension to get run the logic and list slicing can slice out the alternate character, summation by the sum function
# Python3 code to demonstrate# alternate elements summation# using list comprehension + list slicing  # initializing list test_list = [2, 1, 5, 6, 8, 10]  # printing original list print("The original list : " + str(test_list))  # using list comprehension + list slicing# alternate elements summationres = [sum(test_list[i : : 2])      for i in range(len(test_list)//(len(test_list)//2))]  # print resultprint("The alternate elements summation list : " + str(res))
The original list : [2, 1, 5, 6, 8, 10]
The alternate elements summation list : [15, 17]

 
Method #2 : Using loopThis is the brute method to perform this particular task in which we have the summation of alternate elements in different element indices and then return the output list.
# Python3 code to demonstrate# alternate elements summation# using loop  # initializing list test_list = [2, 1, 5, 6, 8, 10]  # printing original list print("The original list : " + str(test_list))  # using loop# alternate elements summationres = [0, 0]for i in range(0, len(test_list)):    if(i % 2):        res[1] += test_list[i]    else :        res[0] += test_list[i]  # print resultprint("The alternate elements summation list : " + str(res))
The original list : [2, 1, 5, 6, 8, 10]
The alternate elements summation list : [15, 17]

Marketing
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
CSS | :only-child Selector - GeeksforGeeks

17 Dec, 2018
The :only-child selector in CSS is used to match every element that is the only child of its parent. It represents an element without any siblings.
Syntax:
:only-child {
    // CSS property
} 

Example 1:
<!DOCTYPE html><html>    <head>        <title>:only-child selector</title>        <style>            h1 {                color: green;                text-align: center;            }            h2 {                text-align: center;            }            div:only-child {                color: white;                background: green;            }            div {                display: block;                margin: 6px;                font-size: 17px;                padding: 5px 8px;                border: solid 2px grey;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>:only-child selector</h2>        <div>            <div>I am an only child.</div>        </div>        <div>            <div>I am the 1st child.</div>            <div>I am the 2nd child.</div>            <div>I am the 3rd child, <div> Only             child of parent.</div></div>        </div>    </body></html>
Output:
Example 2:
<!DOCTYPE html><html>    <head>        <title>:only-child selector</title>        <style>            h1 {                color: green;                text-align: center;            }            h2 {                text-align: center;            }            li:only-child {            color: green;            }            li {                font-size: 20px;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>:only-child selector</h2>        <ol>            <li>Data Structures</li>            <ul>                <li>Arrays </li>            </ul>            <li>Languages</li>            <ul>                <li>C++ </li>                <li>Python</li>            </ul>            <li>Algorithms</li>            <ul>                <li>Searching Algorithms</li>                <li>Sorting Algorithms</li>                <ul>                    <li>Bubble sort </li>                </ul>            </ul>        </ol>    </body></html>
Output:
Supported Browser: The browser supported by :only-child selector are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Safari 3.2
Opera 9.6
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills