code-rag-bench/online-tutorials huggingface dataset:
How to validate a URL using regular expression in C#?

To validate, you need to check for the protocols.
http
https
With that, you need to check for .com, .in, .org, etc.
For this, use the following regular expression −
(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?
The following is the code −
 Live Demo
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
   class Program {
      private static void showMatch(string text, string expr) {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args) {
         string str = "https://example.com";
         Console.WriteLine("Matching URL...");
         showMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?");
         Console.ReadKey();
      }
   }
}
Matching URL...
The Expression: ^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?
https://example.com
Enum.GetName in C#

Gets the string representation of an Enum value using the Enum.GetName.
It has two parameters −
Type − Enumeration type
Type − Enumeration type
Object − Value of an enumeration
Object − Value of an enumeration
The following is an example −
 Live Demo
using System;

class Demo {
   enum Vehicle {
      Car,
      Motorbike,
      Truck,
      Bicycles
   };
   static void Main() {
      // Usig GetName to get the string representation of enum type
      string res = Enum.GetName(typeof(Vehicle), Vehicle.Motorbike);
   
      // Displaying
      Console.WriteLine(res);
   }
}
Motorbike
Difference between Steganography and Cryptography

08 Jun, 2020
1. Steganography:Steganography is a method in which secret message is hidden in a cover media. Steganography means covered writing. Steganography is the idea to prevent secret information by creating the suspicion. Steganography is less popular than Cryptography. In steganography, structure of data is not usually altered.The forms of steganography are:
1. Text
2. Audio
3. Video
4. Images
5. Network or Protocol
 
2. Cryptography:Cryptography means secret writing. In cryptography, sender does not send message directly to the receiver, before sending information to the receiver information or plain text is converted into cipher text by using some encryption algorithm then send to the receiver and receiver decrypt the cipher text into plain text to read the original information.It is of two types:
1. Symmetric key cryptography
2. Asymmetric key cryptography 
The difference between Steganography and Cryptography:
swetha_vazhakkat
Computer Networks
Difference Between
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python: Numpy’s Structured Array

27 Aug, 2021
Numpy’s Structured Array is similar to Struct in C. It is used for grouping data of different types and sizes. Structure array uses data containers called fields. Each data field can contain data of any type and size. Array elements can be accessed with the help of dot notation.Note: Arrays with named fields that can contain data of various types and sizes.Properties of Structured array  
All structs in array have same number of fields.
All structs have same fields names.
For example, consider a structured array of student which has different fields like name, year, marks. 
Each record in array student has a structure of class Struct. The array of a structure is referred to as struct as adding any new fields for a new struct in the array, contains the empty array. Example 1: 
Python3
# Python program to demonstrate# Structured array  import numpy as np  a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)],       dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)]) print(a)
[('Sana', 2, 21.0) ('Mansi', 7, 29.0)]
 
Example 2: The structure array can be sorted by using numpy.sort() method and passing the order as parameter. This parameter takes the value of the field according to which it is needed to be sorted. 
Python3
# Python program to demonstrate# Structured array  import numpy as np  a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)],       dtype=[('name', (np.str_, 10)), ('age', np.int32), ('weight', np.float64)])              # Sorting according to the nameb = np.sort(a, order='name')print('Sorting according to the name', b) # Sorting according to the ageb = np.sort(a, order='age')print('\nSorting according to the age', b)
Sorting according to the name [('Mansi', 7, 29.0) ('Sana', 2, 21.0)]

Sorting according to the age [('Sana', 2, 21.0) ('Mansi', 7, 29.0)]
 
sagar0719kumar
varshagumber28
Picked
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CSS - Visibility

A property called visibility allows you to hide an element from view. You can use this property along with JavaScript to create very complex menu and very complex webpage layouts.
You may choose to use the visibility property to hide error messages that are only displayed if the user needs to see them, or to hide answers to a quiz until the user selects an option.
NOTE − Remember that the source code will still contain whatever is in the invisible paragraph, so you should not use this to hide sensitive information such as credit card details or passwords.
The visibility property can take the values listed in the table that follows −
visible
The box and its contents are shown to the user.
hidden
The box and its content are made invisible, although they still affect the layout of the page.
collapse
This is for use only with dynamic table columns and row effects.
Here is an example −
<html>
   <head>
   </head>

   <body>
      <p>
         This paragraph should be visible in normal way.
      </p>
   
      <p style = "visibility:hidden;">
         This paragraph should not be visible.
      </p>
   </body>
</html> 
It will produce the following result −

   This paragraph should be visible in normal way.


   This paragraph should not be visible.
DateTime.IsLeapYear() Method in C#

15 Jul, 2021
This method returns an indication of whether the specified year is a leap year or not. Here, the year is always interpreted as a year in the Gregorian calendar.
Syntax: 
public static bool IsLeapYear (int year);
Return Value: This method return true if year is a leap year otherwise it returns false.
Exception: This method will give ArgumentOutOfRangeException if the year is less than 1 or greater than 9999.
Below programs illustrate the use of above-discussed method:
Example 1: 
C#
// C# code to demonstrate the// IsLeapYear(Int32) Methodusing System; class GFG {     // Main Method    public static void Main()    {         // Checking the leap year between 2000 to 2019        for (int y = 2000; y <= 2019; y++)        {             // using method            if (DateTime.IsLeapYear(y))            {                Console.WriteLine("{0} is a Leap Year.", y);            }             else            {                Console.WriteLine("{0} is not a Leap Year.", y);            }        }    }}
Output: 
2000 is a Leap Year.
2001 is not a Leap Year.
2002 is not a Leap Year.
2003 is not a Leap Year.
2004 is a Leap Year.
2005 is not a Leap Year.
2006 is not a Leap Year.
2007 is not a Leap Year.
2008 is a Leap Year.
2009 is not a Leap Year.
2010 is not a Leap Year.
2011 is not a Leap Year.
2012 is a Leap Year.
2013 is not a Leap Year.
2014 is not a Leap Year.
2015 is not a Leap Year.
2016 is a Leap Year.
2017 is not a Leap Year.
2018 is not a Leap Year.
2019 is not a Leap Year.
Example 2:
C#
// C# code to demonstrate the// IsLeapYear(Int32) Methodusing System; class GFG {     // Main Method    public static void Main()    {         // using method        if (DateTime.IsLeapYear(9999))        {            Console.WriteLine("9999 is a Leap Year.");        }         else        {            Console.WriteLine("9999 is not a Leap Year.");        }         // using method will give an error        // as year's value is greater than        // 9999        if (DateTime.IsLeapYear(10000))        {            Console.WriteLine(" 10000 is a Leap Year.");        }         else {            Console.WriteLine("10000 is not a Leap Year.");        }    }}
Runtime Error:
Unhandled Exception: System.ArgumentOutOfRangeException: Year must be between 1 and 9999. Parameter name: year  
Reference:  
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.isleapyear?view=netframework-4.7.2
 
sooda367
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
numpy.arange() in Python

08 Nov, 2021
The arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop) 
Parameters : 
start : [optional] start of interval range. By default start = 0
stop  : end of interval range
step  : [optional] step size of interval. By default step size = 1,  
For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. 
dtype : type of output array
Return: 
Array of evenly spaced values.
Length of array being generated  = Ceil((Stop - Start) / Step) 
Example:
Python3
# Python Programming illustrating# numpy.arange method import numpy as geek print("A\n", geek.arange(4).reshape(2, 2), "\n")print("A\n", geek.arange(4, 10), "\n")print("A\n", geek.arange(4, 20, 3), "\n")
Output : 
A
 [[0 1]
 [2 3]]

A
 [4 5 6 7 8 9]

A
 [ 4  7 10 13 16 19]
Note: 
These NumPy-Python programs won’t run on onlineID, so run them on your systems to explore them.
The advantage of numpy.arange() over the normal in-built range() function is that it allows us to generate sequences of numbers that are not integers.
Example:
Python3
# Python Programming illustrating# numpy.arange method import numpy as np # Printing all numbers from 1 to# 2 in steps of 0.1print(np.arange(1, 2, 0.1))
Output: 
[1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]
If you try it with the range() function, you get a TypeError.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AshwinShenoy
adnanirshad158
shreybitz
akshaysingh98088
johannes124
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Convert integer to string in Python
HTML | <body> alink Attribute

05 Jan, 2022
The HTML <body> alink Attribute is used to specify the color of an active link in a document.
Note: The HTML <body> alink attribute is not supported by HTML5.
Syntax:
<body alink="color_name|hex_number|rgb_number">
Attribute Values:
color_name: It specifies the name of the color of an active link.
hex_number: It specifies the color of the activated link in terms of hex code.
rgb_number: It specifies the color of the activated link in terms of RGB value.
Example:
<!DOCTYPE html> <html>   <head>     <title>        HTML body alink Attribute    </title> </head>       <body alink="red" link="blue">     <center>         <h1 style="color:green;">            GeeksforGeeks        </h1>                   <h2>HTML <body> alink Attribute</h2>                             <a href="#">            A computer science portal for geeks        </a>    </center> </body>       </html>             
Output:
Supported Browsers: The browser supported by HTML <body> alink attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Design a Tribute Page using HTML & CSS
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to Install PHP on Linux?

06 Dec, 2021
PHP is a general-purpose scripting language that is especially used in web development. It was created in 1994 by Rasmus Lerdorf. It is used to manage dynamic content, databases, session tracking, and build entire e-commerce websites and Linux is an open-source operating system. It was first released on  17 September 1991  by Linus Torvalds. In this article, we will know that How can we install PHP on Linux operating system.
An ANSI C compiler.
Module-specific components like GD graphics libraries or PDF libraries.
Optional: Autoconf 2.59+ (for PHP versions < 7.0), Autoconf 2.64+ (for PHP versions > 7.2), Automake 1.4+, Libtool 1.4+, re2c 0.13.4+, and Bison.
Follow the below steps to install PHP on Linux:
Step 1: Open your terminal in Linux
On your Linux computer open the terminal. You can also open the terminal by using Ctrl+Alt+T.
Step 2: Update your packages
On your terminal update your packages using the following command.
#    sudo apt-get update
Step 3: Upgrade your packages
Now install available upgrades of all packages currently installed on the system using the following command.
#    sudo apt-get upgrade
Step 4: Install PHP
Now we are ready to install PHP. The following command will install PHP on our system.
#    sudo apt-get install php
After entering the above command a prompt will appear enter Y and press enter key. Within few minutes the latest version of PHP along with several extensions will install on your Linux system.
You can verify the PHP version after installation using the following command.
#    php --version
As you can see the output PHP version shown that means we have successfully installed PHP in our system.
how-to-install
PHP-basics
Picked
How To
Installation Guide
PHP
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
Python – Create a dictionary using list with none values

11 Sep, 2021
Sometimes you might need to convert a list to dict object for some better and fast operation. Let’s see how to convert a list into a dictionary of none values. Here we will find three methods of doing this.
Method #1: Using zip()and dict 
Python3
# Python code to demonstrate# converting list into dictionary with none values# using zip() and dictionary # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint ("initial list", str(ini_list)) # Converting list into dictionary using zip() and dictionaryres = dict(zip(ini_list, [None]*len(ini_list))) # printing final resultprint ("final dictionary", str(res))
initial list [1, 2, 3, 4, 5]
final dictionary {1: None, 2: None, 3: None, 4: None, 5: None}
 
Method #2: Using dict 
Python3
# Python code to demonstrate converting# list into dictionary with none values# using dict() # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint ("initial list", str(ini_list)) # Converting list into dict()res = dict.fromkeys(ini_list) # printing final resultprint ("final dictionary", str(res))
initial list [1, 2, 3, 4, 5]
final dictionary {1: None, 2: None, 3: None, 4: None, 5: None}
 
Method #3: Using dict comprehension  
Python3
# Python code to demonstrate converting# list into dictionary with none values# using dict comprehension # initializing listini_list = [1, 2, 3, 4, 5] # printing initialized listprint ("initial list", str(ini_list)) # Converting list into dict()res = {key: None for key in ini_list} # printing final resultprint ("final dictionary", str(res))
initial list [1, 2, 3, 4, 5]
final dictionary {1: None, 2: None, 3: None, 4: None, 5: None}
 
arorakashish0911
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to define custom methods in C#?

To define a custom method in C#, use the following syntax −
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body
}
The following are the various elements of a method −
Access Specifier − This determines the visibility of a variable or a method from another class.
Access Specifier − This determines the visibility of a variable or a method from another class.
Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
Method body − This contains the set of instructions needed to complete the required activity.
Method body − This contains the set of instructions needed to complete the required activity.
Let us see an example −
 Live Demo
using System;

namespace Demo {
   class NumberManipulator {
      public int FindMax(int num1, int num2) {
         /* local variable declaration */
         int result;

         if (num1 > num2)
         result = num1;
         else
         result = num2;
         return result;
      }

      static void Main(string[] args) {
         /* local variable definition */
         int a = 90;
         int b = 15;
         int ret;
         NumberManipulator n = new NumberManipulator();

         //calling the FindMax method
         ret = n.FindMax(a, b);
         Console.WriteLine("Max value is : {0}", ret );
         Console.ReadLine();
      }
   }
}
Max value is : 90
Replace an element of a Java LinkedList

An element in an Java LinkedList can be replaced using the java.util.ArrayList.set() method. This method has two parameters i.e the index at which the LinkedList element is to be replaced and the element that it should be replaced with. ArrayList.set() method returns the element that was at the position specified at the index previously.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Pear");
      l.add("Apple");
      l.add("Mango");
      l.add("Guava");
      l.add("Orange");
      System.out.println("The LinkedList is: " + l);
      l.set(2, "Peach");
      System.out.println("The LinkedList is: " + l);
   }
}
The LinkedList is: [Pear, Apple, Mango, Guava, Orange]
The LinkedList is: [Pear, Apple, Peach, Guava, Orange]
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.set() is used to replace the element “Mango” with “Peach” at index 2. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>();
l.add("Pear");
l.add("Apple");
l.add("Mango");
l.add("Guava");
l.add("Orange");
System.out.println("The LinkedList is: " + l);
l.set(2, "Peach");
System.out.println("The LinkedList is: " + l);
How to get file name from a path in PHP?

To get the file name from a path, the code is as follows−
 Live Demo
<?php
   $file = pathinfo('/home/cg/root/6985034/main.php');
   echo $file['basename'], "\n";
?>
This will produce the following output−
main.php
Let us now see another example −
 Live Demo
<?php
   $path = "/home/cg/root/6985034/main.php";
   $file = basename($path, ".php");
   echo $file;
?>
This will produce the following output−
main
What does backward() do in PyTorch?

The backward() method is used to compute the gradient during the
backward pass in a neural network.
The gradients are computed when this method is executed.
The gradients are computed when this method is executed.
These gradients are stored in the respective variables.
These gradients are stored in the respective variables.
The gradients are computed with respect to these variables, and the gradients are accessed using .grad.
The gradients are computed with respect to these variables, and the gradients are accessed using .grad.
If we do not call the backward() method for computing the gradient, the gradients are not computed.
If we do not call the backward() method for computing the gradient, the gradients are not computed.
And, if we access the gradients using .grad, the result is None.
And, if we access the gradients using .grad, the result is None.
Let's have a couple of examples to demonstrate how it works.
In this example, we attempt to access the gradients without calling the
backward() method. We notice that all the gradients are None.
# import torch library
import torch

# define three tensor
x = torch.tensor(2., requires_grad = False)
w = torch.tensor(3., requires_grad = True)
b = torch.tensor(1., requires_grad = True)
print("x:", x)
print("w:", w)
print("b:", b)

# define a function of the above defined tensors
y = w * x + b
print("y:", y)

# print the gradient w.r.t above tensors
print("x.grad:", x.grad)
print("w.grad:", w.grad)
print("b.grad:", b.grad)
x: tensor(2.)
w: tensor(3., requires_grad=True)
b: tensor(1., requires_grad=True)
y: tensor(7., grad_fn=<AddBackward0>)
x.grad: None
w.grad: None
b.grad: None
In this second example, the backward() method is called for the function
y. Then, the gradients are accessed. The gradient with respect to a tensor
that doesn't require grad is again None. The gradient with respect to the
tensor with gradient is not None.
# import torch library
import torch

# define three tensors
x = torch.tensor(2., requires_grad = False)
w = torch.tensor(3., requires_grad = True)
b = torch.tensor(1., requires_grad = True)
print("x:", x)
print("w:", w)
print("b:", b)

# define a function y
y = w * x + b
print("y:", y)

# take the backward() for y
y.backward()
# print the gradients w.r.t. above x, w, and b
print("x.grad:", x.grad)
print("w.grad:", w.grad)
print("b.grad:", b.grad)
x: tensor(2.)
w: tensor(3., requires_grad=True)
b: tensor(1., requires_grad=True)
y: tensor(7., grad_fn=<AddBackward0>)
x.grad: None
w.grad: tensor(2.)
b.grad: tensor(1.)
How to spilt a binary file into multiple files using Python?

To split a big binary file in multiple files, you should first read the file by the size of chunk you want to create, then write that chunk to a file, read the next chunk and repeat until you reach the end of original file.
For example, you have a file called my_song.mp3 and want to split it in files of size 500 bytes each.
CHUNK_SIZE = 500
file_number = 1
with open('my_song.mp3') as f:
    chunk = f.read(CHUNK_SIZE)
    while chunk:
        with open('my_song_part_' + str(file_number)) as chunk_file:
            chunk_file.write(chunk)
        file_number += 1
        chunk = f.read(CHUNK_SIZE)
In your current directory, now you'll find chunks of your original file scattered across multiple files with prefix as: my_song_part_
Bootstrap table-hover class

Using the .table-hover class, a light gray background will be added to rows while the cursor hovers over them.
You can try to run the following code to implement the table-hover class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Table</title>
      <meta name = "viewport" content = "width=device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <table class = "table table-hover table-bordered table-striped">
         <caption>Footballer Rank</caption>
         <thead>
            <tr>
               <th>Footballer</th>
               <th>Rank</th>
               <th>Country</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>Messi</td>
               <td>1</td>
               <td>Argentina</td>
            </tr>
            <tr>
               <td>Neymar</td>
               <td>2</td>
               <td>Brazil</td>
            </tr>
            <tr>
               <td>Ronaldo</td>
               <td>3</td>
               <td>Portugal</td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
How to repeat HTML element multiple times using ngFor based on a number? - GeeksforGeeks

24 Jun, 2020
In Angular ngFor is directive which accomplishes the motive of displaying repeated or list of contents with least lines of code, this serves the same purpose as for loops in conventional programming languages.
We can print repeated lines of content based on a number using the javascript/typescript function Array() which will generate a list of number from 0 to n-1. We traverse this list to produce n repeated lines of content.
Example 1:Demo.Component.ts
import { Component, OnInit } from '@angular/core';  @Component({  selector: 'app-demo',  templateUrl: './demo.component.html',  styleUrls: ['./demo.component.css']})  export class DemoComponent implements OnInit {    constructor() {  }  ngOnInit() {  }  //function to return list of numbers from 0 to n-1  numSequence(n: number): Array<number> {    return Array(n);  }}
Demo.Component.html
<mat-card class="example-card" >  <mat-card-header>   <h2 >Sequence of Numbers from 0 to 5</h2  >  </mat-card-header>  <mat-card-content>     <!-- n traverses through a list of [0, 1, 2, 3, 4, 5] i.e 0 to 5           i stores the index in each iteration -->    <span *ngFor="let n of numSequence(6);           let i = index;">{{i}} </span>  </mat-card-content></mat-card>
Output:
Example 2:Inserting template in typescript file and repeating the same element 6 times.Demo2.component.ts
import { Component, OnInit } from '@angular/core';  @Component({  selector: 'app-demo',  //template encapsulated within the component ts file  // instead of separate template(html)  template: '  <mat-card class="example-card" >  <mat-card-header class="example-header">   <h2 >Repeated GeeksforGeeks</h2  >  </mat-card-header>  <mat-card-content>    <ul>      <!--n traverses through a list of [0, 1, 2, 3, 4, 5] i.e 0 to 5             prints GeeksforGeeks for 6 times -->      <li example-card-text          *ngFor="let n of numSequence(6)">                <b>GeeksforGeeks</b></li>    </ul>  </mat-card-content></mat-card>',  styleUrls: ['./demo.component.css']})  export class DemoComponent implements OnInit {  constructor() {  }    ngOnInit() {  }     //function to return list of numbers from 0 to n-1  numSequence(n: number): Array<number> {    return Array(n);  }}
Output:
AngularJS-Misc
Picked
AngularJS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
How to create module with Routing in Angular 9 ?
How to setup 404 page in angular routing ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Materialize - Tabs

Materialize provides tabs CSS class to make a ul element as a tab. The following table mentions the available classes and their effects.
tabs
Identifies ul as a materialize tab component. Required for ul element.
active
Makes a tab active.
Following is an example of using a tab.
<!DOCTYPE html>
<html>
   <head>
      <title>The Materialize Tabs Example</title>
         <meta name="viewport" content="width=device-width, initial-scale=1">
         <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
         <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
   </head>
   <body class="container">
      <h3>Tabs Demo</h3>
         <div class="row">
            <div class="col s12">
            <ul class="tabs">
               <li class="tab col s3"><a href="#inbox">Inbox</a></li>
               <li class="tab col s3"><a class="active" href="#unread">Unread</a></li> 
               <li class="tab col s3 disabled"><a href="#outbox">Outbox (Disabled)</a></li>
               <li class="tab col s3"><a href="#sent">Sent</a></li>
            </ul>
         </div>
         <div id="inbox" class="col s12">Inbox</div>
          <div id="unread" class="col s12">Unread</div>
          <div id="outbox" class="col s12">Outbox (Disabled)</div>
         <div id="sent" class="col s12">Sent</div>
      </div>
   </body>
</html>
Verify the output.
 Print
 Add Notes
 Bookmark this page
DB2 - Triggers

This chapter describes triggers, their types, creation and dropping of the triggers.
A trigger is a set of actions, which are performed for responding to an INSERT, UPDATE or DELETE operation on a specified table in the database. Triggers are stored in the database at once. They handle governance of data. They can be accessed and shared among multiple applications. The advantage of using triggers is, if any change needs to be done in the application, it is done at the trigger; instead of changing each application that is accessing the trigger. Triggers are easy to maintain and they enforce faster application development. Triggers are defined using an SQL statement “CREATE TRIGGER”.
There are two types of triggers:
They are executed before any SQL operation.
They are executed after any SQL operation.
Let us see how to create a sequence of trigger:
Syntax:
db2 create sequence <seq_name> 
Example: Creating a sequence of triggers for table shopper.sales1
db2 create sequence sales1_seq as int start with 1 increment by 1 
Syntax:
db2 create trigger <trigger_name> no cascade before insert on 
<table_name> referencing new as <table_object> for each row set 
<table_object>.<col_name>=nextval for <sequence_name> 
Example: Creating trigger for shopper.sales1 table to insert primary key numbers automatically
db2 create trigger sales1_trigger no cascade before insert on 
shopper.sales1 referencing new as obj for each row set 
obj.id=nextval for sales1_seq
Now try inserting any values:
db2 insert into shopper.sales1(itemname, qty, price) 
values('bicks', 100, 24.00) 
Let us see how to retrieve values from a table:
Syntax:
db2 select * from <tablename>
Example:
db2 select * from shopper.sales1
Output:
  ID       ITEMNAME       QTY 
-------  ------------   ---------- 
    3      bicks            100 
    2      bread            100 
  
  2 record(s) selected. 
Let us see how to create an after trigger:
Syntax:
db2 create trigger <trigger_name> no cascade before insert on 
<table_name> referencing new as <table_object> for each row set
 <table_object>.<col_name>=nextval for <sequence_name> 
Example: [To insert and retrieve the values]
db2 create trigger sales1_tri_after after insert on shopper.sales1 
for each row mode db2sql begin atomic update shopper.sales1 
set price=qty*price; end  
Output:
//inseting values in shopper.sales1 
db2 insert into shopper.sales1(itemname,qty,price) 
values('chiken',100,124.00) 
//output 
ID    ITEMNAME       QTY         PRICE 
----- -------------- ----------- -----------                      
    3 bicks          100         2400.00 
    4 chiken         100         12400.00 
    2 bread          100         2400.00 

	3 record(s) selected. 
Here is how a database trigger is dropped:
Syntax:
db2 drop trigger <trigger_name>  
Example:
db2 drop trigger slaes1_trigger   

    10 Lectures 
     1.5 hours 

 Nishant Malik

    41 Lectures 
     8.5 hours 

 Parth Panjabi

    53 Lectures 
     11.5 hours 

 Parth Panjabi

    33 Lectures 
     7 hours 

 Parth Panjabi

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    178 Lectures 
     14.5 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python – Sum of each List element occurrence in another

09 Mar, 2020
Sometimes, while working with Python, we can have a problem in which we need to get occurrence of 1 element in another. But as a modification of this, we can have a problem in which we need to count the occurrence of all elements of 1 list in another. Lets discuss certain ways in which this task can be performed.
Method #1 : Using nested loopsThis is one of the way in which this task can be performed. This is brute force way in which this task can be performed. In this, we iterate one list and then target list, if element match, we increase the counter.
# Python3 code to demonstrate # Sum of each List element occurrence in another# using nested loops  # Initializing liststest_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]test_list2 = [4, 6, 1]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Sum of each List element occurrence in another# using nested loopsres = 0for ele in test_list2:    for ele1 in test_list1:        if ele1 == ele:            res = res + 1  # printing result print ("The occurrence count : " + str(res))
The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]
The original list 2 is : [4, 6, 1]
The occurrence count : 6

 
Method #2 : Using sum() + count()The combination of above methods can be used to perform this particular task. This is one liner alternative to the above method. In this counting is done using count() and accumulation using sum().
# Python3 code to demonstrate # Sum of each List element occurrence in another# using sum() + count()  # Initializing liststest_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]test_list2 = [4, 6, 1]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Sum of each List element occurrence in another# using sum() + count()res = sum(test_list1.count(idx) for idx in test_list2)  # printing result print ("The occurrence count : " + str(res))
The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]
The original list 2 is : [4, 6, 1]
The occurrence count : 6

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
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Divide a Vector into Ranges in R Programming – cut() Function

12 Jun, 2020
cut() function in R Language is used to divide a numeric vector into different ranges.
Syntax:cut.default(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3)
Parameters:x: Numeric Vectorbreak: break points of the vectorlabels: labels for levelsinclude.lowest: Boolean value to include lowest break valueright: Boolean value to close interval on the rightdig.lab: Used when labels are not provided
Example 1:
# R program to divide vector into ranges  # Generating a vector with random numbers y <- rnorm(100)     # the output factor is created by the division # of the range of variables into pi / 3*(-3:3) # 4 equal-length intervals table(cut(y, breaks = pi / 3*(-3:3))) 
Output:
(-3.14, -2.09] (-2.09, -1.05]     (-1.05, 0]      (0, 1.05]   (1.05, 2.09] 
            0            12            33            40            12 
  (2.09, 3.14] 
            2 

Example 2:
# R program to divide vector into ranges  # Creating vectors age <- c(40, 49, 48, 40, 67, 52, 53)   salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220) gender <- c("male", "male", "transgender",             "female", "male", "female", "transgender")     # Creating data frame named employee employee<- data.frame(age, salary, gender)       # Creating a factor corresponding to age with labels wfact = cut(employee$age, 3, labels = c('Young', 'Medium', 'Aged')) table(wfact) 
Output:
wfact
 Young Medium   Aged 
     4      2      1 

R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl ucfirst Function

This function returns the value of EXPR with only the first character uppercased. If EXPR is omitted, then uses $_.
Following is the simple syntax for this function −
ucfirst EXPR

ucfirst

This function returns String with first character in uppercase.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

$string = 'the cat sat on the mat.';
$u_string = ucfirst($string);

print "First String |$string|\n";
print "Second String |$u_string|\n";
When above code is executed, it produces the following result −
First String |the cat sat on the mat.|
Second String |The cat sat on the mat.|


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Display records after a particular date in MySQL

Let us first create a table −
mysql> create table DemoTable708 (
   CustomerName varchar(100),
   ShippingDate date
);
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable708 values('John','2019-01-21');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable708 values('Chris','2019-03-24');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable708 values('Robert','2019-04-26');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable708 values('David','2019-07-22');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable708;
This will produce the following output -
+--------------+--------------+
| CustomerName | ShippingDate |
+--------------+--------------+
| John         | 2019-01-21   |
| Chris        | 2019-03-24   |
| Robert       | 2019-04-26   |
| David        | 2019-07-22   |
+--------------+--------------+
4 rows in set (0.00 sec)
Following is the query to display records after a particular date in MySQL −
mysql> select *from DemoTable708 where ShippingDate >='2019-04-01';
This will produce the following output -
+--------------+--------------+
| CustomerName | ShippingDate |
+--------------+--------------+
| Robert       | 2019-04-26   |
| David        | 2019-07-22   |
+--------------+--------------+
2 rows in set (0.00 sec)
How to Install Tkinter on Linux? - GeeksforGeeks

05 Oct, 2021
Tkinter is the most popular Python library used to create GUI-based applications. The name Tkinter comes from the Tk interface. In this article, we will look into the process of installing Tkinter in a Linux system.
Note: Tkinter module comes in bundled with Python, so this article can be helpful for those who might face an error running Tkinter on their system.
Follow the below step to install Tkinter on a Linux system:
Step 1. Open up the Linux terminal and run the following command depending upon your version of Linux:
For Debian-based Linux:
sudo apt-get install python-tk
For Arch-based Linux:
sudo pacman -S tk
For Fedora-based Linux:
sudo dnf install python3-tkinter
For RHEL, CentOS, Oracle Linux:
sudo yum install -y tkinter tk-devel
Installing Tkinter in debian based linux
Step 2: After writing the above command hit the enter button and type your user password. After this, it will ask you to confirm the installation type “Y”  in the terminal and hit enter.
installing tkinter
Step 3: To verify the Tkinter installation run the following command in the terminal. And you will see a pop-up window opened with two buttons showing the current version of Tkinter installed.
python -m Tkinter
Tkinter installed
Note: The highlighted text shows the current version of the Tkinter i.e. 8.6
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
SQL - Multiple Column Ordering
How to pass data into table from a form using React Components
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How do you get a directory listing sorted by creation date in Python?

To get a directory listing sorted by creation date in Python, you can call os.listdir() to get a list of the filenames. Then call os.stat() for each one to get the creation time and finally sort against the creation time. 
import os
import time
import sys
from stat import S_ISREG, ST_CTIME, ST_MODE
dir_path = '.'
# get all entries in the directory
entries = (os.path.join(dir_path, file_name) for file_name in os.listdir(dir_path))
# Get their stats
entries = ((os.stat(path), path) for path in entries)
# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
           for stat, path in entries if S_ISREG(stat[ST_MODE]))
print(entries)
Running the above code will give you listing sorted by creation date, for example,
Mon Oct 23 18:01:25 2017 sorted_ls.py
How to escape all special characters for regex in Python?

We use re.escape() to escape the special characters −
The following code shows how all special characters in given string are escaped using re.escape() method
>>> p = '5*(67).89?'
>>> re.escape(p)
'5\\*\\(67\\)\\.89\\?'
How to show the title for the diagram of Seaborn pairplot() or PridGrid()? (Matplotlib)

To show the title for the diagram for Seaborn pairplot(), we can use pp.fig.suptitle() method.
Set the figure size and adjust the padding between and around the subplots.
Create a Pandas dataframe, i.e., a two-dimensional, size-mutable, potentially heterogeneous tabular data.
Plot pairwise relationships in a dataset.
Add a centered title to the figure.
To display the figure, use show() method.
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(np.random.random((5, 5)),
                  columns=["a", "b", "c", "d", "e"])

pp = sns.pairplot(df, height=3.5)
pp.fig.suptitle("My Pairplot")

plt.show()
Kotlin Syntax

In the previous chapter, we created a Kotlin file called Main.kt, and we used the following code to print "Hello World" to the screen:
fun main() {
  println("Hello World")
}
The fun keyword is used to declare a function. A function is a block of code designed to perform a particular task. In the example above, it declares the main() function.
The main() function is something you will 
see in every Kotlin program. This function is used to execute code. Any code inside the main() function's curly brackets {} will be executed.
For example, the println() function is inside the main() function, meaning that this will be executed. The println() function is used to output/print text, and in our example it will output "Hello World".
Good To Know: In Kotlin, code statements do not have to end with a semicolon (;) (which is often required for other programming languages, such as Java, C++, C#, etc.).
Before Kotlin version 1.3, it was required to use the main() function with parameters, like: fun main(args : Array<String>). 
The example above had to be written like this to work:
fun main(args : Array<String>) {
  println("Hello World")
}
Note: This is no longer required, and the program will run fine without it. However, it will not do any harm if you have been using it in the past, and will continue to use it.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
C program to sort names in alphabetical order

User has to enter number of names, and those names are required to be sorted in alphabetical order with the help of strcpy() function.
An array of characters (or) collection of characters is called a string.
Following is the declaration for an array −
char stringname [size];
For example, char string[50]; string of length 50 characters.
Using single character constant
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants
char string[10] = "Hello":;
There is a control string "%s" used for accessing the string till it encounters ‘\0’
This function is used for copying source string into destination string.
The length of the destination string is greater than or equal to the source string.
The syntax for strcpy() function is as follows −
strcpy (Destination string, Source String);
For example,
char a[50];             char a[50];
strcpy ("Hello",a);      strcpy ( a,"hello");
output: error           output: a= "Hello"
The logic used to sort the names in alphabetical order is as follows −
for(i=0;i<n;i++){
   for(j=i+1;j<n;j++){
      if(strcmp(str[i],str[j])>0){
         strcpy(s,str[i]);
         strcpy(str[i],str[j]);
         strcpy(str[j],s);
      }
   }
}
Following is the C program to sort names in alphabetical order −
#include<stdio.h>
#include<string.h>
main(){
   int i,j,n;
   char str[100][100],s[100];
   printf("Enter number of names :\n");
   scanf("%d",&n);
   printf("Enter names in any order:\n");
   for(i=0;i<n;i++){
      scanf("%s",str[i]);
   }
   for(i=0;i<n;i++){
      for(j=i+1;j<n;j++){
         if(strcmp(str[i],str[j])>0){
            strcpy(s,str[i]);
            strcpy(str[i],str[j]);
            strcpy(str[j],s);
         }
      }
   }
   printf("\nThe sorted order of names are:\n");
   for(i=0;i<n;i++){
      printf("%s\n",str[i]);
   }
}
When the above program is executed, it produces the following result −
Enter number of names:
5
Enter names in any order:
Pinky
Lucky
Ram
Appu
Bob
The sorted order of names is:
Appu
Bob
Lucky
Pinky
Ram