code-rag-bench/online-tutorials huggingface dataset:
GATE | GATE-CS-2003 | Question 84

02 Dec, 2021
Host A is sending data to host B over a full duplex link. A and B are using the sliding window protocol for flow control. The send and receive window sizes are 5 packets each. Data packets (sent only from A to B) are all 1000 bytes long and the transmission time for such a packet is 50 μs. Acknowledgement packets (sent only from B to A) are very small and require negligible transmission time. The propagation delay over the link is 200 us. What is the maximum achievable throughput in this communication?(A) A(B) B(C) C(D) DAnswer: (B)Explanation: Network throughput,
≈ Window size / roundtrip time 
Roundtrip time,
= 2 × Packet delivery time + processing delay
= Transmission delay + 2 * propagation delay 
= 50 microsec + 2 * 200 microsec
= 450 microsec 
Now, Throughput
= ((5*1000*bytes)/450microsec) 
= 11.1111 * 106 bytes per second 
So, option (B) is correct.Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
Python Extract specific keys from dictionary?

Dictionaries are most extensively used data structures in python. They contain data in form of keys and values. In this example we will see how to get the items form a dictionary specific to a given set of keys.
In this approach we simply loop through the dictionary using a for loop with in operator. But along with the in operator we also mention the values of the keys when referring to the dictionary keys.
dictA = {'Sun': '2 PM', "Tue": '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'}

# Given dictionary
print("Given dictionary : ",dictA)

res = {key: dictA[key] for key in dictA.keys()
& {'Fri', 'Sun'}}

# Result
print("Dictionary with given keys is : ",res)
Running the above code gives us the following result −
Given dictionary : {'Sun': '2 PM', 'Tue': '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'}
Dictionary with given keys is : {'Fri': '9 PM', 'Sun': '2 PM'}
In this approach we choose the required keys of the dictionary while passing on the keys to the dict() function. Alogn with using a for loop.
 Live Demo
dictA = {'Sun': '2 PM', "Tue": '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'}

# Given dictionary
print("Given dictionary : ",dictA)

res = dict((k, dictA[k]) for k in ['Fri', 'Wed']
if k in dictA)

# Result
print("Dictionary with given keys is : ",res)
Running the above code gives us the following result −
Given dictionary : {'Sun': '2 PM', 'Tue': '5 PM', 'Wed': '3 PM', 'Fri': '9 PM'}
Dictionary with given keys is : {'Fri': '9 PM', 'Wed': '3 PM'}
Java Examples - Check Date Format

How to check check whether date is in proper format or not?
Following example demonstrates how to check whether the date is in a proper format or not using matches method of String class.
public class Main {
   public static void main(String[] argv) {
      boolean isDate = false;
      String date1 = "8-05-1988";
      String date2 = "08/04/1987";
      String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";
      
      isDate = date1.matches(datePattern);
      System.out.println("Date :"+ date1+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate);
      
      isDate = date2.matches(datePattern);
      System.out.println("Date :"+ date2+": matches with the this date Pattern:"+datePattern+"Ans:"+isDate);
   }
}
The above code sample will produce the following result.
Date :8-05-1988: matches with the this date Pattern: \d{1,2}-\d{1,2}-\d{4}Ans:true
Date :08/04/1987: matches with the this date Pattern: \d{1,2}-\d{1,2}-\d{4}Ans:false

The following is an example to check check whether date is in proper format or not.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String args[]) {
      List dates = new ArrayList();
      dates.add("25/12/1990");
      dates.add("25/12/1990");
      dates.add("12/12/90");
      dates.add("05/02/1990");
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      Pattern pattern = Pattern.compile(regex);
      
      for(Object date : dates) { 
         Matcher matcher = pattern.matcher((CharSequence) date);
         System.out.println(date +" : "+ matcher.matches());
      }
   }
}
The above code sample will produce the following result.
25/12/1990 : false
25/12/1990 : false
12/12/90 : false
05/02/1990 : true
How to create a canvas polygon using Fabric.js ?

19 May, 2020
In this article, we are going to see how to create a canvas polygon using FabricJS. The canvas means polygon is movable and can be stretched according to requirement. Further, the polygon can be customized when it comes to the initial fill color and its coordinates.
Approach: To make it possible we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain our polygon. After this, we will initialize instances of Canvas and Polygon provided by FabricJS and render the Polygon instance on the Canvas instance as given in the example below.
Syntax:
 fabric.Polygon(points, options); 
Parameters: This function accepts two parameters as mentioned above and described below:
points: It specifies the starting and ending coordinates for all the points of the polygon.
options: It specifies the additional options to be applied.
Program: This example uses FabricJS to create simple editable canvas polygon.
<!DOCTYPE html><html>  <head>    <title>        How to create a canvas polygon using Fabric.js?    </title>      <!-- Loading the FabricJS library -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">    </script></head>  <body>    <canvas id="canvas"             width="600"             height="200"             style="border:1px solid #000000;">    </canvas>      <script>          // Initiate a Canvas instance        var canvas = new fabric.Canvas("canvas");          // Initiate a polygon instance        var polygon = new fabric.Polygon([        { x: 200, y: 10 },        { x: 250, y: 50 },        { x: 250, y: 180},        { x: 150, y: 180},        { x: 150, y: 50 }], {            fill: 'green'        });          // Render the polygon in canvas        canvas.add(polygon);    </script></body>  </html>
Output:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | Append suffix/prefix to strings in list

27 Sep, 2019
Sometimes, while working with Python, we can a problem in which we need to pad strings in lists at trailing or leading position. This kind of problem is quite common and can occur in day-day programming or web development. Let’s discuss a way in which this task can be performed.
Method : Using + operator + list comprehension
In this task, we just append the string at rear or front position using + operator and list comprehension is used to iterate through all the elements.
# Python3 code to demonstrate working of# Append suffix / prefix to strings in list# Using list comprehension + "+" operator  # initializing listtest_list = ['a', 'b', 'c', 'd']  # printing listprint("The original list : " + str(test_list))  # initializing append_strappend_str = 'gfg'  # Append suffix / prefix to strings in listpre_res = [append_str + sub for sub in test_list]suf_res = [sub + append_str for sub in test_list]  # Printing resultprint("list after prefix addition : " + str(pre_res))print("list after suffix addition : " + str(suf_res))
 
The original list : ['a', 'b', 'c', 'd']
list after prefix addition : ['gfga', 'gfgb', 'gfgc', 'gfgd']
list after suffix addition : ['agfg', 'bgfg', 'cgfg', 'dgfg']

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 | Convert string dictionary to dictionary
CSS | translateY() function

07 Aug, 2019
The translateY() function is an inbuilt function which is used to reposition the element along the vertical axis.
Syntax:
translateY( t )
Parameters: This function accepts the single parameter t which holds the length of translation corresponding to the y-axis.
Below examples illustrate the translateY() function in CSS:
Example 1:
<!DOCTYPE html><html>  <head>    <title>      CSS translateY() function  </title>    <style>        body {            text-align: center;        }                  h1 {            color: green;        }                  .translateY_image {            transform: translateY(100px);        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>CSS translateY() function</h2>      <h4>Original Image</h4>    <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"          alt="GeeksforGeeks logo">    <br>      <h4>Translated image</h4>    <img class="translateY_image"         src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"         alt="GeeksforGeeks logo"></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <title>      CSS translateY() function  </title>    <style>        body {            text-align: center;        }                  h1 {            color: green;        }                  .GFG {            font-size: 35px;            font-weight: bold;            color: green;        }                  .geeks {            transform: translateY(100px);        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>CSS translateY() function</h2>      <h4>Original Element</h4>    <div class="GFG">      Welcome to GeeksforGeeks  </div>      <h4>Translated Element</h4>    <div class="GFG geeks">      Welcome to GeeksforGeeks  </div></body>  </html>
Output:
Supported Browsers: The browsers supported by translateY() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Integer reverse() Method In Java

07 Jul, 2018
The java.lang.Integer.reverse() is an inbuilt method in Java and is used to return the reverse order of the bits in the two’s complement binary representation of the specified int value.
Syntax:
public static int reverse(int a)
Parameters: The parameter a is an integer value whose bits are to be reversed.
Return Value: The method returns the value which is obtained by reversing the order of the bits in the specified int value.
Examples:
Input: 86
Output: 1778384896
Explanation:
Consider an integer a = 86
Binary Representation = 1010110
The number of one bit = 4 
After reversing it is = 1778384896

Input: 168
Output: 352321536

Below programs illustrate the java.lang.Integer.reverse() method:Program 1: For a positive number.
// Java program to illustrate the// Java.lang.Integer.reverse() methodimport java.lang.*;  public class geeks {      public static void main(String[] args)    {          int a = 168;        System.out.println("Number = " + a);          // It returns the value obtained by reversing order of the bits        System.out.println("By reversing we get = " + Integer.reverse(a));    }}
Number = 168
By reversing we get = 352321536

Program 2: For a Negative number.
// Java program to illustrate the// Java.lang.Integer.reverse() methodimport java.lang.*;  public class geeks {      public static void main(String[] args)    {          int a = -72;        System.out.println("Number = " + a);          // It returns the value obtained by reversing order of the bits        System.out.println("By reversing we get = " + Integer.reverse(a));    }}
Number = -72
By reversing we get = 503316479

Program 3: For a decimal value and string.Note: It throws an error message when a decimal value or string is passed as an argument.
// Java program to illustrate the// Java.lang.Integer.reverse() methodimport java.lang.*;  public class geeks {      public static void main(String[] args)    {          int a = 37.9;        System.out.println("Number = " + a);          // It returns the value obtained by reversing order of the bits in        // the specified int value        System.out.println("By reversing we get = " + Integer.reverse(a));        a = "21";        System.out.println("Number = " + a);          // It returns the value obtained by reversing order of the bits in        // the specified int value        System.out.println("By reversing we get = " + Integer.reverse(a));    }}
prog.java:9: error: incompatible types: possible lossy conversion from double to int
    int a = 37.9;
            ^
prog.java:17: error: incompatible types: String cannot be converted to int
     a = "21";
         ^
2 errors

Java-Functions
Java-Integer
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Abstraction in Java
HashSet in Java
Python | sympy.doit() method

19 Jul, 2019
Using the doit() method in simpy module, we can evaluate objects that are not evaluated by default like limits, integrals, sums and products. Note that all objects of this kind will be evaluated recursively.
Syntax : sympy.doit(x)

Return : evaluated object 
Code #1:
With the help of below examples, we can clearly understand that using sympy.doit() method we can evaluate objects that are not evaluated by default.
# importing sympy libraryfrom sympy import * from sympy.abc import x  # calling doit() method on expressiongeek = (2 * Integral(x, x)).doit()  print(geek)
Output:
x**2
 Code #2:
# importing sympy libraryfrom sympy import *  # taking symbolsa, b = symbols('a b')  # calling doit() method on expressiongeek = (3 * a + b * log(a) + log(b) + log(a)*log(1 / b)).doit()print(geek)
Output:
3*a + b*log(a) + log(a)*log(1/b) + log(b)
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Introduction To PYTHON
Python OOPs Concepts
Python Classes and Objects
Python | os.path.join() method
Python - Pytorch randn() method
How to drop one or multiple columns in Pandas Dataframe
Python - Pandas dataframe.append()
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to Set X-Axis Values in Matplotlib in Python?

22 Dec, 2021
In this article, we will be looking at the approach to set x-axis values in matplotlib in a python programming language.
The xticks() function in pyplot module of the Matplotlib library is used to set x-axis values.
Syntax:
matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
xticks() function accepts the following parameters:
List of xticks locations.
Optional
Passing an empty list will remove all the xticks.
List of labels to palace at given ticks location.
Optional
Returns: xticks() function returns following values:
locs: List of xticks location.
labels: List of xlabel text location.
Example #1 :
In this example, we will be setting up the X-Axis Values in Matplotlib using the xtick() function in the python programming language.
Python3
# Python program to set x-axis values in matplotlib import matplotlib.pyplot as plt # x-axis and y-axis values for plottingx = [1, 2, 3, 4, 5, 6]y = [3, 1, 4, 5, 3, 6] # labels for x-asixlabels = ['A', 'B', 'C', 'D', 'E', 'F'] # Plotting x-axis and y-axisplt.plot(x, y) # naming of x-axis and y-axisplt.xlabel("X-Axis")plt.ylabel("Y-Axis") # naming the title of the plotplt.title("Set X-Axis Values in Matplotlib") # setting x-axis valuesplt.xticks(x, labels) plt.show()
Output:
Example #2:
In this example, we will use the rotation argument to accept rotation value in degree and it will rotate labels in the clockwise direction by specified degree.
Python3
# Python program to set x-axis values in matplotlib import matplotlib.pyplot as plt # x-axis and y-axis values for plottingx = [1, 2, 3, 4, 5, 6]y = [3, 1, 4, 5, 3, 6] # labels for x-asixlabels = ['Label1', 'Label2', 'Label3', 'Label4', 'Label5', 'Label6'] # Plotting x-axis and y-axisplt.plot(x, y) # naming of x-axis and y-axisplt.xlabel("X-Axis")plt.ylabel("Y-Axis") # naming the title of the plotplt.title("Set X-Axis Values in Matplotlib") # setting x-axis values and specifying rotation# for the labels in degreesplt.xticks(x, labels, rotation=45) plt.show()
Output:
simranarora5sos
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.getcwd() method

25 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.os.getcwd() method tells us the location of current working directory (CWD).
Syntax: os.getcwd()
Parameter: No parameter is required.
Return Value: This method returns a string which represents the current working directory.
Example #1 :
Using os.getcwd() method to get current working directory
# Python program to explain os.getcwd() method         # importing os module import os     # Get the current working # directory (CWD) cwd = os.getcwd()     # Print the current working  # directory (CWD) print("Current working directory:", cwd) 
Current working directory: C:\Users\Rajnish\AppData\Local\Programs\Python\Python37

Example #2 :Using os.getcwd() method to get current working directory of GeeksforGeeks which is root
# Python program to explain os.getcwd() method         # importing os module import os     # Get the current working # directory (CWD) cwd = os.getcwd()     # Print the current working  # directory (CWD) # which is root in this caseprint("Current working directory:", cwd) 
Current working directory: /

python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
How to Remove the Password from a Zip File?

03 Jul, 2022
ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together. Some ZIP files are password protected to secure the files from outsiders by disabling their access to the files. But, there are multiple methods to crack a password protected zip file to access its content.
Cracking of passwords requires a lot of your time depending upon the length and complexity of the password when using the Brute-force method, which we are using for the current tutorial.
Follow the steps given below to remove password from a ZIP file:
Step 1: Download the free zip password recovery tool for windows from here.
This tool has a free version and a paid version as well. The free version allows only Brute-force method to work with while the paid version allows masking and dictionary method too.
Step 2: Install and launch the recovery tool.
Step 3: Select the password-protected zip file using the browse option in the top left part of the user interface.
For demonstration purpose, we have created a password protected zip file named “testf.zip”
Step 4: Select the types of characters from the list provided below browse option.
We have set an easy password containing only numeric characters of length 5 for demo. For practical purpose, check all the boxes except the “space” because space is generally not used in passwords.
Step 5: Set the minimum length of the password in the top right part of the user interface.
Step 6: Click on the start button at the top and wait for the process to complete.
You can keep track of all the process happening from bottom right of user interface.
Step 7: Once the process is complete, a dialog box pops up showing you the cracked password and other options to manipulate the file.
As you can see we have the password cracked and yes that is the password that was set while creating the zip file. Now you can perform the operation available on screen.
This is the easiest but most time consuming way to crack passwords, but it does work.
Picked
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
epoll_wait() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
epoll_wait - wait for an I/O event on an epoll file descriptor
#include <sys/epoll.h> 

int epoll_wait(int epfd, struct epoll_event * events, 
               int maxevents, int timeout); 


int epoll_wait(int epfd, struct epoll_event * events, 
               int maxevents, int timeout); 

Wait for events on the epoll file descriptor epfd for a maximum time of timeout milliseconds. The memory area pointed to by events will contain the events that will be available for the caller.
Up to maxevents are returned by epoll_wait(2). 
The maxevents parameter must be greater than zero. Specifying a timeout of -1 makes epoll_wait(2) wait indefinitely, while specifying a timeout equal to zero makes
epoll_wait(2) to return immediately even if no events are available (return code equal to zero).
The struct epoll_event is defined as :

    typedef union epoll_data {
        void *ptr;
        int fd;
        __uint32_t u32;
        __uint64_t u64;
    } epoll_data_t;

    struct epoll_event {
        __uint32_t events;      /* Epoll events */
        epoll_data_t data;      /* User data variable */
    };



    typedef union epoll_data {
        void *ptr;
        int fd;
        __uint32_t u32;
        __uint64_t u64;
    } epoll_data_t;


    struct epoll_event {
        __uint32_t events;      /* Epoll events */
        epoll_data_t data;      /* User data variable */
    };



The
data of each returned structure will contain the same data the user set with a epoll_ctl(2) (EPOLL_CTL_ADD,EPOLL_CTL_MOD) while the events member will contain the returned event bit field.
When successful, epoll_wait(2) returns the number of file descriptors ready for the requested I/O, or zero if no file descriptor became ready during the requested
timeout milliseconds.  When an error occurs, epoll_wait(2) returns -1 and errno is set appropriately.
epoll_wait(2) is a new API introduced in Linux kernel 2.5.44. The interface should be finalized by Linux kernel 2.5.66.
Python | Pandas Series.value_counts()

29 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.value_counts() function return a Series containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.
Syntax: Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)
Parameter :normalize : If True then the object returned will contain the relative frequencies of the unique values.sort : Sort by values.ascending : Sort in ascending order.bins : Rather than count values, group them into half-open bins, a convenience for pd.cut, only works with numeric data.dropna : Don’t include counts of NaN.
Returns : counts : Series
Example #1: Use Series.value_counts() function to find the unique value counts of each element in the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Chicago', 'Lisbon'])  # Print the seriesprint(sr)
Output :
Now we will use Series.value_counts() function to find the values counts of each unique value in the given Series object.
# find the value countssr.value_counts()
Output :
As we can see in the output, the Series.value_counts() function has returned the value counts of each unique value in the given Series object.
Example #2: Use Series.value_counts() function to find the unique value counts of each element in the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, 214, 325, 88, None, 325, None, 325, 100])  # Print the seriesprint(sr)
Output :
Now we will use Series.value_counts() function to find the values counts of each unique value in the given Series object.
# find the value countssr.value_counts()
Output :As we can see in the output, the Series.value_counts() function has returned the value counts of each unique value in the given Series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to easily insert datetime in MySQL?

You can easily insert DateTime with the MySQL command line. Following is the syntax −
insert into yourTableName values(‘yourDateTimeValue’);
Let us first create a table −
mysql> create table DemoTable
(
   DateOfBirth datetime
);
Query OK, 0 rows affected (0.97 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('1998-01-23 12:45:56');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values('2010-12-31 01:15:00');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('2015-04-03 14:00:45');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------------+
| DateOfBirth         |
+---------------------+
| 1998-01-23 12:45:56 |
| 2010-12-31 01:15:00 |
| 2015-04-03 14:00:45 |
+---------------------+
3 rows in set (0.00 sec)
Visualizing Relationship between variables with scatter plots in Seaborn

29 Aug, 2020
To understand how variables in a dataset are related to one another and how that relationship is dependent on other variables, we perform statistical analysis. This Statistical analysis helps to visualize the trends and identify various patterns in the dataset. One of the functions which can be used to get the relationship between two variables in Seaborn is relplot().
Relplot() combines FacetGrid with either of the two axes-level functions scatterplot() and lineplot(). Scatterplot is default kind of relplot(). Using this we can visualize joint distribution of two variables through a cloud of points. We can draw scatterplot in seaborn using various ways. The most common one is when both the variables are numeric.
Example: Let’s take an example of a dataset that consists a data of CO2 emissions of different vehicles. To get the dataset click here.
# import librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns  # set grid stylesns.set(style ="darkgrid")  # import datasetdataset = pd.read_csv('FuelConsumption.csv')
Let’s plot the basic scatterplot for visualizing the relation between the target variable “CO2EMISSIOnS” and “ENGINE SIZE”
sns.relplot(x ="ENGINESIZE", y ="CO2EMISSIONS",            data = dataset);
Output:
We can add visualize one more variable by adding another dimension to the plot. This can be done by using “hue”, which colors the points of the third variable, thus adding a meaning to it.
sns.relplot(x ="ENGINESIZE", y ="CO2EMISSIONS",             hue ="FUELTYPE", data = dataset);
Output:
To highlight the different classes, we can add marker styles
sns.relplot(x ="ENGINESIZE", y ="CO2EMISSIONS",            hue ="FUELTYPE", style ="FUELTYPE",             data = dataset);
Output:
In the previous example, hue semantic was for a categorical variable, so it had a default qualitative palette. But if we use a numerical variable instead of categorical, then the default palette used is sequential, which can be modified too.
sns.relplot(x ="ENGINESIZE", y ="CO2EMISSIONS",            hue ="CYLINDERS", data = dataset);
Output:
We can also change the size of points for the third variable.
sns.relplot(x ="ENGINESIZE", y ="CO2EMISSIONS",             size ="CYLINDERS", data = dataset);
Output:
Data Visualization
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
JavaScript Map() Constructor

20 May, 2021
The Map() constructor is used to create Map objects in JavaScript. The map is a data structure that stores elements as a key, value pair.
Syntax:
new Map()
new Map(iterable)
Parameters:
iterable: An iterable object used for iterating through elements, stored as a key, value pair.
Return value: A new Map object returns after the initialization of the map constructor.
 
Example 1:
Javascript
<script>  // map1 contains // 1 => 10// 2 => 20// 3 => 30// 4 => 40var map1 = new Map([    [1 , 10], [2 , 20] ,    [3, 30],[4, 40]]);  console.log("Map1: ");console.log(map1);</script>
Output:
Map1: 
Map(4) { 1 => 10, 2 => 20, 3 => 30, 4 => 40 }
Example 2:
Javascript
<script>  // map2 contains // firstname => Ram// lastname => Prasad// website => geeksforgeeks var map2 = new Map([    ["firstname" ,"Ram"],     ["lastname", "Prasad"],     ["website", "geeksforgeeks"]]);    console.log("Map2: ");console.log(map2);</script>
Output:
Map2:
Map(3) {
 'firstname' => 'Ram',
 'lastname' => 'Prasad',
 'website' => 'geeksforgeeks'
}
Example 3:
Javascript
<script>  // Map contains nested arrayvar map3 = new Map([    ["whole numbers", [1 ,2 ,3 ,4]],    ["Decimal numbers" , [1.1, 1.2, 1.3, 1.4]],    ["negative numbers", [-1, -2, -3, -4]]]);    console.log("Map3: ");console.log(map3);</script>
Output:
Map3:
Map(3) {
 'whole numbers' => [ 1, 2, 3, 4],
 'Decimal numbers' => [ 1.1, 1.2, 1.3, 1.4],
 'negative numbers' => [ -1, -2, -3, -4]
}
javascript-map
JavaScript-Methods
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Difference between -webkit-box-shadow & box-shadow in CSS

26 Apr, 2021
In this article, we will find difference between ‘webkit-box-shadow’ & ‘box-shadow’ in CSS.
Webkit-box-shadow: The webkit-box-shadow property in CSS is used to apply a box-shadow. The webkit-box-shadow is a browser-specific implementation for WebKit browsers like Google Chrome and Safari.
Syntax:webkit-box-shadow: h-offset v-offset blur;
webkit-box-shadow: h-offset v-offset blur;
Advantage: If we use -webkit-box-shadow the old versions of browsers support it.
Box-shadow: The box-shadow property in CSS is used to apply a box-shadow. The box-shadow is the CSS standard implementation.
Syntax: box-shadow: h-offset v-offset blur;
box-shadow: h-offset v-offset blur;
Advantage: If we use box-shadow latest versions of browsers support it.
There are some differences between box-shadow and -webkit-box-shadow properties which are following:
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        .gfg1{            color: green;            cursor: zoom-in;            border: solid 2px red;            margin: 10% 30%;            width: 50%;            box-shadow: 5px 10px 18px red;            -webkit-box-shadow: 5px 10px 18px red;        }    </style></head>  <body>    <div class="gfg1">        <h1>GeeksforGeeks</h1>        <p>box-shadow</p>      </div></body>  </html>
Output:
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python String strip() Method

Python string  method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
Following is the syntax for strip() method −
str.strip([chars]);

chars − The characters to be removed from beginning or end of the string.
chars − The characters to be removed from beginning or end of the string.
This method returns a copy of the string in which all chars have been stripped from the beginning and the end of the string.
The following example shows the usage of strip() method.
#!/usr/bin/python

str = "0000000this is string example....wow!!!0000000";
print str.strip( '0' )
When we run above program, it produces following result −
this is string example....wow!!!
L2 Normalization

It may be defined as the normalization technique that modifies the dataset values in a way that in each row the sum of the squares will always be up to 1. It is also called least squares.
In this example, we use L2 Normalization technique to normalize the data of Pima Indians Diabetes dataset which we used earlier. First, the CSV data will be loaded (as done in previous chapters) and then with the help of Normalizer class it will be normalized.
The first few lines of following script are same as we have written in previous chapters while loading CSV data.
from pandas import read_csv
from numpy import set_printoptions
from sklearn.preprocessing import Normalizer
path = r'C:\pima-indians-diabetes.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = read_csv (path, names=names)
array = dataframe.values
Now, we can use Normalizer class with L1 to normalize the data.
Data_normalizer = Normalizer(norm='l2').fit(array)
Data_normalized = Data_normalizer.transform(array)

We can also summarize the data for output as per our choice. Here, we are setting the precision to 2 and showing the first 3 rows in the output.
set_printoptions(precision=2)
print ("\nNormalized data:\n", Data_normalized [0:3])

Normalized data:
[[0.03 0.83 0.4  0.2  0. 0.19 0. 0.28 0.01]
[0.01  0.72 0.56 0.24 0. 0.22 0. 0.26 0. ]
[0.04  0.92 0.32 0.   0. 0.12 0. 0.16 0.01]]
How to Change Fonts in matplotlib?

13 Jan, 2021
Prerequisites:  Matplotlib 
In this article, we will see how can we can change the font family of our graph using matplotlib. A variety of fonts are in fact supported by matplotlib, alone has to do in order to implement is pass the name as value to fontname parameter.
Approach:
Import required library.
Create data
Set changed font 
Normally plot the data
Display plot
Example 1: Change the font just for the axis labels.
Python3
from scipy import signalimport matplotlib.pyplot as plotimport numpy as np# %matplotlib inline  # Plot the square wavet = np.linspace(0, 1, 1000, endpoint=True)plot.plot(t, signal.square(2 * np.pi * 5 * t))  # Change the x, y axis label to "Brush Script MT" font style.plot.xlabel("Time (Seconds)", fontname="Brush Script MT", fontsize=18)plot.ylabel("Amplitude", fontname="Brush Script MT", fontsize=18)  plot.show()
Output:
Example 2: Change the font just for the title.
Python3
import matplotlib.pyplot as plot  x = [1, 2, 3, 4, 5, 6]y = [0, 2, 4, 6, 8, 10]  # plotting a plotplot.scatter(x, y)  # Set the title to 'Franklin Gothic Medium' style.plot.title("Line Graph - Geeksforgeeks",           fontname='Franklin Gothic Medium', fontsize=18)  plot.show()
Output:
Example 3: Change the font just for the title and axis labels.
Python3
import matplotlib.pyplot as plot  x = [1, 2, 3, 4, 5, 6]y = [0, 2, 4, 6, 8, 10]  # plotting a plotplot.plot(x, y)    # Change the x, y axis label to 'Gabriola' style.plot.xlabel("Years", fontname="Gabriola", fontsize=18)plot.ylabel("Population (million)", fontname="Gabriola", fontsize=18)  # Set the title to 'Franklin Gothic Medium' style.plot.title("Line Graph - Geeksforgeeks",           fontname='Franklin Gothic Medium', fontsize=18)  plot.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to get the azure resources from the resource group using PowerShell?

To get the available resources from the resource groups using PowerShell, we need to use the Get-AZResource command. Suppose we have the resource group name AnsibleTestRG and we need to retrieve the resources from the resource group, then we will use the below command.
Get-AzResource -ResourceGroupName AnsibleTestRG
To filter the output,
Get-AzResource -ResourceGroupName AnsibleTestRG | Select Name, ResourceType, Location
If there are multiple resource groups in the particular subscription, we can use the below commands to export the resources from the resource group to the CSV file.
$ErrorActionPreference = "Stop"
try {
    Connect-AZAccount
    Set-AzContext -SubscriptionName 'Your Subscription Name'
    $rgs = Get-AzResourceGroup

    foreach ($rg in $rgs.ResourceGroupName) {
        Write-Output "Checking Resource Group: $rg"
        Get-AzResource -ResourceGroupName $rg | Select Name, ResourceGroupName, Type, Location | Export-Csv .\AzureResources.csv -Append -Force -NoTypeInformation
    }
}
catch {
    Write-Host "$($_.Exception.Message)" -BackgroundColor DarkRed
}
How I can dump a Python tuple in JSON format?

JSON stands for Javascript object notation. It is a lightweight, language-independent data interchange format. Python library has json module that provides functions for json encoding and decoding.
The dumps() function converts a Python object to JSON format
>>> T1=(12, "Ravi", "B.Com FY", 78.50)
>>> import json
>>> str1=json.dumps(T1)
>>> str1
'[12, "Ravi", "B.Com FY", 78.5]'
Can you take a screenshot of the page using HTML5 Canvas?

Html2Canvas is a JavaScript library that can take screenshot of the whole web page or specific part. It doesn’t take the screenshot but creates the view based on the page information.
Below given is an example code. Here, html2canvas.js script is included at the <head>. The html2canvas() method is called. Returns the base64 value, which eventually creates image source or an image file.
<!DOCTYPE html>
<html>
   <head>
      <script src="html2canvas-master/dist/html2canvas.js"></script>
   </head>
   <body>
      <h1>Take screenshot</h1>
      <div class="container" id='container' >
         <imgsrc='images/one.jpg' width='50' height='50'>
         <imgsrc='images/two.jpg' width='50' height='50'>
      </div>
      <input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/>
      <script>
         function screenshot(){
            html2canvas(document.body).then(function(canvas) {
               document.body.appendChild(canvas);
            });
         }
      </script>
   </body>
</html>
How can we implement an editable JLabel in Java?


A JLabel class can extend JComponent class and an object of JLabel provides text instructions or information on a GUI.
A JLabel can display a single line of read-only text, an image or both text and image.
The important methods of a JLabel are setText(), setIcon(), setBackground(), setOpaque(), setHorizontalAlignment(), setVerticalAlignment() and etc.
A JLabel can explicitly generate a PropertyChangeListener interface.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
public class JEditableLabel extends JFrame {
   public JEditableLabel() {
      setTitle("JEditableLabel");
      setLayout(new FlowLayout());
      final JLabel label = new JLabel(" Welcome to Tutorials Point");
      final JTextField textfield = new JTextField();
      final CardLayout cl = new CardLayout();
      final JPanel panel = new JPanel(cl);
      panel.add(label, "label component");
      panel.add(textfield, "textfield component");
      add(panel);
      label.addMouseListener(new MouseAdapter() {
         public final void mouseEntered(MouseEvent evt) {
            textfield.setText(label.getText());
            cl.show(panel, "textfield component");
         }
      });
      textfield.addMouseListener(new MouseAdapter() {
         public final void mouseExited(MouseEvent evt) {
            label.setText(textfield.getText());
            cl.show(panel, "label component");
         }
      });
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JEditableLabel();
   }
}
Unity - Text Element

Unity’s inbuilt text UI is a great starting point for learners to get into designing UI, even if it tends to be overshadowed by more powerful and efficient community-built assets.
For our purpose, the vanilla Text element is more than sufficient to get started.
Text being a distinct UI element of its own is primarily due to the dynamism of that element. For example, printing the player’s current score to the screen requires the numeric value of the score to be converted to a string, generally through the .toString() method, before it is displayed.
To insert a Text UI element, go to the Scene Heirarchy, Create → UI → Text.
A new Text element should show up in your Canvas region. If we have a look at its properties, we will see some very useful options.
What is most significant of all, however, is the Text field. You can type out what you want the text box to say in that field, but we want to go a step further than that.
To change the font of the text, you must first import the font file from your computer into Unity, as an Asset. A font does not need to be actively attached to anything in the scene, and it can be directly referenced from the Assets.
The Text element can be accessed through scripting as well; this is where the importance of dynamic UI comes in.
Instead of the console, outputting how many times the button has been pressed, as in the previous chapter; let us actually print it out on the game screen. To do so, we will open up our ButtonBehaviour script from the previous lesson, and make a few changes to it.
using UnityEngine;
using UnityEngine.UI;
public class ButtonBehaviour : MonoBehaviour {
   int n;
   public Text myText;
   public void OnButtonPress(){
      n++;
      myText.text = "Button clicked " + n + " times.";
   }
}
The first change we did was to add a new namespace reference. This reference is used to work with Unity’s UI components, and so we add the using UnityEngine.UI line.
Next, we create a public Text variable, where we can drag and drop our Text UI element onto.
Finally, we access the actual text this UI element contains using myText.text.
If we save our script, we will now see a new slot for the Text UI element in our ButtonManager. Simply drag and drop the gameObject containing that Text element onto the slot, and hit the Play button.

    119 Lectures 
     23.5 hours 

 Raja Biswas

    58 Lectures 
     10 hours 

 Three Millennials

    16 Lectures 
     1 hours 

 Peter Jepson

    23 Lectures 
     2.5 hours 

 Zenva

    21 Lectures 
     2 hours 

 Zenva

    43 Lectures 
     9.5 hours 

 Raja Biswas
 Print
 Add Notes
 Bookmark this page