code-rag-bench/online-tutorials huggingface dataset:
GATE | GATE-IT-2004 | Question 83 - GeeksforGeeks

28 Jun, 2021
A 20 Kbps satellite link has a propagation delay of 400 ms. The transmitter employs the “go back n ARQ” scheme with n set to 10. Assuming that each frame is 100 bytes long, what is the maximum data rate possible?(A) 5Kbps(B) 10Kbps(C) 15Kbps(D) 20KbpsAnswer: (B)Explanation:
It uses the sliding window protocol for transmission of data. 
The question takes into consideration the variant of sliding window protocol 
namely GO BACK N ARQ. In this protocol the sender can have up to N packets 
unacknowledged that are still remaining in the pipeline. The receiver only 
sends cumulative acknowledgements. In case of encountering an error the sender 
has to resend all the data frames following the error.

According to the question:
The data rate of the link is 20 Kbps and the propagation delay = 400 ms
So, the time required to transmit 100 bytes long data will be given by

Transmission Time t = Number of bits to be transmitted / data rate of the link 
                    = (100* 8 bits) /20 Kbps =  40 ms

Now, the propagation delay is given as d = 400 ms

So the efficiency of the link is given by:

Efficiency E = N * t / ( t+ 2 * d )

Where N = window size

E = 10 * 40 / (40+2*400) = 0.476

So, the maximum data rate attainable = 0.476 * 20 Kbps = 9.52 Kbps

This is close to 10.
So, the answer will be 10Kbps.

This explanation has been contributed by Namita Singh.Quiz of this Question
GATE IT 2004
GATE-GATE IT 2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2007 | Question 64
GATE | GATE-CS-2009 | Question 28
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 46
GATE | GATE-CS-2005 | Question 80 - GeeksforGeeks

28 Jun, 2021
Consider the following data path of a CPU.
The, ALU, the bus and all the registers in the data path are of identical size. All operations including incrementation of the PC and the GPRs are to be carried out in the ALU. Two clock cycles are needed for memory read operation – the first one for loading address in the MAR and the next one for loading data from the memory bus into the MDR79.The instruction “call Rn, sub” is a two word instruction. Assuming that PC is incremented during the fetch cycle of the first word of the instruction, its register transfer interpretation is
Rn < = PC + 1;
PC < = M[PC]; 
The minimum number of CPU clock cycles needed during the execution cycle of this instruction is:(A) 2(B) 3(C) 4(D) 5Answer: (B)Explanation: One cycle to increment PC, one cycle to load PC into MAR, one cycle to fetch memory content and load into PC.Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 33
GATE | GATE-CS-2007 | Question 64
Amortized analysis for increment in counter in C++

Amortized analysis for a sequence of operations is used to determine the run time, the average time required by the sequence. In cannot be treated as an average-case analysis done on the algorithm as it does not always take the average case scenario. There are cases that occur as a worst-case scenario of analysis. So, amortized analysis can be treated as a worst-case analysis for multiple operations in a sequence. Here, the cost of doing each operations in different and for some its high. This problem is a general view using the binary counter.
Let’s see the working and implementation in c++ programming language so that we will be clear with the concepts.
A k-bit binary counter is implemented using a binary array of length k which is initially valued 0. On this value, the increment operation is performed multiple times. Here is how the binary 8-bit array will behave on the increment operation performed on it.
Initially, 00000000 > 00000001 > 00000010 > 00000011 > 00000100 > 00000101 >.... > 11111111.
This logic is to check for the occurrence of first 0 from the last bit of the number and flip it to 1 and all the bits sequentially following it to 0.
#include <iostream>
using namespace std;
int main(){
   int number[] = {1,0,0,1,0,1,1,1};
   int length = 8;
   int i = length - 1;
   while (number[i] == 1) {
      number[i] = 0;
      i--;
   }
   if (i >= 0)
   str[i] = 1;
   for(int i = 0 ; i<length ; i++)
   cout<<number[i]<<" ";
}
1 0 0 1 0 0 0 0
In this problem, the cost of each operation is constant and does not depend on the number of bits,
Here the asymptotic analysis for the cost of a sequence is O(n).
The total number of flips that are done in n operations is − n + n/2 + n/4 + ..... + n/k2 k in the number of flips.
This is a GP with HP in the denominator.
The sum of flip
Sum = n + n/2 + n/4 + ..... + n/k2 < n/(1-1/2) = 2n
Now, aromatized cost of operation is O(n) / 2n = O(1)
The order is O(1) which is not proportional to n the number of bits in the number.
MySQL update a column with an int based on order?

The syntax is as follows to update a column with an int based on order
set @yourVariableName=0;
update yourTableName
set yourColumnName=(@yourVariableName:=@yourVariableName+1)
order by yourColumnName ASC;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table updateColumnDemo
   -> (
   -> Id int,
   -> OrderCountryName varchar(100),
   -> OrderAmount int
   -> );
Query OK, 0 rows affected (1.76 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(10,'US');
Query OK, 1 row affected (0.46 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(20,'UK');
Query OK, 1 row affected (0.98 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(30,'AUS');
Query OK, 1 row affected (0.77 sec)
mysql> insert into updateColumnDemo(Id,OrderCountryName) values(40,'France');
Query OK, 1 row affected (1.58 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from updateColumnDemo;
The following is the output
+------+------------------+-------------+
| Id   | OrderCountryName | OrderAmount |
+------+------------------+-------------+
| 10   | US               | NULL        |
| 20   | UK               | NULL        |
| 30   | AUS              | NULL        |
| 40   | France           | NULL        |
+------+------------------+-------------+
4 rows in set (1.00 sec)
Here is the query to update a column with an int based on order
mysql> set @sequenceNumber=0;
Query OK, 0 rows affected (0.00 sec)
mysql> update updateColumnDemo
   -> set OrderAmount=(@sequenceNumber:=@sequenceNumber+1)
   -> order by OrderAmount ASC;
Query OK, 4 rows affected (0.25 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check the table records once again.
The query is as follows
mysql> select *from updateColumnDemo;
The following is the output
+------+------------------+-------------+
| Id   | OrderCountryName | OrderAmount |
+------+------------------+-------------+
| 10   | US               | 1           |
| 20   | UK               | 2           |
| 30   | AUS              | 3           |
| 40   | France           | 4           |
+------+------------------+-------------+
4 rows in set (0.00 sec)
Scala Int isValidLong() method with example - GeeksforGeeks

30 Jan, 2020
The isValidLong() method is utilized to return true if the specified int number is either zero or lies within the range of scala.long MinValue and MaxValue; otherwise returns false.
Method Definition: (Int_Number).isValidLong
Return Type: It returns true if the specified number is either zero or lies within the range of scala.long MinValue and MaxValue; otherwise returns false.
Example #1:
// Scala program of Int isValidLong()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying isValidLong method        val result = (0).isValidLong                  // Displays output        println(result)          }} 
true

Example #2:
// Scala program of Int isValidLong()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying isValidLong method        val result = (5).isValidLong                  // Displays output        println(result)          }} 
true

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in Scala
Hello World in Scala
Scala | Option
How to install Scala on Windows?
Scala | Case Class and Case Object
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Scala Map get() method with example
Scala List map() method with example
Scala Sequence
Scala List exists() method with example
DBMS - Joins

We understand the benefits of taking a Cartesian product of two relations, which gives us all the possible tuples that are paired together. But it might not be feasible for us in certain cases to take a Cartesian product where we encounter huge relations with thousands of tuples having a considerable large number of attributes.
Join is a combination of a Cartesian product followed by a selection process. A Join operation pairs two tuples from different relations, if and only if a given join condition is satisfied.
We will briefly describe various join types in the following sections.
Theta join combines tuples from different relations provided they satisfy the theta condition. The join condition is denoted by the symbol θ.
R1 ⋈θ R2

R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the attributes don’t have anything in common, that is R1 ∩ R2 = Φ.
Theta join can use all kinds of comparison operators.
Student_Detail −
STUDENT ⋈Student.Std = Subject.Class SUBJECT

When Theta join uses only equality comparison operator, it is said to be equijoin. The above example corresponds to equijoin.
Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product does. We can perform a Natural Join only if there is at least one common attribute that exists between two relations. In addition, the attributes must have the same name and domain.
Natural join acts on those matching attributes where the values of attributes in both the relations are same.
Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to include all the tuples from the participating relations in the resulting relation. There are three kinds of outer joins − left outer join, right outer join, and full outer join.
All the tuples from the Left relation, R, are included in the resulting relation. If there are tuples in R without any matching tuple in the Right relation S, then the S-attributes of the resulting relation are made NULL.
All the tuples from the Right relation, S, are included in the resulting relation. If there are tuples in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL.
All the tuples from both participating relations are included in the resulting relation. If there are no matching tuples for both relations, their respective unmatched attributes are made NULL.

    178 Lectures 
     14.5 hours 

 Arnab Chakraborty

    194 Lectures 
     16 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Difference between npm i and npm ci in Node.js - GeeksforGeeks

02 Feb, 2022
The following difference covers how npm i and npm ci command are different from each other and their functioning. The npm which is called a node package manager which is used for managing modules needed for our application.
npm i: The npm i (or npm install) is used to install all dependencies or devDependencies from a package.json file.
Syntax:
npm install "package-name"
// OR
npm i "package-name"
npm ci: CI stands for continuous integration and npm ci is used to install all exact version dependencies or devDependencies from a package-lock.json file.
Syntax:
npm ci
Differences between npm i and npm ci are:
S.No.
npm i
npm ci
wua92cbrovlggb9ksnk9i8j3vxe1yf9wer133kjt
q4ok2xsrp23ug90isn3i3y8ns544rge54aetgjt1
Node.js-Misc
Difference Between
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Informed and Uninformed Search in AI
Difference between HashMap and HashSet
Difference between Internal and External fragmentation
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
random.shuffle() function in Python - GeeksforGeeks

18 Jan, 2022
shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is inplace.
Syntax : random.shuffle(sequence, function)
Parameters : 
sequence : can be a list 
function : optional and by default is random(). It should return a value between 0 and 1.
Returns : nothing 
Python3
# import the random moduleimport random  # declare a listsample_list = ['A', 'B', 'C', 'D', 'E'] print("Original list : ")print(sample_list) # first shufflerandom.shuffle(sample_list)print("\nAfter the first shuffle : ")print(sample_list) # second shufflerandom.shuffle(sample_list)print("\nAfter the second shuffle : ")print(sample_list)
Output : 
Original list : 
['A', 'B', 'C', 'D', 'E']

After the first shuffle : 
['A', 'B', 'E', 'C', 'D']

After the second shuffle : 
['C', 'E', 'B', 'D', 'A']
The shuffle() method cannot be used to shuffle immutable datatypes like strings.
Python3
# import the random moduleimport random  # user defined function to shuffledef sample_function():    return 0.5 sample_list = ['A', 'B', 'C', 'D', 'E']print("Original list : ")print(sample_list) # as sample_function returns the same value# each time, the order of shuffle will be the# same each timerandom.shuffle(sample_list, sample_function)print("\nAfter the first shuffle : ")print(sample_list) sample_list = ['A', 'B', 'C', 'D', 'E'] random.shuffle(sample_list, sample_function)print("\nAfter the second shuffle : ")print(sample_list)
Output : 
Original list : 
['A', 'B', 'C', 'D', 'E']

After the first shuffle : 
['A', 'D', 'B', 'E', 'C']

After the second shuffle : 
['A', 'D', 'B', 'E', 'C']
gireshdatta
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
jQuery | hide() with Examples

13 Feb, 2019
The hide() is an inbuilt method in jQuery used to hide the selected element.Syntax:
$(selector).hide(duration, easing, call_function);

Here selector is the selected element.Parameter: It accepts three parameters which are specified below-
duration: It specifies the speed of the hide effect.
easing: It specifies the speed of the element at different point of animation.
call_function: This is call back function to be executed after hide operation.
Return Value: It does not return any value.
<html>   <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <!-- jQuery code to show the working of this method -->    <script>        $(document).ready(function() {            $(".b1").click(function() {                $("p").hide();            });        });    </script>    <style>        div {            width: 50%;            height: 80px;            padding: 20px;            margin: 10px;            border: 2px solid green;            font-size: 30px;        }                   .b1 {            margin: 10px;        }    </style></head>   <body>    <div>        <p>GeeksforGeeks !.</p>    </div>    <!-- click on this button and above paragraph will disappear -->    <button class="b1">Click me !</button>   </body>   </html>
Output:Before clicking on “Click me!” button-
After clicking on “Click me!” button-
Code #2:In the below code, parameter is passed to this method.
<html>  <head>    <script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <script>        <!-- jQuery code to show the working of this method -->        $(document).ready(function() {            $(".btn1").click(function() {                $("p").hide(1000, function() {                    alert("Hide() method has finished its working!");                });            });        });    </script>    <style>        p {            width: 40%;            padding: 20px;            height: 50px;            border: 2px solid green;        }    </style></head>  <body>      <p>GeeksforGeeks.!</p>    <!-- click on this button and above paragraph will hide -->    <button class="btn1">Click to Hide</button>  </body>  </html>
Output:Before clicking on the “Click to Hide” button-
After clicking on the “Click to Hide” button-
jQuery-Effects
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use CSS variables with TailwindCSS ?

12 May, 2021
Tailwind CSS  allows users to predefined classes instead of using the pure CSS properties. 
We have to install the Tailwind CSS.  Create the main CSS file (Global.css) which will look like the below code.
Global.css: In the following code, the entire body is wrapped into a single selector. The entire body is selected by using class root or id root.
@tailwind base;
@tailwind components;
@tailwind utilities;

.root,
#root,
#docs-root {
  --primary-color: green;
  --secondary-color: blue;
}
tailwind.config.js: The following code is the content for the tailwind config file with new CSS variables. We simply want to extend the config to add new values.
Javascript
module.exports = {  theme: {    extend: {      colors: {        header: "var(--header)",        primary: "var(--primary)",        secondary: "var(--secondary)",        main: "var(--main)",        background: "var(--background)",        accent: "var(--accent)",        footer: "var(--footer)"      },    },  },};
HTML code: After completing the above steps, we can use CSS variables in the following HTML code. 
HTML
<!DOCTYPE html><head>          <link href=         "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"        rel="stylesheet">    <script src="tailwind.config.js">    </script>   <link href="Global.css" rel="stylesheet"></head>  <body class="text-center"><center>    <h1 class="text-green-600 text-5xl font-bold">        GeeksforGeeks    </h1>    <b>Tailwind CSS flex Class</b>    <div class="flex bg-green-200 p-4 mx-16 ">        <div class="flex-1 bg-green-500 rounded-lg">1</div>        <div class="flex-1 bg-green-500 rounded-lg">2</div>        <div class="flex-1 bg-green-500 rounded-lg">3</div>    </div></center></body>  </html>
Output:
Picked
Tailwind CSS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if the given string is IPv4 or IPv6 or Invalid

28 Jul, 2020
Given a string. The task is to check if the given string is IPv4 or IPv6 or Invalid.
Examples:
Input : “192.168.0.1”Output : IPv4Explanation : It is a valid IPv4 address
Input : “2001:0db8:85a3:0000:0000:8a2e:0370:7334”Output : IPv6Explanation : It is a valid IPv6 address
Input : “255.32.555.5”Output : InvalidExplanation : It is an invalid IPv4 address as the 3rd octet value(i.e 555) is greater 255.
Input : “250.32:555.5”Output : InvalidExplanation : The given string is invalid as it consists of both : and .
To implement the above problem, we will use the ipaddress module in Python. This module provides the capabilities to create, manipulate, and operate on IPv4 and IPv6 addresses and networks.
Below is the implementation.
from ipaddress import ip_address, IPv4Address  def validIPAddress(IP: str) -> str:    try:        return "IPv4" if type(ip_address(IP)) is IPv4Address else "IPv6"    except ValueError:        return "Invalid"  if __name__ == '__main__' :              # Enter the Ip address     Ip = "192.168.0.1"    print(validIPAddress(Ip))       Ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"    print(validIPAddress(Ip))       Ip = "256.32.555.5"    print(validIPAddress(Ip))        Ip = "250.32:555.5"    print(validIPAddress(Ip))
Output :
IPv4
IPv6
Invalid
Invalid
Python string-programs
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas tseries.offsets.DateOffset

23 Apr, 2019
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F).
DateOffsets can be created to move dates forward a given number of valid dates. For example, Bday(2) can be added to a date to move it two business days forward. If the date does not start on a valid date, first it is moved to a valid date and then offset is created.
Pandas tseries.offsets.DateOffset is used to create standard kind of date increment used for a date range.
Syntax: pandas.tseries.offsets.DateOffset(n=1, normalize=False, **kwds)
Parameter :n : The number of time periods the offset represents.normalize : Whether to round the result of a DateOffset addition down to the previous midnight.level : int, str, default None**kwds : Temporal parameter that add to or replace the offset value. Parameters that add to the offset (like Timedelta): years, months etc.
Returns : DateOffsets
Example #1: Use pandas.tseries.offsets.DateOffset function to create dateoffsets of 2 days.
# importing pandas as pdimport pandas as pd  # Creating Timestampts = pd.Timestamp('2019-10-10 07:15:11')  # Create the DateOffsetdo = pd.tseries.offsets.DateOffset(n = 2)  # Print the Timestampprint(ts)  # Print the DateOffsetprint(do)
Output :
Now we will add the dateoffset to the given timestamp object to create an offset of 2 days from the given date.
# Adding the dateoffset to the given timestampnew_timestamp = ts + do  # Print the updated timestampprint(new_timestamp)
Output :
As we can see in the output, we have successfully created an offset of 2 days and added it to the given timestamp object to move the date forward by 2 days.
Example #2: Use pandas.tseries.offsets.DateOffset function to create dateoffsets of 10 days and 2 hours.
# importing pandas as pdimport pandas as pd  # Creating Timestampts = pd.Timestamp('2019-10-10 07:15:11')  # Create the DateOffsetdo = pd.tseries.offsets.DateOffset(days = 10, hours = 2)  # Print the Timestampprint(ts)  # Print the DateOffsetprint(do)
Output :
Now we will add the dateoffset to the given timestamp object to create an offset of 10 days and 2 hours from the given date.
# Adding the dateoffset to the given timestampnew_timestamp = ts + do  # Print the updated timestampprint(new_timestamp)
Output :
As we can see in the output, we have successfully created an offset of 10 days and 2 hours and added it to the given timestamp object to move the date forward by 10 days and 2 hours.
Python pandas-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Analysis and Visualization in Python?

Python provides numerous libraries for data analysis and visualization mainly numpy, pandas, matplotlib, seaborn etc. In this section, we are going to discuss pandas library for data analysis and visualization which is an open source library built on top of numpy.
It allows us to do fast analysis and data cleaning and preparation.Pandas also provides numerous built-in visualization feautures which we are going to see below.
To install pandas, run the below command in your terminal −
pipinstall pandas
Orwe have anaconda, you can use
condainstall pandas
Data framesa re the main tools when we are working with pandas.
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(50)
df = pd.DataFrame(randn(6,4), ['a','b','c','d','e','f'],['w','x','y','z'])
df
Weare going to see some convenient ways to deal with missing data inpandas, which automatically gets filled with zero's or nan.
import numpy as np
import pandas as pd
from numpy.random import randn
d = {'A': [1,2,np.nan], 'B': [9, np.nan, np.nan], 'C': [1,4,9]}
df = pd.DataFrame(d)
df
So,we are having 3 missing value in above.
df.dropna()
df.dropna(axis = 1)
df.dropna(thresh = 2)
df.fillna(value = df.mean())
We are going to read the csv file which is either stored in our local machine(in my case) or we can directly fetch from the web.
#import pandas library
import pandas as pd

#Read csv file and assigned it to dataframe variable
df = pd.read_csv("SYB61_T03_Population Growth Rates in Urban areas and Capital cities.csv",encoding = "ISO-8859-1")

#Read first five element from the dataframe
df.head()
Toread the number of rows and columns in our dataframe or csv file.
#Countthe number of rows and columns in our dataframe.
df.shape
(4166,9)
Operationson dataframes can be done using various tools of pandas forstatistics
#To computes various summary statistics, excluding NaN values
df.describe()
# computes numerical data ranks
df.rank()
.....
.....
import matplotlib.pyplot as plt
years = [1981, 1991, 2001, 2011, 2016]

Average_populations = [716493000, 891910000, 1071374000, 1197658000, 1273986000]

plt.plot(years, Average_populations)
plt.title("Census of India: sample registration system")
plt.xlabel("Year")
plt.ylabel("Average_populations")
plt.show()
plt.scatter(years,Average_populations)
import matplotlib.pyplot as plt

Average_populations = [716493000, 891910000, 1071374000, 1197658000, 1273986000]

plt.hist(Average_populations, bins = 10)
plt.xlabel("Average_populations")
plt.ylabel("Frequency")

plt.show()
C# program to copy a range of bytes from one array to another

Use the Buffer.BlockCopy method to copy a range of bytes from one array to another −
Set a byte array −
byte[] b1 = new byte[] {22, 49};
byte[] b2 = new byte[5];
Copy bytes from one array to another −
Buffer.BlockCopy(b1, 0, b2, 0, 2);
The following is the complete code −
 Live Demo
using System;
class Demo {
   static void Main(){
      // byte arrays
      byte[] b1 = new byte[] {22, 49};
      byte[] b2 = new byte[5];
      // copying bytes from one to another
      Buffer.BlockCopy(b1, 0, b2, 0, 2);
      /* calling the method with the byte array b2 that has the copied elements */
      bufferFunc(b2);
   }
   static void bufferFunc(byte[] a) {
      for (int j = 0; j < a.Length; j++) {
         Console.Write(a[j]);
      }
      Console.WriteLine();
   }
}
2249000
How to create a frequency column for categorical variable in an R data frame?

To create a frequency column for categorical variable in an R data frame, we can use the transform function by defining the length of categorical variable using ave function. The output will have the duplicated frequencies as one value in the categorical column is likely to be repeated. Check out the below examples to understand how it can be done.
Consider the below data frame −
 Live Demo
Country<-sample(c("India","China","Egypt"),20,replace=TRUE)
Response<-rnorm(20)
df1<-data.frame(Country,Response)
df1
   Country  Response
1  Egypt   -0.6591480
2  China   -1.8163343
3  India   -1.0608470
4  Egypt    0.6736968
5  Egypt    0.7686130
6  India   -0.5509014
7  Egypt   -1.4049758
8  India   -0.1783958
9  China   -0.3233439
10 China    0.5749841
11 China    0.3870373
12 China   -0.9342403
13 China    0.2300502
14 Egypt   -0.4034456
15 Egypt   -0.5925468
16 India   -1.0564102
17 India    0.1227065
18 China    1.7980140
19 China   -1.3700720
20 India    0.9327951
Creating a frequency column for Country column in df1 −
transform(df1,Country_Frequency=ave(seq(nrow(df1)),Country,FUN=length))
  Country Response   Country_Frequency
1 Egypt   -0.6591480   6
2 China   -1.8163343   8
3 India   -1.0608470   6
4 Egypt    0.6736968   6
5 Egypt    0.7686130   6
6 India   -0.5509014   6
7 Egypt   -1.4049758   6
8 India   -0.1783958   6
9 China   -0.3233439   8
10 China   0.5749841   8
11 China   0.3870373   8
12 China  -0.9342403   8
13 China   0.2300502   8
14 Egypt  -0.4034456   6
15 Egypt  -0.5925468   6
16 India  -1.0564102   6
17 India   0.1227065   6
18 China   1.7980140   8
19 China  -1.3700720   8
20 India   0.9327951   6
 Live Demo
Temp<-sample(c("Hot","Cold"),20,replace=TRUE)
Y<-rpois(20,2)
df2<-data.frame(Temp,Y)
df2
   Temp   Y
1  Cold   1
2  Hot    1
3  Cold   4
4  Hot    1
5  Hot    2  
6  Hot    4
7  Hot    1
8  Hot    1
9  Cold   2
10 Hot    1
11 Cold   1
12 Hot    2
13 Hot    3
14 Cold   2
15 Cold   0
16 Cold   4
17 Hot    4
18 Hot    0
19 Cold   1
20 Cold   1
Creating a frequency column for Temp column in df2 −
transform(df2,Temp_Frequency=ave(seq(nrow(df2)),Temp,FUN=length))
  Temp   Y  Temp_Frequency
1  Cold  1   9
2  Hot   1  11
3  Cold  4   9
4  Hot   1  11
5  Hot   2  11
6  Hot   4  11
7  Hot   1  11
8  Hot   1  11
9  Cold  2   9
10 Hot  1   11
11 Cold 1    9
12 Hot  2   11
13 Hot  3   11
14 Cold 2    9
15 Cold 0    9
16 Cold 4    9
17 Hot  4   11
18 Hot  0   11
19 Cold 1    9
20 Cold 1    9
What are JSP comments?

JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out", a part of your JSP page.
Following is the syntax of the JSP comments −
<%-- This is JSP comment --%>
Following example shows the JSP Comments −
<html>
   <head>
      <title>A Comment Test</title>
   </head>
   <body>
      <h2>A Test of Comments</h2>
      <%-- This comment will not be visible in the page source --%>
   </body>
</html>
The above code will generate the following result −
A Test of Comments
How to check if a string in Python is in ASCII?

The simplest way is to loop over the characters of the string and check if each character is ASCII or not. 
def is_ascii(s):
    return all(ord(c) < 128 for c in s)
print is_ascii('ӓmsterdӒm')
This will give the output:
False
But this method is very inefficient. A better way is to decode the string using str.decode('ascii') and check for exceptions. 
mystring = 'ӓmsterdӓm'
try:
    mystring.decode('ascii')
except UnicodeDecodeError:
    print "Not an ASCII-encoded string"
else:
    print "May be an ASCII-encoded string"
This will give the output:
Not an ASCII-encoded string
HTML | <input> src Attribute - GeeksforGeeks

21 Feb, 2022
The HTML <input> src Attribute is used to specify the URL of the image to be used as a submit button. This attribute can only be used with <input type=”image”>.Syntax:  
<input src="URL">
Attribute Values: It contains a single value URL that specifies the link of the source image. There are two types of URL links which are listed below:  
Absolute URL: It points to another webpage.
Relative URL: It points to other files of the same web page.
Example:  
html
<!DOCTYPE html><html> <head>    <title>        HTML Input src Attribute    </title></head> <body style="text-align:center;">     <h1 style="color:green;">            GeeksForGeeks        </h1>     <h2>HTML Input src Attribute</h2>    <form>        <input id="myImage"               type="image"               src="https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png"               alt="Submit"               width="70"               height="48" />    </form></body> </html>
Output:  
Supported Browsers: The browsers supported by HTML <input> src Attribute are listed below:  
Google Chrome 1.0
Internet Explorer 2.0
Firefox 1.0
Apple Safari 1.0
Opera 1.0
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
A Simple Method for Numerical Integration in Python | by Harrison Hoffman | Towards Data Science

In this article, we will introduce a simple method for computing integrals in python. We will first derive the integration formula and then implement it on a few functions in python. This article assumes you have a basic understanding of probability and integral calculus, but if you don’t you can always skip ahead to the examples. Enjoy!
We must first state the definition of the expected value of a continuous random variable.
Suppose X is a random variable with with probability density function f(x). The expected value of X is defined as follows:
Next, we use the expectation formula to derive a simple equation for computing an integral. We would like to estimate the following integral:
We first rewrite the integral as follows:
We can then define a function h(x) as:
This allows us to rewrite the integral in a familiar form:
All of the computation in the integral has been reduced down to an expectation, and we know how to find the expected value of a set of data. The final approximation becomes:
We will start simple by integrating the quadratic function f(x) = x2 from 0 to 1.
# Dependenciesimport numpy as npimport scipy.integrate as integrateimport matplotlib.pyplot as plt# Our integral approximation functiondef integral_approximation(f, a, b):    return (b-a)*np.mean(f)# Integrate f(x) = x^2def f1(x):    return x**2# Define bounds of integrala = 0b = 1# Generate function valuesx_range = np.arange(a,b+0.0001,.0001)fx = f1(x_range)# Approximate integralapprox = integral_approximation(fx,a,b)approx
Our integral approximation comes out to be:
This is about what we would expect since the true value of the integral is 1/3. However, we can also compare our result to Scipy’s “quad” function.
# Scipy approximationintegrate.quad(f1,a,b)
The resulting value:
I’m sure this example has you on the edge of your seat, but let’s see if we can’t integrate a more complicated function.
The gaussian function is notorious for being extremely difficult to integrate. In this example, we will put our method to the test by integrating the standard normal distribution.
# Integrating a random functionnp.random.seed(42)def gaussian(x, mu, sigma):    return np.exp((-1*(x - mu)**2) / (2 * sigma**2))# Define mu and sigmamu = 0sigma = 1# Define bounds of integrala = -3b = 3# Generate function valuesx_range = np.linspace(-3,3,200)fx = gaussian(x_range, mu, sigma)
The resulting function looks like this:
The nice thing about our integral approximation is that the complexity of the function does affect the difficulty of the computation. In every case, all we need is the bounds of integration and the function values.
# Our approximationapprox = integral_approximation(fx,a,b)approx
Comparing to the Scipy solution:
# Scipy approximationintegrate.quad(lambda x: np.exp((-1*(x - mu)**2) / (2 * sigma**2)),a,b)
I hope that you found this article easy to follow and interesting!
VBScript Number Conversion Functions

Variable_name = Conversion_function_name(expression)
Number functions help us to convert a given number from one data subtype to another data subtype.
CDbl
A Function, which converts a given number of any variant subtype to double
CInt
A Function, which converts a given number of any variant subtype to Integer
CLng
A Function, which converts a given number of any variant subtype to Long
CSng
A Function, which converts a given number of any variant subtype to Single
Hex
A Function, which converts a given number of any variant subtype to Hexadecimal
Try the following example to understand all the Number Conversion Functions available in VBScript.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         x = 123
         y = 123.882
         document.write("x value after converting to double - " & CDbl(x) & "<br />")
         
         document.write("y value after converting to double - " & CDbl(y) & "<br />")
         
         document.write("x value after converting to Int -" & CInt(x) & "<br />")
         
         document.write("y value after converting to Int -" & CInt(y) & "<br />")
         
         document.write("x value after converting to Long -" & CLng(x) & "<br />")
         
         document.write("y value after converting to Long -" & CLng(y) & "<br />") 
         
         document.write("x value after converting to Single -" & CSng(x) & "<br />")
         
         document.write("y value after converting to Single -" & CSng(y) & "<br />") 
         
         document.write("x value after converting to Hex -" & Hex(x) & "<br />")
         
         document.write("y value after converting to Hex -" & Hex(y) & "<br />") 
      </script>
   </body>
</html>
When executed, the above script will produce the following output −
x value after converting to double - 123
y value after converting to double - 123.882
x value after converting to Int -123
y value after converting to Int -124
x value after converting to Long -123
y value after converting to Long -124
x value after converting to Single -123
y value after converting to Single -123.882
x value after converting to Hex -7B
y value after converting to Hex -7C


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Match multiple occurrences in a string with JavaScript?

To match multiple occurrences in a string, use regular expressions. Following is the code −
function checkMultipleOccurrences(sentence) {
   var matchExpression = /(JavaScript?[^\s]+)|(typescript?[^\s]+)/g;
   return sentence.match(matchExpression);
}
var sentence="This is my first JavaScript Program which is the subset
of typescript";
console.log(sentence);
console.log(checkMultipleOccurrences(sentence));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo70.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo70.js
This is my first JavaScript Program which is the subset of typescript
[ 'JavaScript', 'typescript' ]
How do you convert a list collection into an array in C#?

Firstly, set a list collection −
List < string > myList = new List < string > ();
myList.Add("RedHat");
myList.Add("Ubuntu");
Now, use ToArray() to convert the list to an array −
string[] str = myList.ToArray();
The following is the complete code −
 Live Demo
using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {

      List < string > myList = new List < string > ();
      myList.Add("RedHat");
      myList.Add("Ubuntu");

      Console.WriteLine("List...");
      foreach(string value in myList) {
         Console.WriteLine(value);
      }

      Console.WriteLine("Converting to Array...");
      string[] str = myList.ToArray();

      foreach(string s in myList) {
         Console.WriteLine(s);
      }
   }
}
List...
RedHat
Ubuntu
Converting to Array...
RedHat
Ubuntu
Kubernetes - Replica Sets

Replica Set ensures how many replica of pod should be running. It can be considered as a replacement of replication controller. The key difference between the replica set and the replication controller is, the replication controller only supports equality-based selector whereas the replica set supports set-based selector.
apiVersion: extensions/v1beta1 --------------------->1
kind: ReplicaSet --------------------------> 2
metadata:
   name: Tomcat-ReplicaSet
spec:
   replicas: 3
   selector:
      matchLables:
         tier: Backend ------------------> 3
      matchExpression:
{ key: tier, operation: In, values: [Backend]} --------------> 4
template:
   metadata:
      lables:
         app: Tomcat-ReplicaSet
         tier: Backend
      labels:
         app: App
         component: neo4j
   spec:
      containers:
      - name: Tomcat
      image: tomcat: 8.0
      ports:
      - containerPort: 7474

apiVersion: extensions/v1beta1 → In the above code, the API version is the advanced beta version of Kubernetes which supports the concept of replica set.
apiVersion: extensions/v1beta1 → In the above code, the API version is the advanced beta version of Kubernetes which supports the concept of replica set.
kind: ReplicaSet → We have defined the kind as the replica set which helps kubectl to understand that the file is used to create a replica set.
kind: ReplicaSet → We have defined the kind as the replica set which helps kubectl to understand that the file is used to create a replica set.
tier: Backend → We have defined the label tier as backend which creates a matching selector.
tier: Backend → We have defined the label tier as backend which creates a matching selector.
{key: tier, operation: In, values: [Backend]} → This will help matchExpression to understand the matching condition we have defined and in the operation which is used by matchlabel to find details.
{key: tier, operation: In, values: [Backend]} → This will help matchExpression to understand the matching condition we have defined and in the operation which is used by matchlabel to find details.
Run the above file using kubectl and create the backend replica set with the provided definition in the yaml file.

    41 Lectures 
     5 hours 

 AR Shankar

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    18 Lectures 
     1.5 hours 

 Nigel Poulton

    25 Lectures 
     1.5 hours 

 Pranjal Srivastava

    18 Lectures 
     1 hours 

 Pranjal Srivastava

    26 Lectures 
     1.5 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How to replace the last occurrence of an expression in a string in Python?

This problem can be solved by reversing the string, reversing the string to be replaced,replacing the string with reverse of string to be replaced with and finally reversing the string to get the result. 
You can reverse strings by simple slicing notation - [::-1]. To replace the string you can use str.replace(old, new, count). For example,
 def rreplace(s, old, new):
    return (s[::-1].replace(old[::-1],new[::-1], 1))[::-1]
 rreplace('Helloworld, hello world, hello world', 'hello', 'hi')
 This will give the output:
'Hello world,hello world, hi world'
Another method by which you can do this is to reverse split the string once on the old string and join the list with the new string. For example,
 def rreplace(s, old, new):
    li = s.rsplit(old, 1) #Split only once
    return new.join(li)
 rreplace('Helloworld, hello world, hello world', 'hello', 'hi')
 This will give the output:
'Hello world, hello world, hi world'
C# Round-trip ("R") Format Specifier

This round-trip ("R") format specifier is supported for the Single, Double, and BigInteger types.
It ensures that a numeric value converted to a string is parsed back into the same numeric value.
Let us see an example −
Firstly, we have a double variable.
double doubleVal = 0.91234582637;
Now, use the ToString() method: and set the Round-trip format specifier.
doubleVal.ToString("R", CultureInfo.InvariantCulture);
Let us see the complete example −
 Live Demo
using System;
using System.Numerics;
using System.Globalization;
class Demo {
   static void Main() {
      double doubleVal = 0.91234582637;
      string str = doubleVal.ToString("R", CultureInfo.InvariantCulture);
      double resRound = double.Parse(str, CultureInfo.InvariantCulture);
      // round-trip Double with 'R'
      Console.WriteLine(doubleVal.Equals(resRound));
   }
}
True
DAX Aggregation - GENERATE function

Returns a table with the Cartesian product between each row in table1 and the table that results from evaluating table2 in the context of the current row from table1.
GENERATE (<table1>, <table2>)

table1
Table or a DAX expression that returns a table.
table2
Table or a DAX expression that returns a table.
A table that can be passed as a parameter to a DAX function.
If the evaluation of table2 for the current row in table1 returns an empty table, then the result table will not contain the current row from table1. This is different than GENERATEALL () where the current row from table1 will be included in the results, and columns corresponding to table2 will have null values for that row.
If the evaluation of table2 for the current row in table1 returns an empty table, then the result table will not contain the current row from table1. This is different than GENERATEALL () where the current row from table1 will be included in the results, and columns corresponding to table2 will have null values for that row.
All column names from table1 and table2 must be different or an error is returned.
All column names from table1 and table2 must be different or an error is returned.
= GENERATE ( 
   SUMMARIZE(Salesperson,Salesperson[Salesperson]),
      SUMMARIZE(SalesTarget,SalesTarget[SalesTarget],
      "MaxTarget",MAX(Sales Target[SalesTarget]))
)

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Digit sum upto a number of digits of a number in JavaScript

We are required to write a JavaScript function that takes in two numbers, let’s say m and n as arguments.
n will always be smaller than or equal to the number of digits present in m. The function should calculate and return the sum of first n digits of m.
For example −
If the input numbers are −
const m = 5465767;
const n = 4;
Then the output should be −
const output = 20;
because 5 + 4 + 6 + 5 = 20
Following is the code −
const m = 5465767;
const n = 4;
const digitSumUpto = (m, n) => {
   if(n > String(m).length){
      return 0;
   };
   let sum = 0;
   for(let i = 0; i < n; i++){
      const el = +String(m)[i];
      sum += el;
   };
   return sum;
};
console.log(digitSumUpto(m, n));
Following is the console output −
20