code-rag-bench/online-tutorials huggingface dataset:
CSS Buttons - Social Buttons Usage

Social Buttons library is a set of CSS Buttons made in pure CSS and are based on Bootstrap and Font Awesome.
To load the bootstrap-social.css library, download the bootstrap-social.css from github and paste the following line in the <head> section of the webpage.
<head>
   <link rel = "stylesheet" href = "bootstrap-social.css">
</head>

Create a button using html anchor tag and add styles btn, btn-block with social specifier btn-social.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
      <link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
      <link rel = "stylesheet" href = "/css_buttons/bootstrap-social.css">
   </head>
   
   <body>
      <a class = "btn btn-block btn-social btn-twitter">
         <span class = "fa fa-twitter"></span>
         Login with Twitter
      </a>
   </body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
      <link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
      <link rel = "stylesheet" href = "/css_buttons/bootstrap-social.css">
   </head>
   
   <body>
      <a class = "btn btn-block btn-lg btn-social btn-twitter">
         <span class = "fa fa-twitter"></span>
         Login with Twitter
      </a>
      <a class = "btn btn-block btn-md btn-social btn-twitter">
         <span class = "fa fa-twitter"></span>
         Login with Twitter
      </a>
      <a class = "btn btn-block btn-sm btn-social btn-twitter">
         <span class = "fa fa-twitter"></span>
         Login with Twitter
      </a>
      <a class = "btn btn-block btn-xs btn-social btn-twitter">
         <span class = "fa fa-twitter"></span>
         Login with Twitter
      </a>
   </body>
</html>
It will produce the following output −
The following example shows how to choose icon only buttons.
<html>
   <head>
      <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
      <link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
      <link rel = "stylesheet" href = "bootstrap-social.css">
   </head>
   
   <body>
      <a class = "btn btn-social-icon btn-twitter">
         <span class = "fa fa-twitter"></span>
      </a>   
   </body> 
</html>
It will produce the following output −

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Convert HTML table into CSV file in python

21 Apr, 2020
CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today’s world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file.
Example: Suppose HTML file looks like,
HTML table can be converted to CSV file using BeautifulSoup and Pandas module of Python. These modules do not comes built-in with Python. To install them type the below command in the terminal.
pip install BeautifulSoup
pip install pandas

Python3 Code for converting the HTML table into CSV file
# Importing the required modules import osimport sysimport pandas as pdfrom bs4 import BeautifulSoup   path = 'html.html'   # empty listdata = []   # for getting the header from# the HTML filelist_header = []soup = BeautifulSoup(open(path),'html.parser')header = soup.find_all("table")[0].find("tr")  for items in header:    try:        list_header.append(items.get_text())    except:        continue  # for getting the data HTML_data = soup.find_all("table")[0].find_all("tr")[1:]  for element in HTML_data:    sub_data = []    for sub_element in element:        try:            sub_data.append(sub_element.get_text())        except:            continue    data.append(sub_data)  # Storing the data into Pandas# DataFrame dataFrame = pd.DataFrame(data = data, columns = list_header)   # Converting Pandas DataFrame# into CSV filedataFrame.to_csv('Geeks.csv')
Output:
python-csv
python-utility
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
Python | Pandas.CategoricalDtype()

10 Mar, 2022
pandas.api.types.CategoricalDtype(categories = None, ordered = None) : This class is useful for specifying the type of Categorical data independent of the values, with categories and orderness.  
Parameters- categories : [index like] Unique categorization of the categories. ordered : [boolean] If false, then the categorical is treated as unordered. Return- Type specification for categorical data
Code:  
Python3
# Python code explaining# numpy.pandas.CategoricalDtype()    # importing librariesimport numpy as npimport pandas as pdfrom pandas.api.types import CategoricalDtype  a = CategoricalDtype(['a', 'b', 'c'], ordered=True)print ("a : ", a)  b = CategoricalDtype(['a', 'b', 'c'])print ("\nb : ", b)  print ("\nTrue / False : ", a == CategoricalDtype(['a', 'b', 'c'],                                                   ordered=False))  c = pd.api.types.CategoricalDtype(categories=["a","b","d","c"], ordered=True)print ("\nType : ", c)
Python3
c1 = pd.Series(['a', 'b', 'a', 'e'], dtype = c)print ("c1 : \n", c1)    c2 = pd.DataFrame({'A': list('abca'), 'B': list('bccd')})  c3 = CategoricalDtype(categories=list('abcd'), ordered=True)  c4 = c2.astype(c3)  print ("\n c4['A'] : \n", c4['A'])
rkbhola5
Python pandas-datatypes
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert an object to string using JavaScript?

23 May, 2019
Below are the methods to convert different objects to string.Method 1: Using the function String()The String() function converts the value of an object to a string.Syntax:
String(object)
Parameter:
JavaScript Object
Example :
<script> var bool_to_s1 = Boolean(0);var bool_to_s2 = Boolean(1);var num_to_s = 1234;    document.write( typeof( bool_to_s1)+"<br>");  document.write( typeof(String( bool_to_s1))+ "<br>");  document.write( typeof( bool_to_s2)+ "<br>");   document.write(typeof(String( bool_to_s2))+ "<br>");   document.write( typeof( num_to_s)+ "<br>");   document.write(typeof(String( num_to_s))+ "<br>"); </script>                    
Output:
boolean
string
boolean
string
number
string
Method 2:Using JSON.stringify()JSON.stringify() converts the javascript object to string which is needed to send data over web server.
Syntax:
 JSON.stringify(obj)
Parameter:
Can be object, array
Example:
<script>var obj_to_str = { name: "GeeksForGeeks", city: "Noida", contact:2488 };var myJSON = JSON.stringify(obj_to_str);document.write(myJSON)</script>
Output:
{"name":"GeeksForGeeks", "city":"Noida", "contact":2488}
More about JSON.stringify()
javascript-object
javascript-string
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
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 ?
How to create texture background using CSS ?

18 Jun, 2020
Introduction: We can use CSS property to texture the background of web page by using an image editor to cut out a portion of the background. Apply CSS background-repeat property to make the small image fill the area where it is used. CSS provides many styling properties of background including coloring the background, background images, etc. Background properties are background-color, background-image, background-position, background-attachment.
Approach of texturing the background: There are some steps for texturing the background using CSS with example and the explanation.
Create a html file using html tags.<html>  <head>    <title>        Texture Background        Using CSS     </title></head><body></body>  </html>
<html>  <head>    <title>        Texture Background        Using CSS     </title></head><body></body>  </html>
Choose the texture color that we want to set in Background. Save the texture color in image format like(.png, .jpg etc)
Suppose we want to set the background of this web page using internal sheet CSS. So write the following code in head section.<style>    body {        background-image: url("BG.jpg");        background-repeat: repeat/no-repeat;        background-size: 1600px 840px:    }</style>
<style>    body {        background-image: url("BG.jpg");        background-repeat: repeat/no-repeat;        background-size: 1600px 840px:    }</style>
Example:
<!DOCTYPE><html>  <head>    <title>        Texture Background using CSS    </title>      <style>        body {            background-image: url("https://contribute.geeksforgeeks.org/wp-content/uploads/backgroundimage-1.png");            background-repeat: no-repeapt;        }    </style></head>  <body>    <h1>        This is our texture        background    </h1></body>  </html>
Explanation: In this code, we are placing the image in the background through background-image:url(“backgroundimage-1.png”); in the form of .jpg. It can be in .png also.Here, we are not repeating the image in the background so, the image shown only one time in the background, background-repeat:no-repeapt; this syntax means image is not repeating. These all commands are written in <style> tag using CSS.Output:
Akanksha_Rai
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Partial Methods in C#

23 Jan, 2019
C# contains a special method is known as a partial method, which contains declaration part in one partial class and definition part in another partial class or may contain both declaration and definition in the same partial class.Basically, partial methods exist in the partial class, or in the struct. A partial method may or may not contain implementation if a partial method doesn’t contain an implementation in any part then the compiler will not create that method in the final class or driver class. A partial method is declared with the help of the partial keyword as shown below.
Syntax:
partial void method_name
{
    // Code
}

Important Points:
The declaration of the partial method must begin with partial modifier.
The partial method may contain ref.
The partial method does not contain out parameters.
It is implicitly private method.
It can be a static method.
Partial method is generic.
It can have only void return type.
A partial method is created only in partial class or in partial struct.
Example: We have a class named as Circle. The functionality of the Circle class is chopped into two different files named as circle1.cs and circle2.cs. These circle1.cs and circle2.cs files contain the partial class of the Circle class and partial method, i.e area. The circle1.cs file contains the declaration of the partial area() method and circle2.cs file contains the implementation of the area method as shown below:
circle1.cs
public partial class Circle {      // This file only contains    // declaration of partial method    partial void area(int p);      public void Display()    {        Console.WriteLine("Example of partial method");    }}
circle2.cs
public partial class Circle {      public void newarea(int a)    {        area(int a);    }      // This is the definition of    // partial method    partial void area(int r)    {        int A = 3.14 * r * r;        Console.WriteLine("Area is : {0}", A);    }}
When we execute the above code, then compiler combines circle1.cs and circle2.cs into a single file, i.e. circle as shown below.
circle
public class Circle {      public void Display()    {        Console.WriteLine("Example of partial method");    }      public void newarea(int a)    {        area(int a);    }      private void area(int r)    {        int A = 3.14 * r * r;        Console.WriteLine("Area is : {0}", A);    }}
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Arrays
C# | Encapsulation
C# | Replace() Method
Python program to count the number of characters in a String - GeeksforGeeks

01 Oct, 2020
Given a String. The task is to return the number of characters in the string.
Examples:
Input : test_str = ‘geeksforgeeks !!$*** best 4 all Geeks 10-0’ Output : 25Explanation : Only alphabets, when counted are 25
Input : test_str = ‘geeksforgeeks !!$*** best for all Geeks 10—0’ Output : 27Explanation : Only alphabets, when counted are 27
Method #1 : Using isalpha() + len()
In this approach, we check for each character to be alphabet using isalpha() and len() is used to get the length of the list of alphabets to get count.
Python3
# Python3 code to demonstrate working of# Alphabets Frequency in String# Using isalpha() + len()  # initializing stringtest_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'  # printing original stringprint("The original string is : " + str(test_str))  # isalpha() to computation of Alphabetsres = len([ele for ele in test_str if ele.isalpha()])  # printing resultprint("Count of Alphabets : " + str(res))
The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0Count of Alphabets : 27
Method #2 : Using ascii_uppercase() + ascii_lowercase() + len()
In this, we perform the task of getting alphabets as a combination of upper and lowercase, using inbuilt functions, len() returns frequency.
Python3
# Python3 code to demonstrate working of# Alphabets Frequency in String# Using ascii_uppercase() + ascii_lowercase() + len()import string  # initializing stringtest_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0'  # printing original stringprint("The original string is : " + str(test_str))  # ascii_lowercase and ascii_uppercase# to check for Alphabetsres = len([ele for ele in test_str if ele in string.ascii_uppercase or ele in string.ascii_lowercase])  # printing resultprint("Count of Alphabets : " + str(res))
The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0Count of Alphabets : 27
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Ruby | Array uniq() function - GeeksforGeeks

06 Dec, 2019
Array#uniq() : uniq() is a Array class method which returns a new array by removing duplicate values in the array.
Syntax: Array.uniq()
Parameter: Array
Return: a new array by removing duplicate values in the array
Example #1 :
# Ruby code for uniq() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, 50, 6]  # uniq method exampleputs "uniq() method form : #{a.uniq()}\n\n"  puts "uniq() method form : #{b.uniq()}\n\n"  puts "uniq() method form : #{c.uniq()}\n\n"
Output :
uniq() method form : [18, 22, 33, nil, 5, 6]

uniq() method form : [1, 4, 88, 9]

uniq() method form : [18, 22, 50, 6]


Example #2 :
# Ruby code for uniq() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayc = ["cat", nil]  # declaring arrayb = ["cow", "gogoog", "dog"]    # uniq method exampleputs "uniq() method form : #{a.uniq()}\n\n"  puts "uniq() method form : #{b.uniq()}\n\n"  puts "uniq() method form : #{c.uniq()}\n\n"
Output :
uniq() method form : ["abc", "nil", "dog"]

uniq() method form : ["cow", "gogoog", "dog"]

uniq() method form : ["cat", nil]


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Numeric round() function
Ruby | Data Types
Ruby | String capitalize() Method
How to set the overflow property to scroll in CSS ? - GeeksforGeeks

03 Jun, 2021
In this article, we will see how to set the overflow property to scroll in CSS. The overflow property is used to control the big content. It tells what to do when an element’s content is too big to fit in the specified area. When the overflow property is set to scroll, the overflow is clipped, but a scrollbar is added to see the rest.
Example 1: 
HTML
<!DOCTYPE html><html>  <head>    <style>        p {            width: 120px;            height: 100px;            border: 1px solid;            overflow: scroll;            color: green;        }    </style></head>  <body>    <h2>GEEKSFORGEEKS</h2>      <p>        The CSS overflow controls big content.        It tells whether to clip content or to        add scroll bars.    </p></body>  </html>
Output: 
 
Example 2: In this example, we have to use the overflow-x property to scroll. The overflow-x property is used when the content is overflown at the left and right edges.
HTML
<!DOCTYPE html><html>  <head>    <style>        p {            color: green;            width: 40px;            border: 1px solid;            overflow-x: scroll;        }    </style></head>  <body>    <h2>GEEKSFORGEEKS</h2>      <p>        The CSS overflow controls big         content. It tells whether to         clip content or to add scroll         bars to show rest of the content.    </p></body>  </html>
Output: 
Example 3: In this example, we have used the overflow-y property to scroll. The overflow-y property is used when the content overflows at the top and bottom edges
HTML
<!DOCTYPE html><html>  <head>    <style>        p {            color: green;            height: 50px;            width: 200px;            border: 1px solid;            overflow-y: scroll;        }    </style></head>  <body>    <h2>GEEKSFORGEEKS</h2>      <p>        The CSS overflow controls big         content. It tells whether to         clip content or to add scroll         bars to show rest of the content.    </p></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.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Modify values of a Data Frame in R Language - transform() Function - GeeksforGeeks

26 May, 2020
transform() function in R Language is used to modify data. It converts the first argument to the data frame.This function is used to transform/modify the data frame in a quick and easy way.
Syntax:transform(data, value)
Parameters:data: Data Frame to be modifiedvalue: new modified value of data
Example 1: Use transform() on variables
# R program to illustrate# transform on variables  # Create example data framedata <- data.frame(x1 = c(1, 2, 3, 4),                               x2 = c(5, 6, 7, 8))   # Apply transform functiondata_ex1 <- transform(data, x1 = x1 + 10)    # Print data      print(data_ex1)                                                                               
Output:
x1= 11, 12, 13, 14.
x2 = 5, 6, 7, 8.
Here in the above code, we have a data framework and we transform it by adding 10(x1 = x1 + 10) to each of the values.The values of x2 will not get changed as we do not apply any transformation to it.
Example 2: Add new variables to data
# R program to illustrate # Adding new variables to data  data <- data.frame(x1 = c(11, 12, 13, 14),                               x2 = c(5, 6, 7, 8))  # Apply transform functiondata_ex2 <- transform(data, x3 = c(1, 3, 3, 4))    print(data_ex2) 
Output:
X1= 11, 12, 13, 14.
X2 = 5, 6, 7, 8.
X3 = 1, 3, 3, 4.

Here in the above code, we are adding a new variable x3 to the previous data.
R-Functions
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
5 Best Languages for Competitive Programming
Introduction of Object Oriented Programming
7 Highest Paying Programming Languages For Freelancers in 2022
R - Matrices
R - Charts and Graphs
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
How to use a DataLoader in PyTorch? - GeeksforGeeks

24 Feb, 2021
Operating with large datasets requires loading them into memory all at once. In most cases, we face a memory outage due to the limited amount of memory available in the system. Also, the programs tend to run slowly due to heavy datasets loaded once. PyTorch offers a solution for parallelizing the data loading process with automatic batching by using DataLoader. Dataloader has been used to parallelize the data loading as this boosts up the speed and saves memory.
The dataloader constructor resides in the torch.utils.data package. It has various parameters among which the only mandatory argument to be passed is the dataset that has to be loaded, and the rest all are optional arguments.
Syntax:
DataLoader(dataset, shuffle=True, sampler=None, batch_size=32)
DataLoaders on Custom Datasets:
To implement dataloaders on a custom dataset we need to override the following two subclass functions: 
The _len_() function: returns the size of the dataset.
The _getitem_() function: returns a sample of the given index from the dataset.
Python3
# importing the required librariesimport torchfrom torch.utils.data import Datasetfrom torch.utils.data import DataLoader  # defining the Dataset classclass data_set(Dataset):    def __init__(self):        numbers = list(range(0, 100, 1))        self.data = numbers      def __len__(self):        return len(self.data)      def __getitem__(self, index):        return self.data[index]    dataset = data_set()  # implementing dataloader on the dataset and printing per batchdataloader = DataLoader(dataset, batch_size=10, shuffle=True)for i, batch in enumerate(dataloader):    print(i, batch)
Output:
DataLoaders on Built-in Datasets:
Python3
# importing the required librariesimport torchfrom torch.utils.data import Datasetfrom torch.utils.data import DataLoaderimport seaborn as snsfrom torch.utils.data import TensorDataset  # defining the dataset consisting of # two columns from iris datasetiris = sns.load_dataset('iris')petal_length = torch.tensor(iris['petal_length'])petal_width = torch.tensor(iris['petal_width'])dataset = TensorDataset(petal_length, petal_width)  # implementing dataloader on the dataset # and printing per batchdataloader = DataLoader(dataset,                         batch_size=5,                         shuffle=True)  for i in dataloader:    print(i)
Output:
Picked
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Filter a list based on the given list of strings - GeeksforGeeks

25 Jun, 2019
Given a List, the task is to filter elements from list based on another list of strings. These type of problems are quite common while scraping websites.
Examples:
Input:
List_string1 = ['key', 'keys', 'keyword', 'keychain', 'keynote']
List_string2 = ['home/key/1.pdf',
         'home/keys/2.pdf', 
         'home/keyword/3.pdf', 
         'home/keychain/4.pdf',
         'home/Desktop/5.pdf', 
         'home/keynote/6.pdf']
Output:
['home/Desktop/5.pdf']

Explanation: We filter only those element from 
list_string2 that do not have string in list_string1

Below are some ways to achieve the above task.
Method #1: Using Iteration
# Python code to  filter element from list # based on another list of string.  # List InitializationInput = ['key', 'keys', 'keyword', 'keychain', 'keynote']Input_string = ['home/key/1.pdf',         'home/keys/2.pdf',          'home/keyword/3.pdf',          'home/keychain/4.pdf',         'home/Desktop/5.pdf',          'home/keynote/6.pdf']   Output = Input_string.copy()temp = []  # Using iterationfor elem in Input_string:    for n in Input:        if n in elem:            temp.append(elem)  for elem in temp:    if elem in Output:        Output.remove(elem)  # Printingprint("List of keywords are:", Input)print("Given list:", Input_string)print("filtered list is :", Output)
List of keywords are: [‘key’, ‘keys’, ‘keyword’, ‘keychain’, ‘keynote’]Given list: [‘home/key/1.pdf’, ‘home/keys/2.pdf’, ‘home/keyword/3.pdf’, ‘home/keychain/4.pdf’, ‘home/Desktop/5.pdf’, ‘home/keynote/6.pdf’]filtered list is : [‘home/Desktop/5.pdf’]
 Method #2: Using list comprehension
# Python code to  filter element from list # based on another list of string.  # List InitializationInput = ['key', 'keys', 'keyword', 'keychain', 'keynote']Input_string = ['home/key/1.pdf',         'home/keys/2.pdf',          'home/keyword/3.pdf',          'home/keychain/4.pdf',         'home/Desktop/5.pdf',          'home/keynote/6.pdf']  # Using list comprehensionOutput = [b for b in Input_string if          all(a not in b for a in Input)]  # Printingprint("List of keywords are:", Input)print("Given list:", Input_string)print("filtered list is :", Output)
List of keywords are: [‘key’, ‘keys’, ‘keyword’, ‘keychain’, ‘keynote’]Given list: [‘home/key/1.pdf’, ‘home/keys/2.pdf’, ‘home/keyword/3.pdf’, ‘home/keychain/4.pdf’, ‘home/Desktop/5.pdf’, ‘home/keynote/6.pdf’]filtered list is : [‘home/Desktop/5.pdf’]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
p5.js | redraw() Function - GeeksforGeeks

23 Aug, 2019
The redraw() function is used to execute the code within draw() function one time. This functions is used to update the display window only when it necessary. The redraw() function does not work when it is called inside the draw() function. The loop() and noLoop() function is used to enable/disable the animations.
Syntax:
redraw( n )
Parameters: This function accepts single parameter n which is used to set the redraw for n times. The default value of this function is 1.
Below example illustrates the redraw() function in p5.js:
Example:
let l = 0;  function setup() {      // Create canvas of given size  createCanvas(500, 300);      // Set the background color  background('green');  }  function draw() {      // Set the stroke color  stroke('black');      // Function to draw the line  line(l, 0, l, height);    }  function mousePressed() {  l += 1;  redraw();}
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Compute the Value of Poisson Density in R Programming - dpois() Function - GeeksforGeeks

04 Jan, 2022
dpois() function in R Language is used to compute the Poisson Density for a set of Integer values. It also creates a density plot of poisson distribution. 
Syntax: dpois(vec, lambda)Parameters: vec: Sequence of integer values lambda: Average number of events per interval 
Example 1: 
Python3
# R program to compute# Poisson Density # Sequence of x-valuesx <- seq(-10, 10, by = 1) # Calling dpois() Functiony <- dpois(x, lambda = 5)y
Output: 
 [1] 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000
 [7] 0.000000000 0.000000000 0.000000000 0.000000000 0.006737947 0.033689735
[13] 0.084224337 0.140373896 0.175467370 0.175467370 0.146222808 0.104444863
[19] 0.065278039 0.036265577 0.018132789
Example 2: 
Python3
# R program to compute# Poisson Density # Sequence of x-valuesx <- seq(-10, 20, by = 1) # Calling dpois() Functiony <- dpois(x, lambda = 15) # Plot a graphplot(y)
Output: 
nnr223442
R Statistics-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Printing Output of an R Program
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Importance of @JsonView annotation using Jackson in Java?

The JsonView annotation can be used to include/exclude a property during the serialization and deserialization process dynamically. We need to configure an ObjectMapper class to include the type of view used for writing a JSON from Java object using the writerWithView() method.
@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonView
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonViewAnnotationTest {
   public static void main(String args[]) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      String jsonString = objectMapper.writerWithView(Views.Public.class).writeValueAsString(new Person());
      String jsonStringInternal = objectMapper.writerWithView(Views.Internal.class).writeValueAsString(new Person());
      System.out.println(jsonString);
      System.out.println(jsonStringInternal);
   }
}
// Person class
class Person {
   @JsonView(Views.Public.class)
   public long personId = 115;
   @JsonView(Views.Public.class)
   public String personName = "Raja Ramesh";
   @JsonView(Views.Internal.class)
   public String gender = "male";
   @Override
   public String toString() {
      return "Person{" +
             "personId=" + personId +
             ", personName='" + personName + '\'' +
             ", gender='" + gender + '\'' +
       '}';
   }
}
class Views {
   static class Public {}
   static class Internal extends Public {}
}
{"personId":115,"personName":"Raja Ramesh"}
{"personId":115,"personName":"Raja Ramesh","gender":"male"}
java.time.ZoneId.of() Method Example

The java.time.ZoneId.of(String zoneId) method obtains an instance of ZoneId from an ID ensuring that the ID is valid and available for use.
Following is the declaration for java.time.ZoneId.of(String zoneId) method.
public static ZoneId of(String zoneId)

zoneId − the time-zone ID, not null.
the zone ID, not null
DateTimeException − if the zone ID has an invalid format
DateTimeException − if the zone ID has an invalid format
ZoneRulesException − if the zone ID is a region ID that cannot be found.
ZoneRulesException − if the zone ID is a region ID that cannot be found.
The following example shows the usage of java.time.ZoneId.of(String zoneId) method.
package com.tutorialspoint;

import java.time.ZoneId;

public class ZoneIdDemo {
   public static void main(String[] args) {
 
      ZoneId zone = ZoneId.of("Z");
      System.out.println(zone);  
   }
}
Let us compile and run the above program, this will produce the following result −
Z

 Print
 Add Notes
 Bookmark this page
Yii - Rules of URL

A URL rule is an instance if yii\web\UrlRule. The urlManager components uses the URL rules declared in its rules property when the pretty URL format is enabled.
To parse a request, the URL manager obtains the rules in the order they are declared and looks for the first rule.
Step 1 − Modify the urlManager component in the config/web.php file.
'urlManager' => [
   'showScriptName' => false,
   'enablePrettyUrl' => true,
   'rules' => [
      'about' => 'site/about',
   ]
],
Step 2 − Go to your web browser at http://localhost:8080/about, you will see the about page.
A URL rule can be associated with query parameters in this pattern −
<ParamName:RegExp>, where −
ParamName − The parameter name
ParamName − The parameter name
RegExp − An optional regular expression used to match parameter values
RegExp − An optional regular expression used to match parameter values
Suppose, we have declared the following URL rules −
[
   'articles/<year:\d{4}>/<category>' => 'article/index',
   'articles' => 'article/index',
   'article/<id:\d+>' => 'article/view',
]
When the rules are used for parsing −
/index.php/articles is parsed into the article/index
/index.php/articles/2014/php is parsed into the article/index
/index.php/article/100 is parsed into the article/view
/index.php/articles/php is parsed into articles/php
When the rules are used for creating URLs −
Url::to(['article/index']) creates /index.php/articles
Url::to(['article/index']) creates /index.php/articles
Url::to(['article/index', 'year' => 2014, 'category' => 'php']) creates /index.php/articles/2014/php
Url::to(['article/index', 'year' => 2014, 'category' => 'php']) creates /index.php/articles/2014/php
Url::to(['article/view', 'id' => 100]) creates /index.php/article/100
Url::to(['article/view', 'id' => 100]) creates /index.php/article/100
Url::to(['article/view', 'id' => 100, 'source' => 'ad']) creates /index.php/article/100?source=ad
Url::to(['article/view', 'id' => 100, 'source' => 'ad']) creates /index.php/article/100?source=ad
Url::to(['article/index', 'category' => 'php']) creates /index.php/article/index?category=php
Url::to(['article/index', 'category' => 'php']) creates /index.php/article/index?category=php
To add a suffix to the URL, you should configure the yii\web\UrlManager::$suffix property.
Step 3 − Modify the urlComponent in the config/web.php file.
'urlManager' => [
   'showScriptName' => false,
   'enablePrettyUrl' => true,
   'enableStrictParsing' => true,
   'suffix' => '.html'
],
Step 4 − Type the address http://localhost:8080/site/contact.html in the address bar of the web browser and you will see the following on your screen. Notice the html suffix.
 Print
 Add Notes
 Bookmark this page
Filtering array to contain palindrome elements in JavaScript

We are required to write a JavaScript function that takes in an array of String / Number literals and returns a subarray of all the elements that were palindrome in the original array.
If the input array is −
const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
Then the output should be −
const output = [12321, 'did'];
We will create a helper function that takes in a number or a string and checks if its a boolean or not.
Then we will loop over the array, filter the palindrome elements and return the filtered array.
Therefore, let’s write the code for this function −
The code for this will be −
const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
const isPalindrome = el => {
   const str = String(el);
   let i = 0;
   let j = str.length - 1;
   while(i < j) {
      if(str[i] === str[j]) {
         i++;
         j--;
      } else {
         return false;
      }
   }
   return true;
};
const findPalindrome = arr => {
   return arr.filter(el => isPalindrome(el));
};
console.log(findPalindrome(arr));
The output in the console will be −
[ 12321, 'did' ]
C++ Set Library - begin Function

It returns an iterator referring to the first element in the set container.
Following are the ways in which std::set::begin works in various C++ versions.
iterator begin();
const_iterator begin() const;

 iterator begin() noexcept;
const_iterator begin() const noexcept;

It returns an iterator referring to the first element in the set container.
It never throws exceptions.
Time complexity is contstant.
The following example shows the usage of std::set::begin.
#include <iostream>
#include <set>

int main () {
   int myints[] = {50,40,30,20,10};
   std::set<int> myset (myints,myints+10);

   std::cout << "myset contains:";
   for (std::set<int>::iterator it = myset.begin(); it!=myset.end(); ++it)
      std::cout << ' ' << *it;

   std::cout << '\n';

   return 0;
}
The above program will compile and execute properly.
myset contains: 0 1 10 20 30 40 50 26390 2065620553

 Print
 Add Notes
 Bookmark this page
Generate Random double type number in Java

In order to generate Random double type numbers in Java, we use the nextDouble() method of the java.util.Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.
Declaration - The java.util.Random.nextDouble() method is declared as follows −
public float nextDouble()
Let us see a program to generate random double type numbers in Java −
 Live Demo
import java.util.Random;
public class Example {
   public static void main(String[] args) {
      Random rd = new Random(); // creating Random object
      System.out.println(rd.nextDouble()); // displaying a random double value between 0.0 & 1.0
   }
}
0.40755033612457214
Note - The output might vary on Online Compilers.
Unvalidated Redirects and Forwards

Most web applications on the internet frequently redirect and forward users to other pages or other external websites. However, without validating the credibility of those pages, hackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.
Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram.
Some classic examples of Unvalidated Redirects and Forwards are as given −
Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware.
Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware.
http://www.mywebapp.com/redirect.jsp?redirectrul=hacker.com

All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access.
All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access.
http://www.mywebapp.com/checkstatus.jsp?fwd=appadmin.jsp

It is better to avoid using redirects and forwards.
It is better to avoid using redirects and forwards.
If it is unavoidable, then it should be done without involving user parameters in redirecting the destination.
If it is unavoidable, then it should be done without involving user parameters in redirecting the destination.

    36 Lectures 
     5 hours 

 Sharad Kumar

    26 Lectures 
     2.5 hours 

 Harshit Srivastava

    47 Lectures 
     2 hours 

 Dhabaleshwar Das

    14 Lectures 
     1.5 hours 

 Harshit Srivastava

    38 Lectures 
     3 hours 

 Harshit Srivastava

    32 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
What is difference between onCreate() and onStart() on Android?

This example demonstrates the difference between onCreate() and onStart() in Android.
Note −
onCreate() is called when the when the activity is first created.
onStart() is called when the activity is becoming visible to the user.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Have a very nice day!"
      android:textSize="35dp"
      android:textStyle="bold"
      android:textColor="@color/colorAccent"
      android:layout_centerInParent="true"
      android:padding="20sp"
      android:layout_gravity="center_vertical" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
   public static final String TAG = "Have a nice day!";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.i(TAG,"onCreate");
   }
   protected void onStart(){
      super.onStart();
      Log.i(TAG,"onStart");
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Linux | Uptime command with examples

27 May, 2019
Uptime Command In Linux: It is used to find out how long the system is active (running). This command returns set of values that involve, the current time, and the amount of time system is in running state, number of users currently logged into, and the load time for the past 1, 5 and 15 minutes respectively.
Syntax:
uptime [-options]
Example:Input
[mistersubha@server-1 ~]$uptime              
 08:24:37 up 207 days, 11:10,  0 users,  load average: 0.00, 0.03, 0.05               

Output
From the above code, the output has got four parts: Current time, Uptime, Number of Users, and average load as mentioned earlier.
uptime has got few options to tailor outputs and to those who are unaware of the options of the newbies working with uptime can use the option “-h” (which means help). This will give the options available to the preceding command.
[mistersubha@server-1 ~]$uptime -h

Usage:
uptime [options]

Options:
 -p, --pretty   show uptime in pretty format
 -h, --help     display this help and exit
 -s, --since    system up since
 -V, --version  output version information and exit

For more details see uptime(1).

Just to make sure you get the uptime in human-readable format, you can use option “p”
[mistersubha@server-1 ~]$uptime -p
up 29 weeks, 4 days, 11 hours, 1 minute

Option “s” is used to get the starting time/specified time when the system started has been running.
[mistersubha@server-1 ~]$uptime -s
2017-11-10 20:14:15

Version information can be shown using option “V”.
[mistersubha@server-1 ~]$uptime -V
uptime from procps-ng 3.3.10

There are few other ways to find the uptime and output header of command “w” is similar to that of output of “uptime” command.
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
diff command in Linux with examples
Cat command in Linux with examples
echo command in Linux with Examples