code-rag-bench/online-tutorials huggingface dataset:
Ruby Search and Replace

25 Sep, 2019
sub and gsub string methods that use regular expressions, and their in-place variants are sub! and gsub!. The sub & sub! replaces the first occurrence of the pattern and gsub & gsub! replaces all occurrences. All of these methods perform a search-and-replace operation using a Regexp pattern. sub! and gsub! modify the string on which they are called whereas the sub and gsub returns a new string, leaving the original unmodified.Below is the example to understand it better.
Example :
# Ruby program of sub and gsub method in a string  roll = "2004-959-559 # This is Roll Number"  # Delete Ruby-style commentsroll = roll.sub!(/#.*$/, "")   puts "Roll Num : #{roll}"  # Remove anything other than digitsroll = roll.gsub!(/\D/, "")    puts "Roll Num : #{roll}"
Output :
Roll Num : 2004-959-559 
Roll Num : 2004959559
In above example, we are using sub! and gsub!. here sub! replace first occurrence of the pattern and gsub! replaces all occurrences.
Example :
# Ruby program of sub and gsub methodtext = "geeks for geeks, is a computer science portal"  # Change "rails" to "Rails" throughouttext.gsub!("geeks", "Geeks")  # Capitalize the word "Rails" throughouttext.gsub!(/\bgeeks\b/, "Geeks")puts "#{text}"
Output :
Geeks for Geeks, is a computer science portal
The gsub! method too can be used with a regular expression.
Ruby-Methods
Ruby-String
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?
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Balanced Binary Search Trees - GeeksforGeeks

06 May, 2017
                 a
               /   \
             /      \
            b        c
          /  \      /
         /    \    /
        d     e   g
       /
      /
     h
A
        100
     /      
    50       200
   /           
 10            300


B
           100
       /       
     50        200
    /        /     
  10       150     300
 /
5


C
            100
       /          
     50            200
    /            /     
  10    60       150     300
 /                         
5                   180       400

         60
      /       
    20      100
           /   
         80    120     

A
        70
      /      
    60      100
   /       /    
 20       80    120 

B
        100
      /      
    60      120
   /       /  
 20   70   80   


C
        80
      /      
    60      100
   /         
 20   70      120

D
        80
      /      
    60      100
   /       /   
 20      70    120  
After insertion of 70, tree becomes following
         60
      /     \  
    20      100
           /   \
         80    120     
        /
       70

         60                               60                            80
      /     \       Right Rotate(100)  /      \     Left Rotate(60)   /    \
    20      100    -----------------> 20        80 ---------------> 60      100 
           /   \                              /   \                /  \        \
         80    120                          70     100            20   70       120  
        /                                            \    
      70                                             120 

T1, T2 and T3 are subtrees of the tree rooted with y (on left side) 
or x (on right side)           
                y                               x
               /      Right Rotation          /  
              x   T3   – - – - – - – >        T1   y 
             /        < - - - - - - -            / 
            T1  T2     Left Rotation            T2  T3

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Time Complexity Analysis | Tower Of Hanoi (Recursion)

27 Jan, 2022
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk. 
Pseudo Code  
TOH(n, x, y, z)
{
   if (n >= 1)
   {
      // put (n-1) disk to z by using y
      TOH((n-1), x, z, y)
   
       // move larger disk to right place
       move:x-->y
     
      // put (n-1) disk to right place 
      TOH((n-1), z, y, x)
   }
}
Analysis of Recursion 
Recursive Equation : ——-equation-1 
Solving it by Backsubstitution : ———–equation-2 ———–equation-3 
Put the value of T(n-2) in the equation–2 with help of equation-3 ——equation-4 
Put the value of T(n-1) in equation-1 with help of equation-4 
After Generalization : 
Base condition T(1) =1 n – k = 1 k = n-1put, k = n-1
It is a GP series, and the sum is 
, or you can say which is exponential
for 5 disks i.e. n=5 It will take 2^5-1=31 moves.
vedantmehta
aswini123p
Analysis
Recursion
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between Deterministic and Non-deterministic Algorithms
What is algorithm and why analysis of it is important?
Time-Space Trade-Off in Algorithms
Complexity analysis of various operations of Binary Min Heap
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
C | Macro & Preprocessor | Question 1 - GeeksforGeeks

12 Jan, 2013
#include <stdio.h>#define PRINT(i, limit) do \                        { \                            if (i++ < limit) \                            { \                                printf("GeeksQuiz\n"); \                                continue; \                            } \                        }while(1)  int main(){    PRINT(0, 3);    return 0;}
How many times GeeksQuiz is printed in the above program?(A) 1(B) 3(C) 4(D) Compile-time errorAnswer: (D)Explanation: The PRINT macro gets expanded at the pre-processor time i.e. before the compilation time. After the macro expansion, the if expression becomes: if (0++ < 3). Since 0 is a constant figure and represents only r-value, applying increment operator gives compile-time error: lvalue required. lvalue means a memory location with some address.
C-Macro & Preprocessor
Macro & Preprocessor
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1
Displaying bar graphs using Matplotlib

In this program, we will plot a bar graph using the matplotlib library. The most important Step in solving matplotlib related problems using the matplotlib library is importing the matplotlib library. The syntax is −
import matplotlib.pyplot as plt
Pyplot is a collection of command style functions that make Matplotlib work like MATLAB
Step 1: Define a list of values.
Step 2: Use the bar() function in the matplotlib.pyplot library and define different parameters like height, width, etc.
Step 3: Label the axes using xlabel() and ylabel().
Step 3: Plot the graph using show().
import matplotlib.pyplot as plt

data_x = ['Mumbai', 'Delhi', 'Ahmedabad', 'Banglore']
data_y = [40, 35, 29, 32]

plt.xlabel("CITY")
plt.ylabel("POPULATION")
plt.title("BAR PLOT")

plt.bar(data_x, data_y, color='red')
plt.show()
How does JavaScript focus() method works?

Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.  
element.focus(options);
In the following example, initially, the text "Tutorialspoint" is in an anchor tag 'a', which as an id called 'focus'. Later on, a function is declared in which the id is called using a DOM method and focus() method is applied on it to change the color of text "Tutorialspoint" to red. Here a button is used for the click event.
Live Demo
<html>
<head>
<style>
   a:focus, a:active {
      color: red;
   }
</style>
</head>
<body>
<a href="http://www.tutorialspoint.com/" id="focus">Tutorialspoint</a>
<input type="button" value="getfocus" onclick="getfo()">
<script>
   function getfo() {
      document.getElementById("focus").focus();
   }
</script>
</body>
</html>
After executing the above code we will get the following image displayed on the screen.
Once we click on the get focus button we will get the following output.
NLP | Using dateutil to parse dates. - GeeksforGeeks

18 Jun, 2019
The parser module can parse datetime strings in many more formats. There can be no better library than dateutil to parse dates and times in Python. To lookup the timezones, the tz module provides everything. When these modules are combined, they make it very easy to parse strings into timezone-aware datetime objects.
Installation :dateutil can be installed using pip or easy_install, that is, sudo pip install dateutil==2.0 or sudo easy_install dateutil==2.0. 2.0 version for Python 3 compatibility is required. The complete documentation can be found at http://labix.org/python-dateutil.
Code: Parsing Examples
# importing libraryfrom dateutil import parser  print (parser.parse('Thu Sep 25 10:36:28 2010'))  print (parser.parse('Thursday, 25. September 2010 10:36AM'))  print (parser.parse('9 / 25 / 2010 10:36:28'))  print (parser.parse('9 / 25 / 2010'))  print (parser.parse('2010-09-25T10:36:28Z'))
Output :
datetime.datetime(2010, 9, 25, 10, 36, 28)
datetime.datetime(2010, 9, 25, 10, 36)
datetime.datetime(2010, 9, 25, 10, 36, 28)
datetime.datetime(2010, 9, 25, 0, 0)
datetime.datetime(2010, 9, 25, 10, 36, 28, tzinfo=tzutc())
All it takes is importing the parser module and calling the parse() function with a datetime string. The parser can return a sensible datetime object, but it cannot parse the string, it will raise a ValueError.How it works :
The parser instead of looking for recognizable tokens, guess what those tokens refer to. It doesn’t use regular expressions.
The order of these tokens matters as it uses a date format that looks like Month/Day/Year (the default order), while others use a Day/Month/Year format.
The parse() function takes an optional keyword argument, dayfirst, which defaults to False to deal with this problem.
It can correctly parse dates in the latter format if it is set to True.
parser.parse('16 / 6/2019', dayfirst = True)
Output :
datetime.datetime(2016, 6, 16, 0, 0)
Another ordering issue can occur with two-digit years. but ’11-6-19′ is an ambiguous date format. Since dateutil defaults to the Month-Day-Year format, ’11-6-19′ is parsed to the year 2019. But if yearfirst = True is passed into parse(), it can be parsed to the year 2011.
print (parser.parse('11-6-19'))print (parser.parse('10-6-25', yearfirst = True))
Output :
datetime.datetime(2019, 11, 6, 0, 0)
datetime.datetime(2011, 6, 19, 0, 0)
dateutil parser can also do fuzzy parsing and allows to ignore extraneous characters in a datetime string. parse() will raise a ValueError with the default value of False, when it encounters unknown tokens. A datetime object can usually be returned, if fuzzy = True.
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Dart - Standard Input Output - GeeksforGeeks

30 Jun, 2021
In Dart programming language, you can take standard input from the user through the console via the use of .readLineSync() function. To take input from the console you need to import a library, named dart:io from libraries of Dart. 
About Stdin Class: 
This class allows the user to read data from standard input in both synchronous and asynchronous ways. The method readLineSync() is one of the methods used to take input from the user. Refer to the official doc for other methods, from here. 
Taking a string input from user:
Dart
// importing dart:io fileimport 'dart:io'; void main(){    print("Enter your name?");    // Reading name of the Geek    String? name = stdin.readLineSync();     // Printing the name    print("Hello, $name! \nWelcome to GeeksforGeeks!!");}
Input: 
Geek
Output: 
Enter your name?
Hello, Geek! 
Welcome to GeeksforGeeks!!
Taking integer value as input: 
Dart
// Importing dart:io fileimport 'dart:io'; void main(){    // Asking for favourite number    print("Enter your favourite number:");    // Scanning number    int? n = int.parse(stdin.readLineSync()!);   // Here ? and ! are for null safety     // Printing that number    print("Your favourite number is $n");}
Input: 
01
Output: 
Enter your favourite number:
Your favourite number is 1
 
In dart, there are two ways to display output in the console: 
Using print statement.Using stdout.write() statement.
Using print statement.
Using stdout.write() statement.
Printing Output in two different ways:
Dart
import 'dart:io'; void main(){    // Printing in first way    print("Welcome to GeeksforGeeks! // printing from print statement");     // Printing in second way    stdout.write("Welcome to GeeksforGeeks! // printing from stdout.write()");}
Output:  
Welcome to GeeksforGeeks! // printing from print statement
Welcome to GeeksforGeeks! // printing from stdout.write()
Note: The print() statement brings the cursor to next line while stdout.write() don’t bring the cursor to the next line, it remains in the same line.If the print statements are switched in the above program then:  
Output: 
Welcome to GeeksforGeeks! // printing from stdout.write()Welcome to GeeksforGeeks! // printing from print statement
Making a simple addition program:
Dart
import 'dart:io'; void main(){    print("-----------GeeksForGeeks-----------");    print("Enter first number");    int? n1 = int.parse(stdin.readLineSync()!);     print("Enter second number");    int? n2 = int.parse(stdin.readLineSync()!);     // Adding them and printing them    int sum = n1 + n2;    print("Sum is $sum");}
Input: 
11
12
Output: 
-----------GeeksForGeeks-----------
Enter first number
Enter second number
Sum is 23
almostsagar
rajatrrpalankar
Dart-IO
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
Dart Tutorial
Container class in Flutter
Flutter - Stack Widget
Operators in Dart
How to change the size of figures drawn with matplotlib? - GeeksforGeeks

26 May, 2021
The main purpose of matplotlib is to create a figure representing data. The use of visualizing data is to tell stories by curating data into a form easier to understand, highlighting the trends and outliers. We can populate the figure with all different types of data, including axes, a graph plot, a geometric shape, etc. “When” we plot graphs we may want to set the size of a figure to a certain size. You may want to make the figure wider in size, taller in height, etc.
This can be achieved by an attribute of matplotlib known as figsize. The figsize attribute allows us to specify the width and height of a figure in unit inches.
 Syntax:
import matplotlib.pyplot as plt
figure_name = plt.figure(figsize=(width, height))
The figsize attribute is a parameter of the function figure(). It is an optional attribute, by default the figure has the dimensions as (6.4, 4.8). This is a standard plot where the attribute is not mentioned in the function. 
Normally each unit inch is of 80 x 80 pixels. The number of pixels per unit inch can be changed by the parameter dpi, which can also be specified in the same function.
Approach:
We create a variable plt_1, and set it equal to, plt.figure(figsize=(6,3)).
This creates a figure object, which has a width of 6 inches and 3 inches in height.
The values of the figsize attribute are a tuple of 2 values.
Example 1:
Python3
# We start by importing matplotlibimport matplotlib.pyplot as plt # Plotting a figure of width 6 and height 3plt_1 = plt.figure(figsize=(6, 3)) # Let's plot the equation y=2*xx = [1, 2, 3, 4, 5] # y = [2,4,6,8,10]y = [x*2 for x in x] # plt.plot() specifies the arguments for x-axis# and y-axis to be plottedplt.plot(x, y) # To show this figure object, we use the line,# fig.show()plt.show()
Output:
This works if you’re using a python IDE other than jupyter notebooks. If you are using  
jupyter notebooks, then you would not use, plt.show(). Instead, you would specify in the  
Code right after importing matplotlib, %matplotlib inline.
Example 2:
To see the dynamic nature of figure sizing in matplotlib, now we to create a figure with the dimensions inverted. The height will now be double the size of the width.
Python3
# We start by importing matplotlibimport matplotlib.pyplot as plt # Plotting a figure of width 3 and height 6plt_1 = plt.figure(figsize=(3, 6)) # Let's plot the equation y=2*xx = [1, 2, 3, 4, 5] # y = [2,4,6,8,10]y = [x*2 for x in x] # plt.plot() specifies the arguments for# x-axis and y-axis to be plottedplt.plot(x, y) # To show this figure object, we use the line,# fig.show()plt.show()
Output:
simranarora5sos
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
PostgreSQL - Change Column Type - GeeksforGeeks

28 Aug, 2020
In this article, we will discuss the step by step process of changing the data type of a column using the ALTER TABLE statement in PostgreSQL.
Syntax:
ALTER TABLE table_name
ALTER COLUMN column_name [SET DATA] TYPE new_data_type;
Let’s analyze the above syntax:
First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause.
Second, give the name of column whose data type will be changed in the ALTER COLUMN clause.
Third, provide the new data type for the column after the TYPE keyword. It is possible to use either SET DATA TYPE or TYPE.
Example:Let’s create a table (say, assets) and insert a few rows into it for the demonstration using the below statement:
CREATE TABLE assets (
    id serial PRIMARY KEY,
    name TEXT NOT NULL,
    asset_no VARCHAR NOT NULL,
    description TEXT,
    LOCATION TEXT,
    acquired_date DATE NOT NULL
);

INSERT INTO assets (
    NAME,
    asset_no,
    location,
    acquired_date
)
VALUES
    (
        'Server',
        '10001',
        'Server room',
        '2020-01-01'
    ),
    (
        'UPS',
        '10002',
        'Server room',
        '2020-05-16'
);
Now we will change the data type of the name column to VARCHAR, using the below statement:
ALTER TABLE assets ALTER COLUMN name TYPE VARCHAR;
Now we change the data type of description and location columns from TEXT to VARCHAR using the below statement:
ALTER TABLE assets 
    ALTER COLUMN location TYPE VARCHAR,
    ALTER COLUMN description TYPE VARCHAR;
Now we check the table for the changes made using the below statement:
SELECT * FROM assets;
Output:
postgreSQL-dataTypes
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - Identity Column
PostgreSQL - SELECT
PostgreSQL - ROW_NUMBER Function
ZoneId systemDefault() method in Java with Examples - GeeksforGeeks

19 Aug, 2019
The systemDefault() method of the ZoneId class in Java is used to return the system default time-zone.
Syntax:
public String systemDefault()

Parameters: This method does not accepts any parameters.
Return Value: This method returns the zone ID.
Exceptions: This method throws following exception:
DateTimeException – It throws this exception if the converted zone ID has an invalid format.
ZoneRulesException – It throws this exception if the converted zone region ID cannot be found.
Below programs illustrate the systemDefault() method:Program 1:
// Java program to demonstrate// ZoneId.systemDefault() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create ZoneId object        ZoneId zoneId            = ZoneId.systemDefault();          // printresult        System.out.println("ZoneId: "                           + zoneId);    }}
ZoneId: Etc/UTC

Program 2:
// Java program to demonstrate// ZoneId.systemDefault() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create ZoneId object        ZoneId zoneId            = ZoneId.systemDefault();          if (zoneId.getId().equals("Etc/UTC"))            System.out.println("This zone is Etc/UTC");        else            System.out.println("This zone is not Etc/UTC");    }}
This zone is Etc/UTC

References:https://docs.oracle.com/javase/10/docs/api/java/time/ZoneId.html#systemDefault()
Akanksha_Rai
Java-Functions
Java-time package
Java-ZoneId
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
C++ Switch

Use the switch statement to select one of many code blocks to be executed.
This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
When C++ reaches a break 
keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside 
the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
A break can save a lot of execution time because it "ignores" the execution 
of all the rest of the code in the switch block.
The default keyword specifies some code to run if there is no 
case match:
Note: The default keyword must be used as the last statement 
in the switch, and it does not need a break.
Insert the missing parts to complete the following switch statement.
int day = 2;
switch () {
 1:
    cout << "Saturday";
    break;
 2:
    cout << "Sunday";
    ;
}

Start the Exercise
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.
Moving X-axis in Matplotlib during real-time plot

To move X-axis in Matplotlib during real-time plot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Create x and y data points using numpy.
Plot x and y data points using plot() method.
Make an animation by repeatedly calling a function *animate* that moves the X-axis during real-time plot.
To display the figure, use show() method.
import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np

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

fig, ax = plt.subplots()

x = np.linspace(0, 15, 100)
y = np.cos(x)

ax.plot(x, y, lw=2, color='red')

def animate(frame):
   ax.set_xlim(left=0, right=frame)

ani = animation.FuncAnimation(fig, animate, frames=10)

plt.show()
How to add space before and after specific character using regex in Python?

The following code shows how space is added before and after the pipe '|' character in given string. 
import re
regex = r'\b[|:]\b'
s = "abracadabra abraca|dabara | abra cadabra abra ca dabra abra ca dabra abra"
print(re.sub(regex, ' \g<0> ', s))
This gives the output
abracadabra abraca | dabara | abra cadabra abra ca dabra abra ca dabra abra
Angular Material 7 - Select

The <mat-select>, an Angular Directive, is used for <select> for enhance material design based styling..
In this chapter, we will showcase the configuration required to draw a select 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 {MatSelectModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatSelectModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified ts file app.component.ts.
import { Component } from '@angular/core';
import { FormControl } from "@angular/forms";
export interface Food {
  value: string;
  display: string;
}
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'materialApp'; 
   selectedValue: string; 
   foods: Food[] = [
      {value: 'steak', display: 'Steak'},
      {value: 'pizza', display: 'Pizza'},
      {value: 'tacos', display: 'Tacos'}
   ];
}
Following is the content of the modified HTML host file app.component.html.
<form>
   <h4>mat-select</h4>
   <mat-form-field>
      <mat-select placeholder = "Favorite food" 
         [(ngModel)] = "selectedValue" name = "food">
         <mat-option *ngFor = "let food of foods" 
            [value] = "food.value">
            {{food.display}}
         </mat-option>
      </mat-select>
   </mat-form-field>
   <p> Selected food: {{selectedValue}} </p> 
</form>
Verify the result.
As first, we've created a select using mat-select bound with ngModel.
As first, we've created a select using mat-select bound with ngModel.
Then, we've added options using mat-option.
Then, we've added options using mat-option.

    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
Tryit Editor v3.7

CSS 2D Transforms
Tryit: The scale() method
How to find the minimum and maximum values in a single MySQL Query?

To find the minimum and maximum values in a single query, use MySQL UNION. Let us first create a table −
mysql> create table DemoTable
(
   Price int
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(120);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Price |
+-------+
| 88    |
| 100   |
| 98    |
| 120   |
+-------+
4 rows in set (0.00 sec)
Following is the query to find the minimum and maximum values in a single MySQL Query −
mysql> select Price from DemoTable where Price=(select min(Price) from DemoTable)
   UNION
   select Price from DemoTable where Price=(select max(Price) from DemoTable);
This will produce the following output −
+-------+
| Price |
+-------+
| 88    |
| 120   |
+-------+
2 rows in set (0.00 sec)
How to check if two strings are equal in Java?

You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
import java.lang.*
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "Tutorialspoint";
      String str2 = "Tutorialspoint";
      String str3 = "Hi";
     
      // checking for equality
      boolean retval1 = str2.equals(str1);
      boolean retval2 = str2.equals(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}
str2 is equal to str1 = true
str2 is equal to str3 = false
What is dot operator in C++?

The dot and arrow operator are both used in C++ to access the members of a class. They are just used in different scenarios. In C++, types declared as a class, struct, or union are considered "of class type". So the following refers to both of them.
a.b is only used if b is a member of the object (or reference[1] to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class.
a →b is essentially a shorthand notation for (*a).b, ie, if a is a pointer to an object, then a →b is accessing the property b of the object that points to.
Note that . is not overloadable. → is an overloadable operator, so we can define our own function(operator →()) that should be called when this operator is used. so if a is an object of a class that overloads operator → (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented.
[1] References are, semantically, aliases to objects, so I should have added "or reference to a pointer" to the #3 as well. However, I thought this would be more confusing than helpful since references to pointers (T*&) are rarely ever used.
#include<iostream>
class A {
   public: int b;
   A() { b = 5; }
};
int main() {
   A a = A();
   A* x = &a;
   std::cout << "a.b = " << a.b << "\n";
   std::cout << "x->b = " << x->b << "\n";
   return 0;
}
This will give the output −
5
5
How to change files and folders attributes using PowerShell?

There are multiple files and folders attribute supported by the Windows Operating System. To check which attributes that files and folders support use DOS command attrib /?
You can see the attributes listed like Read-Only, Archive, etc. You can set the attribute using PowerShell.
For example, we have a file called TestFile.txt and its attribute is ReadOnly and we need to change it to the Archive.
PS C:\> (Get-ChildItem C:\Temp\TestFile.txt).Attributes
ReadOnly
Change Attribute code −
$file = Get-ChildItem C:\Temp\TestFile.txt
$file.Attributes = 'Archive'
So we have set the attribute to the ‘Archive’ from ‘ReadOnly’ and when you check it, the attribute should be changed.
PS C:\> (Get-ChildItem C:\Temp\TestFile.txt).Attributes
Archive
To set the multiple attributes, you can separate the values by a comma. For example,
$file = Get-ChildItem C:\Temp\TestFile.txt
$file.Attributes = 'Archive','ReadOnly'
(Get-ChildItem C:\Temp\TestFile.txt).Attributes
ReadOnly, Archive
Similar way you can change the attributes of the folder. For example,
$folder = Get-Item C:\Temp
$folder.Attributes = 'Directory','Hidden'
We will check the folder attributes now. This folder is hidden so we need to use -Hidden parameter.
PS C:\> (Get-ChildItem C:\Temp\ -Hidden).Attributes
Hidden, Directory
To change attributes on the multiple files in the same folder, you need to use foreach loop. For example,
Get-ChildItem C:\Test1\ -Recurse | foreach{$_.Attributes = 'Hidden'}
When we check their values, they should be hidden.
PS C:\> Get-ChildItem C:\Test1 -Recurse -Force

Directory: C:\Test1

Mode      LastWriteTime     Length Name
----      -------------     ------ ----
---h--    8/28/2020 7:27 AM 11 File1.txt
---h--    8/28/2020 7:49 AM 11 File2.txt
-Recurse parameter is to retrieve the data from subfolders. If you need only parent folder data attribute change then remove -Recure parameter.
Differences between orTimeout() and completeOnTimeOut() methods in Java 9?

Both orTimeout() and completeOnTimeOut() methods are defined in CompletableFuture class and these two methods are introduced in Java 9. The orTimeout() method can be used to specify that if a given task doesn't complete within a certain period of time, the program stops execution and throws TimeoutException whereas completeOnTimeOut() method completes the CompletableFuture with the provided value. If not, it complete before the given timeout.
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class OrTimeoutMethodTest {
   public static void main(String args[]) throws InterruptedException {
      int a = 10;
      int b = 15;
      CompletableFuture.supplyAsync(() -> {
         try {
            TimeUnit.SECONDS.sleep(5);
         } catch(InterruptedException e) {
            e.printStackTrace();
         }
         return a + b;
      })
      .orTimeout(4, TimeUnit.SECONDS)
      .whenComplete((result, exception) -> {
         System.out.println(result);
         if(exception != null)
            exception.printStackTrace();
      });
      TimeUnit.SECONDS.sleep(10);
   }
}
25

public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class CompleteOnTimeOutMethodTest {
   public static void main(String args[]) throws InterruptedException {
      int a = 10;
      int b = 15;
      CompletableFuture.supplyAsync(() -> {
         try {
            TimeUnit.SECONDS.sleep(5);
         } catch(InterruptedException e) {
            e.printStackTrace();
         }
         return a + b;
      })
      .completeOnTimeout(0, 4, TimeUnit.SECONDS)
      .thenAccept(result -> System.out.println(result));
      TimeUnit.SECONDS.sleep(10);
   }
}
25
isprintable() in Python and its application

In this article, we will learn about isprintable() in Python and its application.
Is printable() is a built-in method used for the purpose of string handling. The isprintable() methods return “True” when all characters present in the string are of type printable or the string is empty, Otherwise, It returns a boolean value of “False”.
Arguments − It doesn’t take any argument when called
List of printable characters include digits, letter, special symbols & spaces.
Let’s look at this illustration to check that whether the characters of string are printable or not.
 Live Demo
# checking for printable characters
st= 'Tutorialspoint'
print(st.isprintable())
# checking if \n is a printable character
st= 'Tutorials \n point'
print(st.isprintable())
# checking if space is a printable character
string = ''
print( string.isprintable())
True
False
True
 Live Demo
# checking for printable characters
st= 'Tutorials$$point&&'
print(st.isprintable())
# checking if \t is a printable character
st= 'Tutorials \t point'
print(st.isprintable())
# checking if underscore is a printable character
string = '_'
print( string.isprintable())
True
False
True
To rectify the error of printing error at runtime we can handle this exception and replace all non-printable characters with the desired symbol to print onto the console
To rectify the error of printing error at runtime we can handle this exception and replace all non-printable characters with the desired symbol to print onto the console
This is also useful when we have to format the output in a specific manner so as to remove the unwanted things like escape sequences
This is also useful when we have to format the output in a specific manner so as to remove the unwanted things like escape sequences
In this article, we learnt about the isprintable() function and its application in Python 3.x. Or earlier.
Handle mouse events in Python - OpenCV - GeeksforGeeks

26 Mar, 2020
OpenCV is one of the most popular computer vision libraries. If you want to start your journey in the field of computer vision, then a thorough understanding of the concepts of OpenCV is of paramount importance.
Note: For more information, refer to Introduction to OpenCV
OpenCV sometimes helps to control and manage different types of mouse events and gives us the flexibility to manage them. There can be different types of mouse events such as left button click, right button click, double_click, etc. To manage these events we need to design callback functions for each type of mouse click event while the window or frame is opened by OpenCV.The callback function will be helpful to implement what type of functionality you want with a particular mouse click event.
Below is the code to show how we can perform operations with a right click and left click events.
Code:
import cv2    # read imageimg = cv2.imread('image.jpg')  # show imagecv2.imshow('image', img)   #define the events for the# mouse_click.def mouse_click(event, x, y,                 flags, param):          # to check if left mouse     # button was clicked    if event == cv2.EVENT_LBUTTONDOWN:                  # font for left click event        font = cv2.FONT_HERSHEY_TRIPLEX        LB = 'Left Button'                  # display that left button         # was clicked.        cv2.putText(img, LB, (x, y),                     font, 1,                     (255, 255, 0),                     2)         cv2.imshow('image', img)                        # to check if right mouse     # button was clicked    if event == cv2.EVENT_RBUTTONDOWN:                   # font for right click event        font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX        RB = 'Right Button'                  # display that right button         # was clicked.        cv2.putText(img, RB, (x, y),                    font, 1,                     (0, 255, 255),                    2)        cv2.imshow('image', img)  cv2.setMouseCallback('image', mouse_click)   cv2.waitKey(0)  # close all the opened windows.cv2.destroyAllWindows()
Output:
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Python | Column wise sum of nested list

07 Aug, 2020
Given a nested list (where sublists are of equal length), write a Python program to find the column-wise sum of the given list and return it in a new list.
Examples:
Input : [[1, 5, 3],
         [2, 7, 8],
         [4, 6, 9]]
Output : [7, 18, 20]

Input : [[20, 5],
         [2, 54],
         [45, 9], 
         [72, 3]]
Output : [139, 71]

Method #1 : zip using list comprehension
We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension.
# Python3 program to Column wise sum of nested list  def column_sum(lst):           return [sum(i) for i in zip(*lst)]      # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))
[7, 18, 20]

 
Method #2 : Using map() method
Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly.
# Python3 program to Column wise sum of nested list  def column_sum(lst):          return list(map(sum, zip(*lst)))      # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))
[7, 18, 20]

 Method #3 : Using numpy.sum()
numpy.sum() function returns the sum of array elements over the specified axis.
# Python3 program to Column wise sum of nested listfrom numpy import array  def column_sum(lst):    arr = array(lst)    return sum(arr, 0).tolist()      # Driver codelst = [[1, 5, 3], [2, 7, 8], [4, 6, 9]]print(column_sum(lst))
[7, 18, 20]

Akanksha_Rai
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.isfortran() in Python

29 Nov, 2018
numpy.isfortran(array) : This is a logical function that checks whether array is Fortran contiguous or not.
Order : [C-contiguous, F-contiguous, A-contiguous; optional]
C-contiguous order in memory(last index varies the fastest). C order means that operating row-rise on the array will be slightly quicker.FORTRAN-contiguous order in memory (first index varies the fastest). F order means that column-wise operations will be faster.‘A’ means to read / write the elements in Fortran-like index order if, array is Fortran contiguous in memory, C-like order otherwise.
Parameters :
array    : [array_like]Input array 

Return :
True, if array is Fortran; else False

Code 1 :
# Python program explaining# isfortran() functionimport numpy as np  in_array = np.array([[1, 2, 3], [4, 5, 6]], order='C')print ("Input array : \n", in_array)  exp2_values = np.exp2(in_array)print ("\nisfortran : ", np.isfortran(in_array))
Output :
Input array : 
 [[1 2 3]
 [4 5 6]]

isfortran :  False

 Code 2 :
# Python program explaining# isfortran() functionimport numpy as np  in_array = np.array([[1, 2, 3], [4, 5, 6]], order='F')print ("Input array : \n", in_array)  exp2_values = np.exp2(in_array)print ("\nisfortran : ", np.isfortran(in_array))
Output :
Input array : 
 [[1 2 3]
 [4 5 6]]

isfortran :  True
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isfortran.html#numpy.isfortran.
Python numpy-Logic Functions
Python-numpy
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Create a Pandas DataFrame from Lists
Python | Pandas Series.filter()

13 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.filter() function returns subset rows or columns of dataframe according to labels in the specified index. Please note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index.
Syntax: Series.filter(items=None, like=None, regex=None, axis=None)
Parameter :items : List of axis to restrict to (must not all be present).like : Keep axis where “arg in col == True”.regex : Keep axis with re.search(regex, col) == True.axis : The axis to filter on. By default this is the info axis, ‘index’ for Series, ‘columns’ for DataFrame.
Returns : same type as input object
Example #1: Use Series.filter() function to filter out some values in the given series object using a regular expressions.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.filter() function to filter those values from the given series object whose index label name has a space in its name.
# filter valuesresult = sr.filter(regex = '. .')  # Print the resultprint(result)
Output :As we can see in the output, the Series.filter() function has successfully returned the desired values from the given series object. Example #2 : Use Series.filter() function to filter out some values in the given series object using a list of index labels.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])  # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :Now we will use Series.filter() function to filter the values corresponding to the passed index labels in the given series object.
# filter valuesresult = sr.filter(items = ['City 2', 'City 4'])  # Print the resultprint(result)
Output :As we can see in the output, the Series.filter() function has successfully returned the desired values from the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2007 | Question 77

28 Jun, 2021
Suppose the letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. What is the average length of Huffman codes?(A) 3(B) 2.1875(C) 2.25(D) 1.9375Answer: (D)Explanation: We get the following Huffman Tree after applying Huffman Coding Algorithm. The idea is to keep the least probable characters as low as possible by picking them first.
The letters a, b, c, d, e, f have probabilities 
1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. 

                 1
               /   \
              /     \
             1/2    a(1/2)
            /  \
           /    \
          1/4  b(1/4) 
         /   \
        /     \
       1/8   c(1/8) 
      /  \
     /    \
   1/16  d(1/16)
  /  \
 e    f
The average length = (1*1/2 + 2*1/4 + 3*1/8 + 4*1/16 + 5*1/32 + 5*1/32)
                   = 1.9375 

Quiz of this Question
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2014-(Set-1) | Question 51