code-rag-bench/online-tutorials huggingface dataset:
numpy string operations | split() function

25 Nov, 2019
numpy.core.defchararray.split(arr, sep=None, maxsplit=None) is another function for doing string operations in numpy.It returns a list of the words in the string, using sep as the delimiter string for each element in arr.
Parameters:arr : array_like of str or unicode.Input array.sep : [ str or unicode, optional] specifies the separator to use when splitting the string.maxsplit : how many maximum splits to do.
Returns : [ndarray] Output Array containing of list objects.
Code #1 :
# Python program explaining# numpy.char.split() method   # importing numpy import numpy as geek  # input array  in_arr = geek.array(['geeks for geeks'])print ("Input array : ", in_arr)   # output array out_arr = geek.char.split(in_arr)print ("Output splitted array: ", out_arr) 
Input array :  ['geeks for geeks']
Output splitted array:  [['geeks', 'for', 'geeks']]

 
Code #2 :
# Python program explaining# numpy.char.split() method   # importing numpy import numpy as geek  # input array in_arr = geek.array(['Num-py', 'Py-th-on', 'Pan-das'])print ("Input array : ", in_arr)     # output array out_arr = geek.char.split(in_arr, sep ='-')print ("Output splitted array: ", out_arr) 
Input array :  ['Num-py' 'Py-th-on' 'Pan-das']
Output splitted array:  [['Num', 'py'] ['Py', 'th', 'on'] ['Pan', 'das']]

 
Code #3 :
# Python program explaining# numpy.char.split() method   # importing numpy import numpy as geek  # input array in_arr = geek.array(['Num-py', 'Py-th-on', 'Pan-das'])print ("Input array : ", in_arr)     # output array when maximum splitting # of every array element is 1out_arr = geek.char.split(in_arr, sep ='-', maxsplit = 1)print ("Output splitted array: ", out_arr) 
Input array :  ['Num-py' 'Py-th-on' 'Pan-das']
Output splitted array:  [['Num', 'py'] ['Py', 'th-on'] ['Pan', 'das']]

shubham_singh
Python numpy-String Operation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Digital Logic & Number representation - GeeksforGeeks

27 Sep, 2021
= XY’+XY
= X(Y’+Y)
= X *1
= X 
Column x = f(x,y) 
So , 
f(x,y)=x 

= PQ + QR’ + PR’ 
= PQ(R+R’) + (P+P’)QR’ + P(Q+Q’)R’
= PQR + PQR’ +PQR’ +P’QR’ + PQR’ + PQ’R’ 
= PQR(m7) + PQR'(m6)+P’QR'(m2) +PQ’R'(m4) 
= m2 + m4 + m6 + m7 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
50 Common Ports You Should Know
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
How to Find Length of String in Bash Script?
Spring Boot - Thymeleaf with Example
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
How to add horizontal line in HTML ?
Explain Promise.all with async-await in JavaScript
double Keyword in C#

22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. It is a keyword that is used to declare a variable that can store a floating-point value from the range of ±5.0 x 10-324 to ±1.7 x 10308. It is an alias of System.Double. Basically, it is a 64-bit double precision floating point number and have 14 to 15 digit precision.
Double Keyword occupies 8 byte (64 bits) space in the memory.
Syntax:
double variable_name = value;
We can specify a suffix d or D to represent a double value. Also floating point value without using any suffix is considered as a double value.
Example:
Input: num: 1234.5678

Output: num: 1234.5678
        Size of a double variable: 8

Input: num = -67895.4322D

Output: Type of num: System.Double
        num: -67895.4322
        Size of a double variable: 8

Example 1:
// C# program for the double keywordusing System;using System.Text;  class geeks {      static void Main(string[] args)    {        // variable declaration        double num = 1234.5678;          // to print value        Console.WriteLine("num: " + num);          // to print size        Console.WriteLine("Size of a double variable: " + sizeof(double));    }}
Output:
num: 1234.5678
Size of a double variable: 8

Example 2:
// C# program for the double keywordusing System;using System.Text;  namespace Test {  class geeks {      static void Main(string[] args)    {        // variable declaration        double num = -67895.4322D;          // to print type of variable        Console.WriteLine("Type of num: " + num.GetType());          // to print value        Console.WriteLine("num: " + num);          // to print size        Console.WriteLine("Size of a double variable: " + sizeof(double));          // to print minimum & maximum value of double        Console.WriteLine("Min value of double: " + double.MinValue);        Console.WriteLine("Max value of double: " + double.MaxValue);          // hit ENTER to exit        Console.ReadLine();    }}}
Output:
Type of num: System.Double
num: -67895.4322
Size of a double variable: 8
Min value of double: -1.79769313486232E+308
Max value of double: 1.79769313486232E+308

CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | Replace() Method
C# | Arrays
Implicit Waits in Selenium Python

19 May, 2020
Selenium Python is one of the great tools for testing automation. These days most of the web apps are using AJAX techniques. When a page is loaded by the browser, the elements within that page may load at different time intervals. This makes locating elements difficult: if an element is not yet present in the DOM, a locate function will raise an ElementNotVisibleException exception. Using waits, we can solve this issue. Waiting provides some slack between actions performed – mostly locating an element or any other operation with the element. Selenium Webdriver provides two types of waits – implicit & explicit. This article revolves around Implicit waits in Selenium Python.
Implicit WaitsAn implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or elements) not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object. Let’s consider an example –
# import webdriverfrom selenium import webdriver  driver = webdriver.Firefox()  # set implicit wait timedriver.implicitly_wait(10) # seconds  # get urldriver.get("http://somedomain / url_that_delays_loading")  # get element after 10 secondsmyDynamicElement = driver.find_element_by_id("myDynamicElement")
This waits up to 10 seconds before throwing a TimeoutException unless it finds the element to return within 10 seconds.
Implicit wait as defined would be the set using implicitly_wait method of driver. Let’s implement this on https://www.geeksforgeeks.org/ and wait 10 seconds before locating an element.
# import webdriver from selenium import webdriver   # create webdriver object driver = webdriver.Firefox()     # set implicit wait timedriver.implicitly_wait(10) # seconds  # get geeksforgeeks.org driver.get("https://www.geeksforgeeks.org/")     # get element after 10 secondselement = driver.find_element_by_link_text("Courses")  # click elementelement.click()  
Output –First it opens https://www.geeksforgeeks.org/ and then finds Courses link
It clicks on courses links and is redirected to https://practice.geeksforgeeks.org/
Python-selenium
selenium
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
Selecting Child Elements with CSS

The CSS child combinator is used to select all child elements of a parent element.
The syntax of the CSS child combinator is as follows −
Selector > Selector {
   attribute: /*value*/
}
The CSS descendant combinator is used to select all descendants of a parent element
The syntax of the CSS descendant combinator is as follows −
Selector Selector {
   attribute: /*value*/
}
The following examples illustrate the CSS child and descendant combinator.
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
article > * {
   text-align: center;
   border: 10px groove tomato;
}
::first-line {
   box-shadow: inset 0 0 7px cornflowerblue;
}
</style>
</head>
<body>
<article>
<h2>Donec rutrum a erat vitae interdum. </h2>
<p>Duis consequat aliquet leo, quis aliquam ex vehicula in. Vivamus placerat tincidunt hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque semper ex eget nulla consectetur varius.</p>
<img src="https://images.unsplash.com/photo-1612840666989- a16302e84978?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=120&ixlib=rb1.2.1&q=80&w=120" />
</article>
</body>
</html>
This will produce the following result −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body > * {
   margin: 20px;
}
article p {
   font-size: 24px;
   box-shadow: -10px 1px 0 rgba(12,43,180, 0.6);
}
</style>
</head>
<body>
<article>
<p>Neque porro quisquam </p>
<p>est qui dolorem ipsum quia dolor sit amet,</p>
<div><p>consectetur, adipisci velit.....</p></div>
</article>
<div>
<p> consectetur, adipisci velit</p>
<article>
<p> consectetur, adipisci velit</p>
</article>
</div>
</body>
</html>
This will produce the following result −
Python – Swap elements in String list

06 Mar, 2020
Sometimes, while working with data records we can have a problem in which we need to perform certain swap operation in which we need to change one element with other over entire string list. This has application in both day-day and data Science domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using replace() + list comprehensionThe combination of above functionalities can be used to perform this task. In this, we iterate through list using list comprehension and task of swapping is performed using replace().
# Python3 code to demonstrate # Swap elements in String list# using replace() + list comprehension  # Initializing listtest_list = ['Gfg', 'is', 'best', 'for', 'Geeks']  # printing original listsprint("The original list is : " + str(test_list))  # Swap elements in String list# using replace() + list comprehensionres = [sub.replace('G', '-').replace('e', 'G').replace('-', 'e') for sub in test_list]  # printing result print ("List after performing character swaps : " + str(res))
The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks']
List after performing character swaps : ['efg', 'is', 'bGst', 'for', 'eGGks']

 
Method #2 : Using join() + replace() + split()The combination of above methods can also be used to perform this task. In this, the task of replace is same, but we use join() and split() with same parameter to perform task of list comprehension.
# Python3 code to demonstrate # Swap elements in String list# using replace() + join() + split()  # Initializing listtest_list = ['Gfg', 'is', 'best', 'for', 'Geeks']  # printing original listsprint("The original list is : " + str(test_list))  # Swap elements in String list# using replace() + join() + split()res = ", ".join(test_list)res = res.replace("G", "_").replace("e", "G").replace("_", "e").split(', ')  # printing result print ("List after performing character swaps : " + str(res))
The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks']
List after performing character swaps : ['efg', 'is', 'bGst', 'for', 'eGGks']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get column names from PostgreSQL table using Psycopg2

14 Sep, 2021
This article is an illustration of how to extract column names from PostgreSQL table using psycopg2 and Python.
Used table for demonstration:
Example 1:
First, we connect the PostgreSQL database using psycopg2.connect()  method, then we create a cursor using cursor() method, after that we use the cursor() then extract the first element from it using slicing.
Python3
import psycopg2  conn = psycopg2.connect(    database="geeks",    user='postgres',    password='pass',    host='localhost',    port= '5432')  conn.autocommit = Truecursor = conn.cursor()  sql = '''SELECT * FROM products'''    cursor.execute(sql)column_names = [desc[0] for desc in cursor.description]for i in column_names:    print(i)conn.commit()conn.close()
Output:
product_no
name
price
Example 2: In the second approach, we execute the following SQL command in the cursor.execute() method.
“select COLUMN_NAME from information_schema.columns where  table_schema = ‘SCHEMA_NAME’ and table_name=’TABLE_NAME'”
Python3
import psycopg2  conn = psycopg2.connect(    database="geeks",    user='postgres',    password='root',    host='localhost',    port='5432')  conn.autocommit = True    with conn:    with conn.cursor() as cursor:        cursor.execute(            "select COLUMN_NAME from information_schema.columns\            where table_name='products'")        column_names = [row[0] for row in cursor]  print("Column names:\n")  for i in column_names:    print(i)
Output:
Column names:

product_no
name
price
Picked
Python PostgreSQL
Python Pyscopg2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyDictionary module in Python

04 May, 2020
PyDictionary is a dictionary (as in the English language dictionary) module for Python2 and Python3. PyDictionary provides the following services for a word:
meanings
translations
To install PyDictionary run the following pip code on the terminal / command prompt:
pip install PyDictionary
Now let us see how to use the PyDictionary module. First of all we need to import the module:
from PyDictionary import PyDictionary

After importing the module, we need to create an instance of it in order to use it:
dict = PyDictionary()

To get the meaning of a word we need to pass the word in the meaning() method.
Example:
from PyDictionary import PyDictionary    dict = PyDictionary()  # meaning of "python"meaning = dict.meaning("python")print(meaning)
Output:
{‘Noun’: [‘large Old World boas’, ‘a soothsaying spirit or a person who is possessed by such a spirit’, ‘(Greek mythology’]}
If a word is both a noun and a verb, then the method will return a dictionary containing the keys ‘Noun’ and ‘Verb’.
Example:
from PyDictionary import PyDictionary    dict = PyDictionary()  # meaning of "test"meaning = dict.meaning("test")print(meaning)
Output:
{‘Noun’: [‘trying something to find out about it’, ‘any standardized procedure for measuring sensitivity or memory or intelligence or aptitude or personality etc’, ‘a set of questions or exercises evaluating skill or knowledge’, ‘the act of undergoing testing’, ‘the act of testing something’, ‘a hard outer covering as of some amoebas and sea urchins’], ‘Verb’: [‘put to the test, as for its quality, or give experimental use to’, ‘test or examine for the presence of disease or infection’, “examine someone’s knowledge of something”, ‘show a certain characteristic when tested’, ‘achieve a certain score or rating on a test’, ‘determine the presence or properties of (a substance’, ‘undergo a test’]}
To get the translation of a word we need to pass the word in the translate() method as the first parameter and the language to be translated into as the second parameter. The name of the language should be in its respective language code.
from PyDictionary import PyDictionary    dict = PyDictionary()  # to translate into Germantranslation = dict.translate("happy",'de')print(translation)
Output:
glücklich
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
R - Bar Charts

A bar chart represents data in rectangular bars with length of the bar proportional to the value of the variable. R uses the function barplot() to create bar charts.
 R can draw both vertical and Horizontal bars in the bar chart.
In bar chart each of the bars can be given different colors.
The basic syntax to create a bar-chart in R is −
barplot(H,xlab,ylab,main, names.arg,col)

Following is the description of the parameters used −
H is a vector or matrix containing numeric values used in bar chart.
xlab is the label for x axis.
ylab is the label for y axis.
main is the title of the bar chart.
names.arg is a vector of names appearing under each bar.
col is used to give colors to the bars in the graph.
A simple bar chart is created using just the input vector and the name of each bar.
 The below script will create and save the bar chart in the current R working directory.
# Create the data for the chart
H <- c(7,12,28,3,41)

# Give the chart file a name
png(file = "barchart.png")

# Plot the bar chart 
barplot(H)

# Save the file
dev.off()
When we execute above code, it produces following result −
The features of the bar chart can be expanded by adding more parameters. The main parameter is used to add  title. The col parameter is used to add colors to the bars. The args.name is a vector having same number of values as the input vector to describe the meaning of each bar.
The below script will create and save the bar chart in the current R working directory.
# Create the data for the chart
H <- c(7,12,28,3,41)
M <- c("Mar","Apr","May","Jun","Jul")

# Give the chart file a name
png(file = "barchart_months_revenue.png")

# Plot the bar chart 
barplot(H,names.arg=M,xlab="Month",ylab="Revenue",col="blue",
main="Revenue chart",border="red")

# Save the file
dev.off()
When we execute above code, it produces following result −
We can create bar chart with groups of bars and stacks in each bar by using a matrix as input values.
 More than two variables are represented as a matrix which is used to create the group bar chart and stacked bar chart.
# Create the input vectors.
colors = c("green","orange","brown")
months <- c("Mar","Apr","May","Jun","Jul")
regions <- c("East","West","North")

# Create the matrix of the values.
Values <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11), nrow = 3, ncol = 5, byrow = TRUE)

# Give the chart file a name
png(file = "barchart_stacked.png")

# Create the bar chart
barplot(Values, main = "total revenue", names.arg = months, xlab = "month", ylab = "revenue", col = colors)

# Add the legend to the chart
legend("topleft", regions, cex = 1.3, fill = colors)

# Save the file
How to Sort Values Alphabetically in R?

28 Nov, 2021
In this article, we will discuss how to sort values alphabetically in R Programming Language.
Here we are using sort() function to sort a vector alphabetically.
Syntax:
sort(vector)
where, vector is the input vector
Example:
R
# create a vectorvector1 = c('G', 'E', 'E', 'K', 'S')  # sort the vectorprint(sort(vector1))
Output:
[1] "E" "E" "G" "K" "S"
We can create a dataframe by using date.frame() function. We can sort a dataframe column by using order() function
Syntax:
dataframe[order(dataframe$column_name),]
where,
dataframe is the input dataframe
column_name is the column that includes alphabetical values based on this column
Example:
R
# create a dataframe with 3 columnsdata = data.frame(name1=c('G', 'E', 'E', 'K', 'S'),                  name2=c('P', 'Y', 'T', 'H', 'O'),                   marks=c(78, 89, 77, 89, 78))  # sort the dataframe based on name1 columnprint(data[order(data$name1), ])  # sort the dataframe based on name2 columnprint(data[order(data$name2), ])
Output:
We can also sort multiple columns in dataframe by using order function.
Syntax:
dataframe[with(dataframe, order(column1, column2,.,column n)), ]
Example:
R
# create a dataframe with 3 columnsdata = data.frame(name1=c('G', 'E', 'E', 'K', 'S'),                   name2=c('P', 'Y', 'T', 'H', 'O'),                   marks=c(78, 89, 77, 89, 78))  # sort the dataframe based on name1 and # name2 columnsprint(data[with(data, order(name1, name2)), ])
Output:
Picked
R DataFrame-Programs
R Vector-Programs
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Run Multiple Threads

22 Dec, 2020
Thread is a lightweight process. A process in execution is called a program. A subpart of a program is called a thread. Threads allow a program to operate more efficiently by doing multiple things at the same time performing complicated tasks in the background without interrupting the main program execution.
All threads can communicate with each other. Java provides a Thread class to achieve thread programming.  Thread class provides constructors and methods to create and perform operations on a thread. 
Various Thread Methods:
start(): method is used to start the execution of the thread.
run(): method is used to do an action.
sleep(): This method sleeps a thread for the specified amount of time.
resume(): This method is used to resume the suspended thread.
stop(): This method is used to stop the thread.
destroy(): This method is used to destroy the thread group and all of its subgroups.
Syntax:
public class Thread   extends Object   implements Runnable
Java
// Java Program to Run Multiple Threads  // class extends thread classclass Main extends Thread {      // run method implementation    public void run()    {        System.out.println("Geeks for Geeks");    }      // in the main method    public static void main(String args[])    {        // object creation        Main t1 = new Main();          // object creation        Main t2 = new Main();          // object creation        Main t3 = new Main();          // start the thread        t1.start();          // start the thread        t2.start();          // start the thread        t3.start();    }}
Geeks for Geeks
Geeks for Geeks
Geeks for Geeks
Java-Multithreading
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Search in PHP

05 Apr, 2018
Binary Search is a searching technique used to search an element in a sorted array. In this article, we will learn about how to implement Binary Search in PHP using iterative and recursive way. Given a array of numbers, we need to search for the presence of element x in the array using Binary Search.
Examples:
Input : 1 2 3 4 5
        5 
Output : 5 Exists

Input : 1 5 8
        0
Output : 0 Doesnt Exist

This searching technique is more efficient than linear search.
Method 1(Iterative):
Steps Involved:1) Sort the array as binary search only works on sorted ranges2) Compute the middle element if the element we wish to search is greater than the middle element search on the right side else search on the left.3) Return True if the element is found.
<?php  function binarySearch(Array $arr, $x){    // check for empty array    if (count($arr) === 0) return false;    $low = 0;    $high = count($arr) - 1;          while ($low <= $high) {                  // compute middle index        $mid = floor(($low + $high) / 2);           // element found at mid        if($arr[$mid] == $x) {            return true;        }          if ($x < $arr[$mid]) {            // search the left side of the array            $high = $mid -1;        }        else {            // search the right side of the array            $low = $mid + 1;        }    }          // If we reach here element x doesnt exist    return false;}  // Driver code$arr = array(1, 2, 3, 4, 5);$value = 5;if(binarySearch($arr, $value) == true) {    echo $value." Exists";}else {    echo $value." Doesnt Exist";}?>
Output:
5 Exists

Method 2(Recursive):Recursion is a way where we repeatedly call the same function until a base condition is matched to end the recursion.Proceeding with the steps in method 1 here we use the same idea by just changing the parameters of the function in recursive manner and breaking down the problem.
function binarySearch(Array $arr, $start, $end, $x){    if ($end < $start)        return false;       $mid = floor(($end + $start)/2);    if ($arr[$mid] == $x)         return true;      elseif ($arr[$mid] > $x) {          // call binarySearch on [start, mid - 1]        return binarySearch($arr, $start, $mid - 1, $x);    }    else {          // call binarySearch on [mid + 1, end]        return binarySearch($arr, $mid + 1, $end, $x);    }}  // Driver code$arr = array(1, 2, 3, 4, 5);$value = 5;if(binarySearch($arr, 0, count($arr) - 1, $value) == true) {    echo $value." Exists";}else {    echo $value." Doesnt Exist";}
Output:
5 Exists

Related PHP functions:in_array() in PHParray_key_exists() in PHP
Binary Search
PHP
Technical Scripter
Web Technologies
Binary Search
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular Material 7 - Radio Button

The <mat-radiobutton>, an Angular Directive, is used for <input type="radio"> for enhance material design based styling..
In this chapter, we will showcase the configuration required to draw a radio button control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatRadioModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatRadioModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-radio-group {
   display: inline-flex;
   flex-direction: column;
}
.tp-radio-button {
   margin: 5px;
}
.tp-selected-value {
   margin: 15px 0;
}
Following is the content of the modified ts file app.component.ts.
import { Component } from '@angular/core';
import { FormControl } from "@angular/forms";
import { Validators } from "@angular/forms";
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'materialApp'; 
   favoriteSeason: string;
   seasons: string[] = ['Winter', 'Spring', 'Summer', 'Autumn'];
}
Following is the content of the modified HTML host file app.component.html.
<mat-radio-group class = "tp-radio-group" [(ngModel)] = "favoriteSeason">
   <mat-radio-button class = "tp-radio-button"
      *ngFor = "let season of seasons" [value] = "season">
      {{season}}
   </mat-radio-button>
</mat-radio-group>
<div class = "tp-selected-value">
   Selected Season: {{favoriteSeason}}
</div>
Verify the result.
As first, we've created an radio button group using mat-radio-group bound with ngModel.
As first, we've created an radio button group using mat-radio-group bound with ngModel.
Then, we've added radio buttons using mat-radio-button.
Then, we've added radio buttons using mat-radio-button.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to create cookies in JavaScript?

Using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.
document.cookie = "key1=value1;key2=value2;expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.
You can try to run the following code. It sets a customer name in an input cookie.
Live Demo
<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("Enter some value!");
                  return;
               }
               cookievalue= escape(document.myform.customer.value) + ";";
               document.cookie = "name = " + cookievalue;
               document.write ("Setting Cookies : " + "name = " + cookievalue );
            }
         //-->
      </script>
   </head>
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
      </form>
   </body>
</html>
Redis Pipelining

13 Aug, 2020
Redis is a Transmission Control Protocol (TCP) server which supports request or response protocol. A request is completed in 2 steps :
The client sends query to server in blocking manner to get server response.
Then server operates command and sends response back result of query to client.
What is Pipelining :In pipelining, client can send multiple queries or requests to server without waiting for all replies of queries at all and can finally reads replies in single go. In pipelining, client needs reply of read command and then it can call write command.
Advantages of Redis Pipelining :The main advantage of Redis pipelining is to boosting up protocol performance. It improves Redis performance because of multiple commands simultaneous execution. The speedup gained by pipelining ranges from factor of 5 for connections to localhost up to factor of at least 100 over low speed internet connections.
Example :Let’s take scenario where we will submit multiple commands to Redis one time and then it will provide output of all commands in one go.
Open Redis terminal and put the following command :
(echo -en “PING\r\n SET master geeksforgeeks\r\n GET master\r\n INCR visitor\r\n INCR visitor\r\n INCR visitor\r\n”; sleep 15) |  nc localhost 6876  
Output:
1st Run:$(echo -en “PING\r\n SET master geeksforgeeks\r\n GET master\r\n INCR visitor\r\n INCR visitor\r\n INCR visitor\r\n”; sleep 15) |
nc localhost 6876  
+PONG 
+OK 
geeksforgeeks
:5 
:6 
:7 
2nd Run:$(echo -en “PING\r\n SET master geeksforgeeks\r\n GET master\r\n INCR visitor\r\n INCR visitor\r\n INCR visitor\r\n”; sleep 15) |
nc localhost 6876  
+PONG 
+OK 
geeksforgeeks
:8 
:9 
:10
Note :
PING command is used to check connection of redis.
A string is set named “master” having value “geeksforgeeks”.
Got the key value and had incremented visitors numbers 3 times.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
Advanced Encryption Standard (AES)
Bluetooth
Intrusion Detection System (IDS)
Cryptography and its Types
Difference between FDMA, TDMA and CDMA
Date() and DateAdd() Function in MS Access

03 Sep, 2020
1. Date() Function :Date() function returns the current date of the system. In this function, no parameter will be passed and it will return the current date.
Syntax :
Date() 
Example :
SELECT Date() AS CurrentDate;
Output –
2. DateAdd() Function :DateAdd() function will add the time interval and date to the given date and return it. In this function, the first parameter will be the interval notation and second parameter will be the number that will be added and the third parameter will be the date,
Syntax :
DateAdd(interval, number, date) 
Example-1 :
SELECT DateAdd("yyyy", 3, #02/09/2020#);
Output –
Example-2 :
SELECT DateAdd("m", 3, Date()) As Date;
Output –
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
GETDATE() Function in SQL Server

18 Jan, 2021
GETDATE() function :This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm:ss.mmm’ pattern.
Features :
This function is used to find the present date and time of the database system.
This function comes under Date Functions.
This function doesn’t accept any parameter.
This function returns output in ‘YYYY-MM-DD hh:mm:ss.mmm‘ format.
Syntax :
GETDATE()
Parameter :This method doesn’t accept any parameter.
Returns :It returns the present date and time of the database system in a ‘YYYY-MM-DD hh:mm:ss.mmm‘ format.
Example-1 :Using GETDATE() function and getting the output.
SELECT GETDATE();
Output :
2021-01-03 14:42:58.970
Here, the output will vary each time the code is compiled as this method returns the current date and time.
Example-2 :Using GETDATE() as a default value in the below example and getting the output.
CREATE TABLE get_date
(
id_num INT IDENTITY, 
message VARCHAR(150) NOT NULL, 
generated_at DATETIME NOT NULL
DEFAULT GETDATE(), 
PRIMARY KEY(id_num)
);

Inserting Data :
INSERT INTO get_date(message)
VALUES('Its the first message.');

INSERT INTO get_date(message)
VALUES('get_date');

Read Data :
SELECT id_num, message, generated_at
FROM get_date;
Output :
Here, firstly you need to create a table then insert values into it then generate the required output using GETDATE() function as a default value.
Note –For running the above code use SQL server compiler, you can also use an online compiler.
Application :This function is used to return the current date and time of the database system.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
Ruby | Array count() operation

08 Jan, 2020
Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array.
Syntax:  Array.count()

Parameter:  obj - specific element to found

Return:  removes all the nil values from the array. 

Code #1 : Example for count() method
# Ruby code for count() method# to count elements  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, nil, nil, 50, 6]  # counting total elementsputs "counting : #{a.count}\n\n"  # counting 1puts "counting : #{b.count(1)}\n\n"  # counting 'nil'puts "counting : #{c.count(nil)}\n\n"
Output :
counting : 6

counting : 3

counting : 2

Code #2 : Example for count() method
# Ruby code for count() method# to count elements  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayb = ["cow", nil, "dog"]  # declaring arrayc = ["cat", nil, nil]  # counting total elementsputs "counting : #{a.count}\n\n"  # counting 1puts "counting : #{b.count(1)}\n\n"  # counting 'nil'puts "counting : #{c.count(nil)}\n\n"
Output :
counting: 3

counting : 0

counting : 2

Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Ruby | String capitalize() Method
HashMap isEmpty() Method in Java

26 Nov, 2018
The java.util.HashMap.isEmpty() method of HashMap class is used to check for the emptiness of the map. The method returns True if no key-value pair or mapping is present in the map else False.
Syntax:
Hash_Map.isEmpty()
Parameters: The method does not take any parameters.
Return Value: The method returns boolean true if the map is empty or does not contain any mapping pairs else boolean false.
Below programs illustrates the working of java.util.HashMap.isEmpty() method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the isEmpty() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();          // Mapping int values to string keys        hash_map.put("Geeks", 10);        hash_map.put("4", 15);        hash_map.put("Geeks", 20);        hash_map.put("Welcomes", 25);        hash_map.put("You", 30);          // Displaying the HashMap        System.out.println("The Mappings are: " + hash_map);          // Checking for the emptiness of Map        System.out.println("Is the map empty? " + hash_map.isEmpty());    }}
The Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Is the map empty? false

Program 2: For an empty HashMap
// Java code to illustrate the isEmpty() methodimport java.util.*;  public class Hash_Map_Demo {    public static void main(String[] args)    {          // Creating an empty HashMap        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();          // Displaying the HashMap        System.out.println("The Mappings are: " + hash_map);          // Checking for the emptiness of Map        System.out.println("Is the map empty? " + hash_map.isEmpty());    }}
The Mappings are: {}
Is the map empty? true

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Introduction to Java
Constructors in Java
Initializing a List in Java
C Library - <float.h>

The float.h header file of the C Standard Library contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. They allow making more portable programs. Before checking all the constants, it is good to understand that floating-point number is composed of following four elements −
S
sign ( +/- )
b
base or radix of the exponent representation, 2 for binary, 10 for decimal, 16 for hexadecimal, and so on...
e
exponent, an integer between a minimum emin and a maximum emax.
p
precision, the number of base-b digits in the significand.
Based on the above 4 components, a floating point will have its value as follows −
floating-point = ( S ) p x be

or

floating-point = (+/-) precision x baseexponent

The following values are implementation-specific and defined with the #define directive, but these values may not be any lower than what is given here. Note that in all instances FLT refers to type float, DBL refers to double, and LDBL refers to long double.
FLT_ROUNDS
Defines the rounding mode for floating point addition and it can have any of the following values −
-1 − indeterminable
0 − towards zero
1 − to nearest
2 − towards positive infinity
3 − towards negative infinity
FLT_RADIX 2
This defines the base radix representation of the exponent. A base-2 is binary, base-10 is the normal decimal representation, base-16 is Hex.
FLT_MANT_DIG
DBL_MANT_DIG
LDBL_MANT_DIG
These macros define the number of digits in the number (in the FLT_RADIX base).
FLT_DIG 6
DBL_DIG 10
LDBL_DIG 10
These macros define the maximum number decimal digits (base-10) that can be represented without change after rounding.
FLT_MIN_EXP
DBL_MIN_EXP
LDBL_MIN_EXP
These macros define the minimum negative integer value for an exponent in base FLT_RADIX.
FLT_MIN_10_EXP -37
DBL_MIN_10_EXP -37
LDBL_MIN_10_EXP -37
These macros define the minimum negative integer value for an exponent in base 10.
FLT_MAX_EXP
DBL_MAX_EXP
LDBL_MAX_EXP
These macros define the maximum integer value for an exponent in base FLT_RADIX.
FLT_MAX_10_EXP +37
DBL_MAX_10_EXP +37
LDBL_MAX_10_EXP +37
These macros define the maximum integer value for an exponent in base 10.
FLT_MAX 1E+37
DBL_MAX 1E+37
LDBL_MAX 1E+37
These macros define the maximum finite floating-point value.
FLT_EPSILON 1E-5
DBL_EPSILON 1E-9
LDBL_EPSILON 1E-9
These macros define the least significant digit representable.
FLT_MIN 1E-37
DBL_MIN 1E-37
LDBL_MIN 1E-37
These macros define the minimum floating-point values.
The following example shows the usage of few of the constants defined in float.h file.
#include <stdio.h>
#include <float.h>

int main () {
   printf("The maximum value of float = %.10e\n", FLT_MAX);
   printf("The minimum value of float = %.10e\n", FLT_MIN);

   printf("The number of digits in the number = %.10e\n", FLT_MANT_DIG);
}
Let us compile and run the above program that will produce the following result −
The maximum value of float = 3.4028234664e+38
The minimum value of float = 1.1754943508e-38
The number of digits in the number = 7.2996655210e-312
How to Clone webpage Using pywebcopy in Python?

17 Jan, 2022
Sometimes we need a handy web page on your local hard drive. So, here we are going to write a simple Python script to Scrap a web page. Web scraping is used for extracting data from websites for offline reading, storage, or whatever reason. Before writing the script we need to know pywebcopy. pywebcopy is available on PyPi and is easily installable using pip. Type the below command in the terminal to install this module
pip install pywebcopy
pywebcopy  Python package for cloning complete web pages and websites to local storage.
Approach:
Import pywebcopy
Pass the argument into the save_webpage(url=”...”,project_folder=”path/download”,kwargs)
Check on your given location. 
Below is the implementation.
Python3
from pywebcopy import save_webpage kwargs = {'project_name': 'site folder'} save_webpage(       # url pf the website    url='https://www.geeksforgeeks.org/data-structures/linked-list/',         # folder where the copy will be saved    project_folder='F:/ro/geek',    **kwargs)
 
 
Output:
 
 
The complete clone of the webpage is made and stored in the specified location. 
 
virajmane5439
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Program to sort a given linked list into ascending order in python

Suppose we have a linked list. We have to sort the list into ascending order.
So, if the input is like [5, 8, 4, 1, 5, 6, 3], then the output will be [1, 3, 4, 5, 5, 6, 8, ]
To solve this, we will follow these steps:
values := a new list
head := node
while node is not null, doinsert value of node at the end of valuesnode := next of node
insert value of node at the end of values
node := next of node
sort the list values
values := make a double ended queue by taking elements of values
node := head
while node is not null, dovalue of node := left element of queue and delete element from left of queuenode := next of node
value of node := left element of queue and delete element from left of queue
node := next of node
return head
Let us see the following implementation to get better understanding:
Live Demo
import collections

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next

def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)

   return head

def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')

class Solution:
   def solve(self, node):

   values = []
   head = node
   while node:
      values.append(node.val)
      node = node.next

   values.sort()
   values = collections.deque(values)

   node = head
   while node:
      node.val = values.popleft()
      node = node.next

   return head

ob = Solution()
head = make_list([5, 8, 4, 1, 5, 6, 3])
print_list(ob.solve(head))
[5, 8, 4, 1, 5, 6, 3]
[1, 3, 4, 5, 5, 6, 8, ]
Python | Splitting operators in String

30 Jun, 2019
Sometimes we have a source string to have certain mathematical statement for computations and we need to split both the numbers and operators as a list of individual elements. Let’s discuss certain ways in which this problem can be performed.
Method #1 : Using re.split()This task can be solved using the split functionality provided by Python regex library which has power to split the string according to certain conditions and in this case all numbers and operators.
# Python3 code to demonstrate working of# Splitting operators in String# Using re.split()import re  # initializing string test_str = "15 + 22 * 3-4 / 2"  # printing original string print("The original string is : " + str(test_str))  # Using re.split()# Splitting operators in Stringres = re.split(r'(\D)', test_str)  # printing result print("The list after performing split functionality : " + str(res))
The original string is : 15+22*3-4/2The list after performing split functionality : [’15’, ‘+’, ’22’, ‘*’, ‘3’, ‘-‘, ‘4’, ‘/’, ‘2’]
 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Method #2 : Using re.findall()This Python regex library function also can perform the similar task as the above function. It can also support decimal numbers as additional functionality.
# Python3 code to demonstrate working of# Splitting operators in String# Using re.findall()import re  # initializing string test_str = "15 + 22.6 * 3-4 / 2"  # printing original string print("The original string is : " + str(test_str))  # Using re.findall()# Splitting operators in Stringres = re.findall(r'[0-9\.]+|[^0-9\.]+', test_str)  # printing result print("The list after performing split functionality : " + str(res))
The original string is : 15+22.6*3-4/2The list after performing split functionality : [’15’, ‘+’, ‘22.6’, ‘*’, ‘3’, ‘-‘, ‘4’, ‘/’, ‘2’]
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers