code-rag-bench/online-tutorials huggingface dataset:
C# - Enums

An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword.
C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.
The general syntax for declaring an enumeration is −
enum <enum_name> {
   enumeration list 
};

Where,
The enum_name specifies the enumeration type name.
The enum_name specifies the enumeration type name.
The enumeration list is a comma-separated list of identifiers.
The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example −
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

The following example demonstrates use of enum variable −
using System;

namespace EnumApplication {
   class EnumProgram {
      enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

      static void Main(string[] args) {
         int WeekdayStart = (int)Days.Mon;
         int WeekdayEnd = (int)Days.Fri;
         
         Console.WriteLine("Monday: {0}", WeekdayStart);
         Console.WriteLine("Friday: {0}", WeekdayEnd);
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Monday: 1
Friday: 5


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Python Shallow and Deep Copy operations

In Python there is a module called copy. Using this module, we can perform deep copy and shallow copy. In python the assignment statements do not copy the objects. They create a binding between the target and the main object.
To use this module, we should import it using −
import copy

This method is used to create a shallow copy of the object x. For the shallow copy, a reference of an object is copied to another object. So if there is any change on the copied reference, it will change the content of the main object.
This method is used to create a deep copy of the object x. For the deep copy, an individual object is created by taking the data from the main object. So if there is any change on the copied reference, the main object will remain same.
 Live Demo
import copy
my_mat = [[11,22,33],[44,55,66],[11,22,33]]
print('Matrix Before Updation: ' + str(my_mat))
new_mat = copy.copy(my_mat) #Make a shallow copy and update on copied object
new_mat[2][0] = 77
new_mat[2][1] = 88
new_mat[2][2] = 99
print('Matrix After Updation: ' + str(my_mat)) #Original Matrix Updated
my_mat = [[11,22,33],[44,55,66],[11,22,33]]
new_mat_deep = copy.deepcopy(new_mat)
print('\nMatrix Before Updation: ' + str(my_mat))
new_mat_deep[2][0] = 77
new_mat_deep[2][1] = 88
new_mat_deep[2][2] = 99
print('Matrix After Updation: ' + str(my_mat)) # Original Matrix unchanged
print('New Matrix: ' + str(new_mat_deep)) # Original Matrix unchanged
Matrix Before Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
Matrix After Updation: [[11, 22, 33], [44, 55, 66], [77, 88, 99]]

Matrix Before Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
Matrix After Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
New Matrix: [[11, 22, 33], [44, 55, 66], [77, 88, 99]]
MariaDB - Drop Database

Creation or deletion of databases in MariaDB requires privileges, typically, only given to root users or admins. Under these accounts, you have two options for deleting a database: the mysqladmin binary and a PHP script.
Note that deleted databases are irrecoverable, so exercise care in performing this operation. Furthermore, PHP scripts used for deletion do not prompt you with a confirmation before the deletion.
The following example demonstrates how to use the mysqladmin binary to delete an existing database −
[root@host]# mysqladmin -u root -p drop PRODUCTS
Enter password:******
mysql> DROP PRODUCTS
ERROR 1008 (HY000): Can't drop database 'PRODUCTS'; database doesn't exist

PHP employs the mysql_query function in deleting MariaDB databases. The function uses two parameters, one optional, and returns either a value of “true” when successful, or “false” when not.
Review the following drop database script syntax −
bool mysql_query( sql, connection );

The description of the parameters is given below −
sql
This required parameter consists of the SQL query needed to perform the operation.
connection
When not specified, this optional parameter uses the most recent connection used.
Try the following example code for deleting a database −
<html>
   <head>
      <title>Delete a MariaDB Database</title>
   </head>

   <body>
      <?php
         $dbhost = 'localhost:3036';
         $dbuser = 'root';
         $dbpass = 'rootpassword';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);
      
         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         echo 'Connected successfully<br />';
         
         $sql = 'DROP DATABASE PRODUCTS';
         $retval = mysql_query( $sql, $conn );
         
         if(! $retval ){
            die('Could not delete database: ' . mysql_error());
         }

         echo "Database PRODUCTS deleted successfully\n";
         mysql_close($conn);
      ?>
   </body>
</html>
On successful deletion, you will see the following output −
mysql> Database PRODUCTS deleted successfully 

 Print
 Add Notes
 Bookmark this page
How to Create a Checkmark / Tick with CSS

We can create a customized checkmark using CSS. The following examples illustrate this effect −
 Live Demo
<!DOCTYPE html>
<html>
<style>
div {
   margin: 2%;
   position: relative;
   width: 40px;
   height: 40px;
   box-shadow: inset 0 0 12px lightblue;
}
div::before {
   content: "";
   position: absolute;
   width: 8px;
   top: 50%;
   height: 50%;
   border-radius: 2px;
   background-color: rgb(123,45,20);
   transform: translateX(12px) rotate(-45deg);
   transform-origin: left bottom;
   z-index: +1;
}
div::after {
   content: "";
   position: absolute;
   bottom: 0;
   height: 8px;
   width: 100%;
   border-radius: 2px;
   background-color: rgb(200,52,120);
   transform: translateX(12px) rotate(-45deg);
   transform-origin: left bottom;
}
</style>
<body>
Custom mark!
<div></div>
</body>
</html>
This will produce the following result −
 Live Demo
<!DOCTYPE html>
<html>
<style>
body {
   padding: 2%;
   text-align: center;
}
div {
   display: inline-block;
   height: 100px;
   width: 35px;
   border-bottom: 10px solid chartreuse;
   border-right: 10px solid chartreuse;
   transform: rotate(45deg);
}
</style>
<body>
<div></div>
</body>
</html>
This will produce the following result −
io.LimitReader() Function in Golang with Examples - GeeksforGeeks

03 May, 2020
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The LimitReader() function in Go language is used to return a “Reader” that reads from the stated “r” but it pauses if the EOF i.e, end of file is reached after reading the stated “n” number of bytes. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
Syntax:
func LimitReader(r Reader, n int64) Reader

Here, “r” is the stated Reader, and “n” is the number of bytes.
Return value: It returns a Reader that reads from the stated “r”.
Below examples illustrates the use of above method:
Example 1:
// Golang program to illustrate the usage of// io.LimitReader() function  // Including main packagepackage main  // Importing fmt, io, strings, and osimport (    "fmt"    "io"    "os"    "strings")  // Calling mainfunc main() {      // Defining r using NewReader    r := strings.NewReader("Geeks\n")      // Calling LimitReader method with its parameters    res := io.LimitReader(r, 3)      // Calling Copy method with its parameters    op, err := io.Copy(os.Stdout, res)      // If error is not nil then panics    if err != nil {        panic(err)    }      // Prints output    fmt.Printf("\nn: %v\n", op)}
Output:
Gee
n: 3

In the above example, the Copy() method is used in order to return the “Reader” and NewReader() method of strings is used from where the content to be read is written.
Example 2:
// Golang program to illustrate the usage of// io.LimitReader() function  // Including main packagepackage main  // Importing fmt, io, strings, and osimport (    "fmt"    "io"    "os"    "strings")  // Calling mainfunc main() {      // Defining r using NewReader    r := strings.NewReader("GfG\nis\na\nCS-Portal.\n")      // Calling LimitReader method with its parameters    res := io.LimitReader(r, 8)      // Calling Copy method with its parameters    op, err := io.Copy(os.Stdout, res)      // If error is not nil then panics    if err != nil {        panic(err)    }      // Prints output    fmt.Printf("\nn: %v\n", op)}
Output:
GfG
is
a
n: 8

Golang-io
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Check if the String ends with specified suffix in Golang
Rune in Golang
Anonymous function in Go Language
How to Parse JSON in Golang?
Class and Object in Golang
Loops in Go Language
Methods in Golang
Structures in Golang
Golang program that uses structs as map keys
fmt.print() Function in Golang With Examples
Display dates after NOW() + 10 days from a MySQL table?

You can use DATE_ADD() function with where clause for this. Let us first create a table −
mysql> create table DemoTable
   (
   ShippingDate date
   );
Query OK, 0 rows affected (0.54 sec)
Note : The current date and time is as follows, we found using NOW() −
mysql> select now();
+-----------------------+
| now()                 |
+-----------------------+
| 2019-06-04 20 :43 :57 |
+-----------------------+
1 row in set (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-06-16');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('2019-05-31');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('2019-05-24');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('2019-06-24');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+--------------+
| ShippingDate |
+--------------+
| 2019-06-16   |
| 2019-05-31   |
| 2019-05-24   |
| 2019-06-24   |
+--------------+
4 rows in set (0.00 sec)
Following is the query to display dates after NOW() + 10 days −
mysql> select *from DemoTable where ShippingDate > DATE_ADD(now(), INTERVAL 10 DAY);
+--------------+
| ShippingDate |
+--------------+
| 2019-06-16   |
| 2019-06-24   |
+--------------+
2 rows in set (0.00 sec)
How to display the name of the Current Thread in C#?

Use the Name property to display the name of the current thread in C#.
Firstly, use the currentThread property to display information about a thread −
Thread thread = Thread.CurrentThread;
Now use the thread.Name property to display name of the thread −
thread.Name
Let us see the complete code show current thread’s name in C# −
 Live Demo
using System;
using System.Threading;

namespace Demo {
   class MyClass {
      static void Main(string[] args) {
         Thread thread = Thread.CurrentThread;
         thread.Name = "My Thread";

         Console.WriteLine("Thread Name = {0}", thread.Name);
         Console.ReadKey();
      }
   }
}
Thread Name = My Thread
How to extract a particular value based on index from an R data frame column?

Sometimes we want to figure out which value lies at some position in an R data frame column, this helps us to understand the data collection or data simulation process. For example, if we have a data frame df that contain columns x, y, and z each with 5000 values then we can use df$x[[253]] to find which values lies at 253rd row in column x of data frame df.
Consider the below data frame −
 Live Demo
set.seed(987)
x<-rnorm(20,521,30.7)
y<-rnorm(20,20,4.05)
z<-rnorm(20,31,1)
a<-rpois(20,8)
b<-rpois(20,10)
c<-rpois(20,2)
df<-data.frame(x,y,z,a,b,c)
df
   x    y     z      a     b    c
1 519.2497 26.62916 31.48431 14 18 0
2 529.2888 16.46887 32.70400 5 5 1
3 547.8463 13.71248 29.73358 10 11 2
4 515.1564 22.82227 30.12065 6 5 5
5 554.7914 20.28892 32.52483 7 2 4
6 493.5616 15.45613 31.23513 14 10 3
7 491.6825 22.32123 30.81875 4 9 4
8 494.7252 18.33388 32.50834 8 13 1
9 486.8303 13.96303 30.71686 5 10 2
10 481.4361 18.60518 32.32576 13 9 3
11 544.2612 19.79058 32.56325 7 8 1
12 494.0999 23.56244 30.83515 4 14 3
13 574.9847 27.61496 29.30917 9 6 0
14 520.7027 27.62166 29.93995 10 12 0
15 507.2346 22.38830 31.16826 7 15 0
16 517.3553 22.60314 31.76175 6 9 2
17 507.0164 18.61279 31.86548 10 10 3
18 484.6791 24.74147 31.88115 5 6 5
19 507.0228 25.21739 32.09461 5 4 0
20 552.1552 16.49131 31.39587 5 7 2
Extracting values from column x using index −
df$x[[1]]
[1] 519.2497
df$x[[5]]
[1] 554.7914
df$x[[6]]
[1] 493.5616
df$x[[7]]
[1] 491.6825
df$x[[12]]
[1] 494.0999
df$x[[15]]
[1] 507.2346
df$x[[19]]
[1] 507.0228
df$x[[20]]
[1] 552.1552
Extracting values from column y using index −
df$y[[19]]
[1] 25.21739
df$y[[1]]
[1] 26.62916
df$y[[4]]
[1] 22.82227
df$y[[3]]
[1] 13.71248
df$y[[5]]
[1] 20.28892
df$y[[7]]
[1] 22.32123
df$y[[10]]
[1] 18.60518
df$y[[9]]
[1] 13.96303
df$y[[13]]
[1] 27.61496
df$y[[14]]
[1] 27.62166
df$y[[18]]
[1] 24.74147
Extracting values from column z using index:
df$z[[2]]
[1] 32.704
df$z[[5]]
[1] 32.52483
df$z[[10]]
[1] 32.32576
df$z[[15]]
[1] 31.16826
df$z[[20]]
[1] 31.39587
df$z[[17]]
[1] 31.86548
Extracting values from column a using index −
df$a[[20]]
[1] 5
df$a[[1]]
[1] 14
df$a[[10]]
[1] 13
df$a[[12]]
[1] 4
df$a[[5]]
[1] 7
df$a[[13]]
[1] 9
df$a[[17]]
[1] 10
df$a[[18]]
[1] 5
df$a[[19]]
[1] 5
Extracting values from column b using index −
df$b[[1]]
[1] 18
df$b[[5]]
[1] 2
df$b[[10]]
[1] 9
df$b[[15]]
[1] 15
df$b[[20]]
[1] 7
Extracting values from column c using index −
df$c[[3]]
[1] 2
df$c[[6]]
[1] 3
df$c[[9]]
[1] 2
df$c[[12]]
[1] 3
df$c[[15]]
[1] 0
df$c[[18]]
[1] 5
Arithmetic Operators in C

The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20, then −
Try the following example to understand all the arithmetic operators available in C −
#include <stdio.h>

main() {

   int a = 21;
   int b = 10;
   int c ;

   c = a + b;
   printf("Line 1 - Value of c is %d\n", c );
	
   c = a - b;
   printf("Line 2 - Value of c is %d\n", c );
	
   c = a * b;
   printf("Line 3 - Value of c is %d\n", c );
	
   c = a / b;
   printf("Line 4 - Value of c is %d\n", c );
	
   c = a % b;
   printf("Line 5 - Value of c is %d\n", c );
	
   c = a++; 
   printf("Line 6 - Value of c is %d\n", c );
	
   c = a--; 
   printf("Line 7 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

 Print
 Add Notes
 Bookmark this page
How to insert mm/dd/yyyy format dates in MySQL?

For this, use STR_TO_DATE(). Following is the syntax −
insert into yourTableName values(STR_TO_DATE(yourDateValue,yourFormatSpecifier));
Let us first create a table −
mysql> create table DemoTable
   (
   ShippingDate date
   );
Query OK, 0 rows affected (0.81 sec)
Insert some records in the table using insert command : Here, we are inserting formatted dates using date formats like m, d, y, etc −
mysql> insert into DemoTable values(STR_TO_DATE('06-01-2019', '%m-%d-%Y'));
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(STR_TO_DATE('01-31-2019', '%m-%d-%Y'));
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(STR_TO_DATE('02-01-2018', '%m-%d-%Y'));
Query OK, 1 row affected (0.27 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+--------------+
| ShippingDate |
+--------------+
| 2019-06-01   |
| 2019-01-31   |
| 2018-02-01   |
+--------------+
3 rows in set (0.00 sec)
MySQL query to display a substring before a special character in a string

Use the LOCATE() and SUBSTRING() method for this in MySQL. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Title text
   -> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Introduction To Java');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('Introduction - To MySQL');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------------------+
| Title                   |
+-------------------------+
| Introduction To Java    |
| Introduction - To MySQL |
+-------------------------+
2 rows in set (0.00 sec)
Following is the query to display a substring before a special character in a substring −
mysql> select distinct
   -> if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) from DemoTable;
This will produce the following output −
+-----------------------------------------------------------------------------+
| if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) |
+-----------------------------------------------------------------------------+
| Introduction To Java                                                        |
| Introduction                                                                |
+-----------------------------------------------------------------------------+
2 rows in set (0.00 sec)
ggplot2 - Marginal Plots

In this chapter, we shall discuss about Marginal Plots.
Marginal plots are used to assess relationship between two variables and examine their distributions. When we speak about creating marginal plots, they are nothing but scatter plots that has histograms, box plots or dot plots in the margins of respective x and y axes.
Following steps will be used to create marginal plot with R using package “ggExtra”. This package is designed to enhance the features of “ggplot2” package and includes various functions for creating successful marginal plots.
Install “ggExtra” package using following command for successful execution (if the package is not installed in your system).
> install.packages("ggExtra")

Include the required libraries in the workspace to create marginal plots.
> library(ggplot2)
> library(ggExtra)

Reading the required dataset “mpg” which we have used in previous chapters.
> data(mpg)
> head(mpg)
# A tibble: 6 x 11
manufacturer   model  displ   year   cyl   trans      drv   cty   hwy  fl  class
<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
1 audi         a4     1.8     1999   4     auto(l5)   f     18    29   p   compa~
2 audi         a4     1.8     1999   4     manual(m5) f     21    29   p   compa~
3 audi         a4     2       2008   4     manual(m6) f     20    31   p   compa~
4 audi         a4     2       2008   4     auto(av)   f     21    30   p   compa~
5 audi         a4     2.8     1999   6     auto(l5)   f     16    26   p   compa~
6 audi         a4     2.8     1999   6     manual(m5) f     18    26   p   compa~
>

Now let us create a simple plot using “ggplot2” which will help us understand the concept of marginal plots.
> #Plot
> g <- ggplot(mpg, aes(cty, hwy)) +
+    geom_count() +
+    geom_smooth(method="lm", se=F)
> g

Now let us create the marginal plots using ggMarginal function which helps to generate relationship between two attributes “hwy” and “cty”.
> ggMarginal(g, type = "histogram", fill="transparent")
> ggMarginal(g, type = "boxplot", fill="transparent")

The output for histogram marginal plots is mentioned below −
The output for box marginal plots is mentioned below −
 Print
 Add Notes
 Bookmark this page
C# program to check the validity of a Password

For validity of a password, you need to recall the concept when your create a password to signup to a website.
While creating a password, you may have seen the validation requirements on a website like a password should be strong and have −
Min 8 char and max 14 char
Min 8 char and max 14 char
One upper case
One upper case
One special char
One special char
One lower case
One lower case
No white space
No white space
Let us see how to check the conditions one by one.
if (passwd.Length < 8 || passwd.Length > 14)
return false;
if (!passwd.Any(char.IsUpper))
return false;
if (!passwd.Any(char.IsLower))
return false;
if (passwd.Contains(" "))
return false;
string specialCh = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" + "\"";
char[] specialCh = specialCh.ToCharArray();
foreach (char ch in specialChArray) {
   if (passwd.Contains(ch))
   return true;
}
Descendant Selectors in CSS

The CSS element selector is used to select the descendant of first element with element name matching the second selector.
The syntax for CSS descendant selector is as follows −
element element {
   /*declarations*/
}
The following examples illustrate CSS descendant selector −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
   float: right;
   margin: 25px;
   padding: 5px;
   width: 80px;
   height: 80px;
   border: solid aqua;
}
div div {
   border-color: blue;
   border-radius: 50%;
}
div div div {
   border-color: orange;
   border-radius: unset;
}
</style>
</head>
<body>
<div>
<div>
<div>
</div>
</div>
</div>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
li li {
   background-color: lightsteelblue;
}
</style>
</head>
<body>
<ol>
<li></li>
<ul>
<li>
<ul>
<li></li>
</ul>
</li>
</ul>
<li></li>
</ol>
</body>
</html>
This gives the following output −
A One-Bit Sliding Window Protocol

Sliding window protocols are data link layer protocols for reliable and sequential delivery of data frames. The sliding window is also used in Transmission Control Protocol. In these protocols, the sender has a buffer called the sending window and the receiver has buffer called the receiving window.
In one – bit sliding window protocol, the size of the window is 1. So the sender transmits a frame, waits for its acknowledgment, then transmits the next frame. Thus it uses the concept of stop and waits for the protocol. This protocol provides for full – duplex communications. Hence, the acknowledgment is attached along with the next data frame to be sent by piggybacking.
The data frames to be transmitted additionally have an acknowledgment field, ack field that is of a few bits length. The ack field contains the sequence number of the last frame received without error. If this sequence number matches with the sequence number of the frame to be sent, then it is inferred that there is no error and the frame is transmitted. Otherwise, it is inferred that there is an error in the frame and the previous frame is retransmitted.
Since this is a bi-directional protocol, the same algorithm applies to both the communicating parties.
begin
   frame s, r; //s and r denotes frames to be sent and received
   SeqNo = 0; // Initialise sequence number of outbound frame  
   RSeqNo = 0; // Initialise sequence number of expected frame
   while (true) //check repeatedly
   do
      Wait_For_Event(); //wait for availability of packet
      if ( Event(Request_For_Transfer) AND canSend) then
         Get_Data_From_Network_Layer();
         s = Make_Frame(SeqNo);
         Store_Copy_Frame(s);
         Start_Timer(s);
         SeqNo = SeqNo + 1;
      end if;
      Wait_For_Event(); //wait for arrival of frame
      if ( Event(Frame_Arrival) then
         r = Receive_Frame_From_Physical_Layer();
         if ( r.SeqNo = RSeqNo ) then
            Extract_Data(r);
            Deliver_Data_To_Network_Layer(r);
            Stop_Timer(r);
            RSeqNo = RSeqNo + 1;
         end if
      end if
      s.ack = r.SeqNo;
      Send_Frame_To_Physical_Layer(s);
      Start_Timer(s);
      SeqNo = SeqNo + 1;
   end while
end
The following diagram depicts a scenario with sequence numbers 0, 1, 2, 3, 0, 1, 2 and so on. It depicts the sliding windows in the sending and the receiving stations during frame transmission.
GATE | GATE-CS-2009 | Question 60 - GeeksforGeeks

28 Jun, 2021
Consider a system with 4 types of resources R1 (3 units), R2 (2 units), R3 (3 units), R4 (2 units). A non-preemptive resource allocation policy is used. At any given instance, a request is not entertained if it cannot be completely satisfied. Three processes P1, P2, P3 request the sources as follows if executed independently.
Process P1: 
t=0: requests 2 units of R2 
t=1: requests 1 unit of R3 
t=3: requests 2 units of R1 
t=5: releases 1 unit of R2    
        and 1 unit of R1. 
t=7: releases 1 unit of R3 
t=8: requests 2 units of R4 
t=10: Finishes

Process P2: 
t=0: requests 2 units of R3 
t=2: requests 1 unit of R4 
t=4: requests 1 unit of R1 
t=6: releases 1 unit of R3 
t=8: Finishes

Process P3: 
t=0: requests 1 unit of R4 
t=2: requests 2 units of R1 
t=5: releases 2 units of R1 
t=7: requests 1 unit of R2 
t=8: requests 1 unit of R3 
t=9: Finishes
Which one of the following statements is TRUE if all three processes run concurrently starting at time t=0? (A) All processes will finish without any deadlock(B) Only P1 and P2 will be in deadlock.(C) Only P1 and P3 will be in a deadlock.(D) All three processes will be in deadlockAnswer: (A)Explanation:
We can apply the following Deadlock Detection algorithm and see that there is no process waiting indefinitely for a resource. See this for deadlock detection algorithm.
Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
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-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 64
How to log a Python exception? - GeeksforGeeks

29 Sep, 2021
To log an exception in Python we can use logging module and through that we can log the error.
Logging module provides a set of functions for simple logging and for following purposes
DEBUG
INFO
WARNING
ERROR
CRITICAL
Logging an exception in python with an error can be done in the logging.exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler.
See the following code for more clarity:
Example 1 :
Python3
# importing the moduleimport logging try:    printf("GeeksforGeeks")except Exception as Argument:    logging.exception("Error occurred while printing GeeksforGeeks")
Output :
ERROR:root:Error occurred while printing GeeksforGeeks
Traceback (most recent call last):
  File "/home/gfg.py", line 3, in 
    printf("GeeksforGeeks")
NameError: name 'printf' is not defined
Example 2: We can also log the error message into a different file without showing error in the console by the following method:
Python3
# importing the moduleimport logging try:    printf("GeeksforGeeks")except Exception as Argument:      # creating/opening a file     f = open("demofile2.txt", "a")      # writing in the file     f.write(str(Argument))           # closing the file     f.close()
Error message will be stored in file name demofille2.txt in same directory as code.
Output :
Traceback (most recent call last):
  File "/home/gfg.py", line 5, in 
    printf("GeeksforGeeks")
NameError: name 'printf' is not defined
khushboogoyal499
sooda367
Python-exceptions
python-utility
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
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
double_click method – Action Chains in Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around double_click method on Action Chains in Python Selenium. double_click method is used to double click on an element or current position.
Syntax –
double_click(on_element=None)
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use double_click method as an Action chain as below –
double_click(on_element=element)

To demonstrate, double_click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # create action chain objectaction = ActionChains(driver)  # double click the itemaction.double_click(on_element = element)  # perform the operationaction.perform()
Output –
Python-selenium
selenium
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Indices of numbers greater than K

02 Apr, 2019
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices greater than particular number, but this approach fails in case of duplicate numbers. Let’s discuss certain ways in which this problem can be successfully solved.
Method #1 : Using loopThis problem can easily be solved using loop with a brute force approach in which we can just check for the index as we iterate and append it in a new list as we proceed forward.
# Python3 code to demonstrate# index of matching element using loop  # initializing list test_list = [12, 10, 18, 15, 8, 18]  # printing original listprint("The original list : " + str(test_list))  # using loop# index of matching elementres = []for idx in range(0, len(test_list)) :    if test_list[idx] > 10:        res.append(idx)  # print resultprint("The list of indices greater than 10 : " + str(res))
The original list : [12, 10, 18, 15, 8, 18]
The list of indices greater than 10 : [0, 2, 3, 5]

 
Method #2 : Using list comprehension + enumerate()The combination of these two function can also perform this particular task efficiently and in one line. The enumerate function is used to get element and its index simultaneously.
# Python3 code to demonstrate# index of matching element# using list comprehension + enumerate()  # initializing list test_list = [12, 10, 18, 15, 8, 18]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + enumerate()# index of matching elementres = [idx for idx, val in enumerate(test_list) if val > 10]  # print resultprint("The list of indices greater than 10 : " + str(res))
The original list : [12, 10, 18, 15, 8, 18]
The list of indices greater than 10 : [0, 2, 3, 5]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Sum of the series 5+55+555+.. up to n terms

15 Jun, 2022
Find the sum up to n terms of the sequence: 5 + 55 + 555 + ... up to n. Examples :  
Input : 2
Output: 60

Input : 3
Output: 595
 
Approach:The above problem can be solved using the following formula: 
Sum = 5 + 55 + 555 + .... n terms. = 5/9[9 + 99 + 999 + .... n terms] = 5/9[(10 – 1) + (100 – 1) + (1000 – 1) + ... n terms] = 5/9[10 + 100 + 1000 ..... – (1 + 1 + ... 1)] = 5/9[10(10n – 1)/(10 – 1) + (1 + 1 + ... n times)) = 50/81(10n – 1) – 5n/9
Below is the Implementation to find the sum of given series:  
C++
Java
Python3
C#
PHP
Javascript
// C++ program for sum of the// series 5 + 55 + 555.....n#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesint sumOfSeries(int n){    return 0.6172 *           (pow(10, n) - 1) -                    0.55 * n;     } // Driver codeint main(){    int n = 2;    cout << sumOfSeries(n);    return 0;}
// Java program for sum of the// series 5 + 55 + 555.....n class GFG{     // function which return the    // the sum of series    static int sumOfSeries(int n)    {        return (int) (0.6172 *                     (Math.pow(10, n) - 1) -                                0.55 * n);    }         // Driver code    public static void main(String []args)    {        int n = 2;        System.out.println(sumOfSeries(n));    }} // This code is contributed by UPENDRA BARTWAL.
# python program for sum of the# series 5 + 55 + 555.....n def sumOfSeries(n):    return (int) (0.6172 *                 (pow(10, n) - 1) -                        0.55 * n)  # Driver Coden = 2print(sumOfSeries(n)) # This code is contributed# by Upendra Singh Bartwal
// C# program for sum of the// series 5 + 55 + 555.....nusing System; class GFG{     // Function which return the    // the sum of series    static int sumOfSeries(int n)    {        return (int)(0.6172 *                    (Math.Pow(10, n) - 1) -                                 0.55 * n);    }         // Driver code    public static void Main()    {        int n = 2;        Console.Write(sumOfSeries(n));    }} // This code is contributed by vt_m.
<?php// PHP program for sum of the//  series 5 + 55 + 555.....n // function which return the// the sum of seriesfunction sumOfSeries($n){    return (int)(0.6172 *                (pow(10, $n) - 1) -                        0.55 * $n);} // Driver code$n = 2;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script>// javascript program for sum of the// series 5 + 55 + 555.....n     // function which return the    // the sum of series    function sumOfSeries(n) {        return parseInt( (0.6172 * (Math.pow(10, n) - 1) - 0.55 * n));    }     // Driver code       var n = 2;    document.write(sumOfSeries(n)); // This code is contributed by aashish1995</script>
Output :  
60
Time complexity: O(log n) since using the inbuilt power function.
Auxiliary Space:  O(1) 
jit_t
aashish1995
polymatir3j
series
series-sum
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Materialize - Colors

Materialize supports a rich set of color classes. These color classes are inspired and developed considering the colors used in marketing, road signs, and sticky notes.
red
pink
purple
deep-purple
indigo
blue
light-blue
cyan
teal
green
light-green
lime
yellow
amber
orange
deep-orange
brown
grey
blue-grey
black
white
transparent
Following is the list of lightness/darkness classes, which can be used to vary the color applied.
lighten-1
lighten-2
lighten-3
lighten-4
lighten-5
darken-1
darken-2
darken-3
darken-4
accent-1
accent-2
accent-3
accent-4
The following example demonstrates how to use the above classes to render the background or to change the color of the text. In case of background, add the classes as such and in case of text, suffix '-text' to color class and prefix 'text-' to lightning class.
<!DOCTYPE html>
<html>
   <head>
      <title>The Materialize Colors Example</title>
         <meta name="viewport" content="width=device-width, initial-scale=1">
         <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
         <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
   </head>
   <body>
      <h2>Color Theme Demo</h2>
      <hr/>
      <div class="card-panel">
         <div class="card-panel red lighten-2">
            <h1>Red Colored Theme</h1>
         </div>
         <span class="red-text text-darken-2">
            <h2>Red Colored Text</h2>
         </span>
         <ul>
            <li class="red lighten-5"><p>Using red lighten-5</p></li>
            <li class="red lighten-4"><p>Using red lighten-4</p></li>
            <li class="red lighten-3"><p>Using red lighten-3</p></li>
            <li class="red lighten-2"><p>Using red lighten-2</p></li>
            <li class="red lighten-1"><p>Using red lighten-1</p></li>
            <li class="red"><p>Using red</p></li>
            <li class="red darken-1"><p>Using red darken-1</p></li>
            <li class="red darken-2"><p>Using red darken-2</p></li>
            <li class="red darken-3"><p>Using red darken-3</p></li>
            <li class="red darken-4"><p>Using red darken-4</p></li>
            <li class="red accent-1"><p>Using red accent-1</p></li>
            <li class="red accent-2"><p>Using red accent-2</p></li>
            <li class="red accent-3"><p>Using red accent-3</p></li>
            <li class="red accent-4"><p>Using red accent-4</p></li>
         </ul>
       </div>
    </body>
</html>
Verify the output.
 Print
 Add Notes
 Bookmark this page
Angular Google Charts - Combination Chart

Combination chart helps in rendering each series as a different marker type from the following list: line, area, bars, candlesticks, and stepped area. To assign a default marker type for series, use the seriesType property. Series property is to be used to specify properties of each series individually. Following is an example of a Column Chart showing differences.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Column Chart showing differences.
We've used ComboChart class to show a Combination Chart.
type='ComboChart';

app.component.ts
import { Component } from '@angular/core';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Fruits distribution';
   type = 'ComboChart';
   data = [
      ["Apples", 3, 2, 2.5],
      ["Oranges",2, 3, 2.5],
      ["Pears", 1, 5, 3],
      ["Bananas", 3, 9, 6],
      ["Plums", 4, 2, 3]
   ];
   columnNames = ['Fruits', 'Jane','Jone','Average'];
   options = {   
      hAxis: {
         title: 'Person'
      },
      vAxis:{
         title: 'Fruits'
      },
      seriesType: 'bars',
      series: {2: {type: 'line'}}
   };
   width = 550;
   height = 400;
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to create a plot of empirical distribution in R?

The empirical distribution can be found by using the function ecdf and if we want to create a plot of empirical distribution then plot function will be used.
For example, if we have a vector called X then plot of empirical distribution can be created by using the below command −
plot(ecdf(X))
To create a plot of empirical distribution in R, use the code given below −
x<-rnorm(100)
plot(ecdf(x))
If you execute the above given code, it generates the following output −
To create a plot of empirical distribution in R, use the code given below −
y<-rpois(10000,2)
plot(ecdf(y))
If you execute the above given code, it generates the following output −
Draw a line in C++ graphics - GeeksforGeeks

25 Jan, 2018
graphics.h library is used to include and facilitate graphical operations in program. graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games. You can draw circles, lines, rectangles, bars and many other geometrical figures. You can change their colors using the available functions and fill them.
Examples:
For line 1, Input : x1 = 150, y1 = 150, x2 = 450, y2 = 150
For line 2, Input : x1 = 150, y1 = 200, x2 = 450, y2 = 200
For line 2, Input : x1 = 150, y1 = 250, x2 = 450, y2 = 250
Output :



Explanation :The header file graphics.h contains line() function which is described below :
Declaration : void line(int x1, int y1, int x2, int y2);
line function is used to draw a line from a point(x1,y1) to point(x2,y2) i.e. (x1,y1) and (x2,y2) are end points of the line.The code given below draws a line.
// C++ Implementation for drawing line#include <graphics.h>  // driver codeint main(){    // gm is Graphics mode which is a computer display    // mode that generates image using pixels.    // DETECT is a macro defined in "graphics.h" header file    int gd = DETECT, gm;      // initgraph initializes the graphics system    // by loading a graphics driver from disk    initgraph(&gd, &gm, "");      // line for x1, y1, x2, y2    line(150, 150, 450, 150);      // line for x1, y1, x2, y2    line(150, 200, 450, 200);      // line for x1, y1, x2, y2    line(150, 250, 450, 250);      getch();      // closegraph function closes the graphics    // mode and deallocates all memory allocated    // by graphics system .    closegraph();}
Output:


computer-graphics
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Bitwise Operators in C/C++
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
Object Oriented Programming in C++
How to show numpy 2D array as grayscale image in Jupyter Notebook?

To show a 2D array as a grayscale image in Jupyter Notebook, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a random data using numpy.
Create a random data using numpy.
Display the data as an image, i.e., on a 2D regular raster, with gray colormap.
Display the data as an image, i.e., on a 2D regular raster, with gray colormap.
To display the figure, use Show() method.
To display the figure, use Show() method.
from matplotlib import pyplot as plt
import numpy as np

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Random data points
data = np.random.rand(5, 5)

# Plot the data using imshow with gray colormap
plt.imshow(data, cmap='gray')

# Display the plot
plt.show()
It will produce the following output −
3D Streamtube Plots using Plotly in Python - GeeksforGeeks

05 Sep, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
In plotly, the streamtube plot, parameter includes X, Y, and Z, which set the coordinates with vector fields. U, V, and W which set X, Y, and Z component of vector fields. A streamtube is a tubular region surrounded by streamlines that form a closed loop.
Syntax: plotly.graph_objects.Streamtube(arg=None, hoverinfo=None, showscale=None, u=None, v=None, w=None, x=None, y=None, z=None, **kwargs)
Parameters:
arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Streamtube
hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired.
showscale: Determines whether or not a colorbar is displayed for this trace.
u: Sets the x components of the vector field.
v: Sets the y components of the vector field.
w: Sets the z components of the vector field.
x: Sets the x coordinates of the vector field.
y: Sets the y coordinates of the vector field.
z: Sets the z coordinates of the vector field.
Example:
Python3
import plotly.graph_objects as go  fig = go.Figure(data=go.Streamtube(x=[1, 1, 1], y=[1, 1, 2],                                   z=[0, 0, 0], u=[0, 0, 0],                                    v=[1, 1, 1], w=[0, 0, 0]))fig.show()
Output:
The diameter of tubes can be determined by local divergence of the vector field. The norms are proportionate but the direction of the vector is different and it result in different divergence field.
Example:
Python3
import plotly.graph_objects as goimport numpy as np  x, y, z = np.mgrid[0:20, 0:20, 0:20]x = x.flatten()y = y.flatten()z = z.flatten()  u = np.zeros_like(x)v = np.zeros_like(y)w = z**2  fig = go.Figure(data=go.Streamtube(x=x, y=y, z=z, u=u, v=v, w=w))fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
How to get the values of an object in JavaScript?

There are some methods such as Object.values() to get the values of an object. But through those methods, the process to find out the values is lengthy. To alleviate this, Underscore.js a library of javascript has provided a method called _.values(). This method requires no for loop to execute the values. It is a direct method to execute the values of an object. 
In the following example, the values of an object were executed using the Object.values() method. This method requires a for-loop to execute the values.
Live Demo
<html>
<body>
<script>
   var user = {
      name: "Rahim",
      designation: "content developer"
   };
   for (let value of Object.values(user)) {
      document.write(value + "</br>");
   }
</script>
</body>
</html>
Rahim
content developer
In the following example, the values of an object were executed using _.values() method. Here no for-loop is required. It's a straight forward method.
Live Demo
<html>
<body>
<script
src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script>
      var res = JSON.stringify(_.values({"name": 'ElonMusk',age: 47, "Organization":'Spacex' }));
      document.write((res));
   </script>
</body>
</html>
["ElonMusk",47,"Spacex"]