code-rag-bench/online-tutorials huggingface dataset:
Python | Get dictionary keys as a list

28 Jan, 2019
Given a dictionary, write a Python program to get the dictionary keys as a list.
Examples:
Input : {1:'a', 2:'b', 3:'c'}
Output : [1, 2, 3]

Input : {'A' : 'ant', 'B' : 'ball'}
Output : ['A', 'B']

 
Approach #1 : Using dict.keys() [For Python 2.x]
# Python program to get # dictionary keys as list  def getList(dict):    return dict.keys()      # Driver programdict = {1:'Geeks', 2:'for', 3:'geeks'}print(getList(dict))
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.
[1, 2, 3]

 Approach #2 : Naive approach.
# Python program to get # dictionary keys as list  def getList(dict):    list = []    for key in dict.keys():        list.append(key)              return list      # Driver programdict = {1:'Geeks', 2:'for', 3:'geeks'}print(getList(dict))
[1, 2, 3]

 Approach #3 : Typecasting to list
# Python program to get # dictionary keys as list  def getList(dict):          return list(dict.keys())      # Driver programdict = {1:'Geeks', 2:'for', 3:'geeks'}print(getList(dict))
[1, 2, 3]

 Approach #4 : Unpacking with *Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.
# Python program to get # dictionary keys as list  def getList(dict):          return [*dict]      # Driver programdict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'}print(getList(dict))
['c', 'a', 'b']

 Approach #5 : Using itemgetteritemgetter from operator module return a callable object that fetches item from its operand using the operand’s __getitem__() method. This method is then mapped to dict.items() and them typecasted to list.
# Python program to get # dictionary keys as listfrom operator import itemgetter  def getList(dict):          return list(map(itemgetter(0), dict.items()))      # Driver programdict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'}print(getList(dict))
['b', 'a', 'c']

Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Ruby | Hash select() method

07 Jan, 2020
Hash#select() : select() is a Hash class method which finds the array from the hash based on the block condition.
Syntax: Hash.select()
Parameter: Hash valuesblock condition
Return: array from the hash based on the block condition.
Example #1 :
# Ruby code for Hash.select() method  # declaring Hash valuea = { "a" => 100, "b" => 200 }  # declaring Hash valueb = {"a" => 100}  # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200}    # select Valueputs "Hash a select form : #{a.select {|key, value| key < "b"}}\n\n"
Output :
Hash a select form : {"a"=>100}


Example #2 :
# Ruby code for Hash.select() method  # declaring Hash valueb = {"a" => 100}  # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200}    # select Value  puts "Hash b select form : #{b.select{|key, value| value < 200}}\n\n"  puts "Hash c select form : #{c.select{|key, value| key < "b"}}\n\n"
Output :
Hash b select form : {"a"=>100}

Hash c select form : {"a"=>100}

Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Palindromic Subsequence

Longest Palindromic Subsequence is the subsequence of a given sequence, and the subsequence is a palindrome.
In this problem, one sequence of characters is given, we have to find the longest length of a palindromic subsequence.
To solve this problem, we can use the recursive formula,
If L (0, n-1) is used to store a length of longest palindromic subsequence, thenL (0, n-1) := L (1, n-2) + 2 (When 0'th and (n-1)'th characters are same).
Input:
A string with different letters or symbols. Say the input is “ABCDEEAB”
Output:
The longest length of the largest palindromic subsequence. Here it is 4.
ABCDEEAB. So the palindrome is AEEA.
palSubSeqLen(str)
Input − The given string.
Output − Length of longest palindromic subsequence.
Begin
   n = length of the string
   create a table called lenTable of size n x n and fill with 1s
   for col := 2 to n, do
      for i := 0 to n – col, do
         j := i + col – 1
         if str[i] = str[j] and col = 2, then
            lenTable[i, j] := 2
         else if str[i] = str[j], then
            lenTable[i, j] := lenTable[i+1, j-1] + 2
         else
            lenTable[i, j] := maximum of lenTable[i, j-1] and lenTable[i+1, j]
      done
   done
   return lenTable[0, n-1]
End
#include<iostream>
using namespace std;

int max (int x, int y) {
   return (x > y)? x : y;
}

int palSubseqLen(string str) {
   int n = str.size();
   int lenTable[n][n];            // Create a table to store results of subproblems

   for (int i = 0; i < n; i++)
      lenTable[i][i] = 1;             //when string length is 1, it is palindrome

   for (int col=2; col<=n; col++) {
      for (int i=0; i<n-col+1; i++) {
         int j = i+col-1;
         if (str[i] == str[j] && col == 2)
            lenTable[i][j] = 2;
         else if (str[i] == str[j])
            lenTable[i][j] = lenTable[i+1][j-1] + 2;
         else
            lenTable[i][j] = max(lenTable[i][j-1], lenTable[i+1][j]);
      }
   }
   return lenTable[0][n-1];
}

int main() {
   string sequence = "ABCDEEAB";
   int n = sequence.size();
   cout << "The length of the longest palindrome subsequence is: " << palSubseqLen(sequence);
}
The length of the longest palindrome subsequence is: 4
C program to copy contents of one file to another file - GeeksforGeeks

20 May, 2017
#include <stdio.h>#include <stdlib.h> // For exit()  int main(){    FILE *fptr1, *fptr2;    char filename[100], c;      printf("Enter the filename to open for reading \n");    scanf("%s", filename);      // Open one file for reading    fptr1 = fopen(filename, "r");    if (fptr1 == NULL)    {        printf("Cannot open file %s \n", filename);        exit(0);    }      printf("Enter the filename to open for writing \n");    scanf("%s", filename);      // Open another file for writing    fptr2 = fopen(filename, "w");    if (fptr2 == NULL)    {        printf("Cannot open file %s \n", filename);        exit(0);    }      // Read contents from file    c = fgetc(fptr1);    while (c != EOF)    {        fputc(c, fptr2);        c = fgetc(fptr1);    }      printf("\nContents copied to %s", filename);      fclose(fptr1);    fclose(fptr2);    return 0;}
Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
Contents copied to b.txt 
cpp-file-handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Substring in C++
Command line arguments in C/C++
Function Pointer in C
Different methods to reverse a string in C/C++
Structures in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
std::string class in C++
Adding Straight Lines to a Plot in R Programming - abline() Function - GeeksforGeeks

14 Jul, 2020
abline() function in R Language is used to add one or more straight lines to a graph. The abline() function can be used to add vertical, horizontal or regression lines to plot.
Syntax:abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)
Parameters:a, b: It specifies the intercept and the slope of the lineh: specifies y-value for horizontal line(s)v: specifies x-value(s) for vertical line(s)
Returns: a straight line in the plot
Example 1: To add a vertical line to the plot
# add line to square plot # first example : Add one lineplot(cars)abline(v = 16, col = "darkgreen")  # second example : add 2 lines # addline to square plot # change line colors, sizes and typesplot(cars)abline(v = c(16, 22), col = c("darkgreen", "blue"),                      lty = c(1, 2), lwd = c(1, 3))  # third exampleset.seed(1200); mydata<-rnorm(180)hist(mydata, col="darkgreen")  # lwd=line width, lty =linetype abline(v = mean(mydata), col = "blue", lwd = 4, lty = 4) 
Output:
Here, in above example straight line is added using abline() to different graphical plots
Example 2: To add a horizontal line
# R program to add a horizontal line# to a plot  # Creating a plotplot(cars)  # Calling abline() functionabline(h = 60, col = "darkgreen")
Output:
In above example abline() Function draws an horizontal line on the current plot at the specified ‘x’ coordinates.
Example 3: To add a regression line
par(mgp = c(2, 1, 0), mar = c(3, 3, 1, 1))  # Fit regression linerequire(stats)reg<-lm(dist ~ speed, data = cars)coeff = coefficients(reg)  # equation of the line : eq = paste0("y = ", round(coeff[1], 1), "*x ",                     round(coeff[2], 1))  # plotplot(cars, main = eq)abline(reg, col = "darkgreen")
Output:
In the above example, straight-line is added using the line equation and abline() function and plot relation between speed and distance.
R Plot-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to convert dot to comma for numerical columns in an R data frame?

Most European countries use a comma in place of a decimal. Therefore, if we have a data set that contains dot as a decimal market and we need to use that four such European countries or if dot is recorded in place of comma then we can replace the dot with comma using format function as shown in the below examples.
 Live Demo
Consider the below data frame −
x1<−sample(c(1.1,1.25,1.57,2.1,2.4),20,replace=TRUE)
y1<−sample(c(20.24,21.27,20.4,20.5,20.37),20,replace=TRUE)
df1<−data.frame(x1,y1)
df1
   x1    y1
1 2.40 20.50
2 2.40 20.50
3 1.25 20.40
4 2.40 20.50
5 2.10 20.24
6 1.57 20.37
7 2.10 20.37
8 2.10 21.27
9 1.25 20.50
10 1.10 20.40
11 1.25 20.40
12 2.40 20.50
13 2.40 21.27
14 1.10 21.27
15 2.10 20.40
16 2.40 21.27
17 2.10 20.24
18 1.10 20.40
19 2.10 20.40
20 1.10 21.27
Replacing dots with comma −
format(df1,decimal.mark=",")
   x1    y1
1 2,40 20,50
2 2,40 20,50
3 1,25 20,40
4 2,40 20,50
5 2,10 20,24
6 1,57 20,37
7 2,10 20,37
8 2,10 21,27
9 1,25 20,50
10 1,10 20,40
11 1,25 20,40
12 2,40 20,50
13 2,40 21,27
14 1,10 21,27
15 2,10 20,40
16 2,40 21,27
17 2,10 20,24
18 1,10 20,40
19 2,10 20,40
20 1,10 21,27
 Live Demo
x2<−sample(c(501.24,502.7,501.24,503.2),20,replace=TRUE)
y2<−sample(c(2.24,2.7,1.4,3.2),20,replace=TRUE)
df2<−data.frame(x2,y2)
df2
   x2     y2
1 503.20 1.40
2 502.70 2.24
3 503.20 2.70
4 503.20 3.20
5 502.70 2.24
6 503.20 2.24
7 502.70 2.24
8 501.24 1.40
9 502.70 1.40
10 501.24 2.70
11 502.70 2.24
12 502.70 3.20
13 503.20 2.70
14 502.70 2.70
15 502.70 3.20
16 503.20 2.70
17 503.20 1.40
18 502.70 1.40
19 501.24 1.40
20 502.70 2.70
Replacing dots with comma −
format(df2,decimal.mark=",")
   x2     y2
1 503,20 1,40
2 502,70 2,24
3 503,20 2,70
4 503,20 3,20
5 502,70 2,24
6 503,20 2,24
7 502,70 2,24
8 501,24 1,40
9 502,70 1,40
10 501,24 2,70
11 502,70 2,24
12 502,70 3,20
13 503,20 2,70
14 502,70 2,70
15 502,70 3,20
16 503,20 2,70
17 503,20 1,40
18 502,70 1,40
19 501,24 1,40
20 502,70 2,70
AngularJS - Internationalization

AngularJS supports inbuilt internationalization for three types of filters : Currency, Date, and Numbers. We only need to incorporate corresponding java script according to locale of the country. By default, it considers the locale of the browser. For example, for Danish locale, use the following script −
<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js">
</script> 
<html>
   <head>
      <title>Angular JS Forms</title>
   </head>
   
   <body>
      <h2>AngularJS Sample Application</h2>
      
      <div ng-app = "mainApp" ng-controller = "StudentController">
         {{fees | currency }}  <br/><br/>
         {{admissiondate | date }}  <br/><br/>
         {{rollno | number }}
      </div>
		
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
      <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js">
      </script>
      
      <script>
         var mainApp = angular.module("mainApp", []);
         
         mainApp.controller('StudentController', function($scope) {
            $scope.fees = 100;
            $scope.admissiondate  = new Date();
            $scope.rollno = 123.45;
         });
      </script>
      
   </body>
</html>
Open the file testAngularJS.htm in a web browser and see the result.
<html>
   <head>
      <title>Angular JS Forms</title>
   </head>
   
   <body>
      <h2>AngularJS Sample Application</h2>
      
      <div ng-app = "mainApp" ng-controller = "StudentController">
         {{fees | currency }}  <br/><br/>
         {{admissiondate | date }}  <br/><br/>
         {{rollno | number }}
      </div>
		
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
      <!-- <script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js">
      </script> -->
      
      <script>
         var mainApp = angular.module("mainApp", []);
         
         mainApp.controller('StudentController', function($scope) {
            $scope.fees = 100;
            $scope.admissiondate  = new Date();
            $scope.rollno = 123.45;
         });
      </script>
      
   </body>
</html>
Open the file testAngularJS.htm in a web browser and see the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    40 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Filter array with filter() and includes() in JavaScript

Let’s say following is our array −
const names = ['John', 'David', 'Mike','Sam','Carol','Bob'];
Now, we will filter the array −
var nameObject=names.filter((allNameObject) => !['David', 'Mike','Sam','Carol'].includes(allNameObject));
const names = ['John', 'David', 'Mike','Sam','Carol','Bob'];
console.log("The names are=");
console.log(names);
var nameObject=names.filter((allNameObject) => !['David', 'Mike','Sam','Carol'].includes(allNameObject));
console.log("After filter=");
console.log(nameObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo65.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo65.js
The names are=
[ 'John', 'David', 'Mike', 'Sam', 'Carol', 'Bob' ]
After filter=
[ 'John', 'Bob' ]
PostgreSQL – VARCHAR Data Type

28 Aug, 2020
PostgreSQL supports a character data type called VARCHAR. This data type is used to store characters of limited length. It is represented as varchar(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to varchar which has unlimited length. Any attempt to store a longer string in the column that defined with varchar(n) results in PostgreSQL issuing an error. However, one exception is that if the excess characters are all spaces, PostgreSQL will truncate the spaces to the maximum length and store the string. The only advantage of specifying the length specifier for the varchar data type is that PostgreSQL will check and issue an error if you try to insert a longer string into the varchar(n) column.
Syntax: variable_name VARCHAR(n)
Example :Let’s create a new table(say, char_test) for the demonstration using the below commands:
CREATE TABLE varchar_test (
    id serial PRIMARY KEY,
    x VARCHAR (1),
        y VARCHAR(10)
);
Now let’s insert a new row into the char_test table using the below command:
INSERT INTO varchar_test (x, y)
VALUES
    (
        'Geeks',
        'This is a test for char'
        
    );
At this stage PostgreSQL will raise an error as the data type of the x column is char(1) and we tried to insert a string with three characters into this column as shown below:
ERROR:  value too long for type character varying(1)
So, now let’s fix it.
INSERT INTO varchar_test (x, y)
VALUES
    (
        'G',
        'This is a test for char'
        
    );
Now, we will get the same error for the y column as the number of characters entered is greater than 10 as shown below:
ERROR:  value too long for type character varying(10)
Let’s fix it too.
INSERT INTO varchar_test (x, y)
VALUES
    (
        'G',
        'hello Geek'
        
    );
Now that we have managed to successfully assign the values to the character data type, check it by running the below command:
SELECT * FROM varchar_test;
Output:
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert the data type of Pandas column to int

13 Jan, 2021
In this article, we are going to see how to convert a Pandas column to int. Once a pandas.DataFrame is created using external data, systematically numeric columns are taken to as data type objects instead of int or float, creating numeric tasks not possible. We will pass any Python, Numpy, or Pandas datatype to vary all columns of a dataframe thereto type, or we will pass a dictionary having column names as keys and datatype as values to vary the type of picked columns.
Here astype() function empowers us to be express the data type you need to have. It’s extremely adaptable i.e you can attempt to go from one type to some other.
Approach:
Import pandas
Initialize DataFrame
Apply function to DataFrame column
Print data type of column
Example 1:
We first imported pandas module using the standard syntax. Then we created a dataframe with values 1, 2, 3, 4 and column indices as a and b. We named this dataframe as df. Next we converted the column type using the astype() method. The final output is converted data types of column.
Code:
Python
import pandas as pd    df = pd.DataFrame([["1", "2"], ["3", "4"]],                  columns = ["a", "b"])  df["a"] = df["a"].astype(str).astype(int)  print(df.dtypes)
Output:
Example 2:
We first imported the pandas module using the standard syntax. Then we created a dataframe with values ‘A’: [1, 2, 3, 4, 5],  ‘B’: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’],  ‘C’: [1.1, ‘1.0’, ‘1.3’, 2, 5] and column indices as A, B and C. We used dictionary named convert_dict to convert specific columns A and C. We named this dataframe as df. Next, we converted the column type using the astype() method. The final output is converted data types of columns.
Python
import pandas as pd    # sample dataframe  df = pd.DataFrame({'A': [1, 2, 3, 4, 5],                   'B': ['a', 'b', 'c', 'd', 'e'],                   'C': [1.1, '1.0', '1.3', 2, 5] })    # using dictionary to convert specific columns  convert_dict = {'A': int,                'C': float }    df = df.astype(convert_dict)  print(df.dtypes)
Output:
Picked
Python pandas-datatypes
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Examples - Display polygon using GUI

How to draw a polygon using GUI?
Following example demonstrates how to draw a polygon by creating Polygon() object. addPoint() & drawPolygon() method is used to draw the Polygon.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JPanel {
   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      Polygon p = new Polygon();
      for (int i = 0; i < 5; i++) p.addPoint((int) (
         100 + 50 * Math.cos(i * 2 * Math.PI / 5)),(int) (100 + 50 * Math.sin(
         i * 2 * Math.PI / 5)));
      g.drawPolygon(p);
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setTitle("Polygon");
      frame.setSize(350, 250);
      
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
      Container contentPane = frame.getContentPane();
      contentPane.add(new Main());
      frame.setVisible(true);
   }
}
The above code sample will produce the following result.
Polygon is displayed in a frame.

The following is an another sample example to draw a polygon using GUI.
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Panel extends JPanel {
   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      Polygon p = new Polygon();
      for (int i = 0; i < 5; i++) p.addPoint((int) (
         100 + 50 * Math.cos(i * 2 * Math.PI / 5)),(int) (
         100 + 50 * Math.sin(i * 2 * Math.PI / 5)));
      
      g.drawPolygon(p);
   } 
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.getContentPane().setBackground(Color.YELLOW); 
      frame.setTitle("DrawPoly");
      frame.setSize(350, 250);
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         } 
      }); 
      Container contentPane = frame.getContentPane();
      contentPane.add(new Panel());
      frame.show();
   }
}
The above code sample will produce the following result.
Polygon is displayed in a frame.
Perl | Exiting from a Script

07 May, 2019
exit() function evaluates the expression passed to it and exits from the Perl interpreter while returning the value as the exit value. The exit() function does not always exit immediately but calls the end routines before it terminates the program. If no expression is passed to the exit function then a default value 0 is returned. Use of exit() function is limited and should not be used to exit from a subroutine. To exit from a subroutine, die or return is used.
Syntax: exit(value)
Parameter: value which is to be returned on function call
Returns: the value passed to it or 0 if function is called without an argument
Example:
# Getting the user's bid for# an online auctionprint "Enter your bid";$bid = <STDIN>;  # Exit function returns $bid# if bid is less than 1000if ($bid < 1000){    exit $bid;}  else{    # Prints this message if bid is     # greater than or equal to 1000    print "\nThanks for Participating";}
Here is how the above code worksStep 1: Get a bid value from the user.Step 2: Exit returns bid value if the bid is less than 1000 and terminates the program.Step 3: Prints this message if the bid is greater than or equal to 1000.
Passing Parameter to exit functionA parameter can be passed to the exit function that gets stored in the system’s variable.
Note: Value passed to the exit function can be any random value, it needs not to be any specific value.The example below shows how to pass a value to the exit function:Example:
# Opening a fileif(!open(fh,"<","Filename.txt")){    # This block passing an error code 56     # to exit function indicating file     # could not be opened.    print "Could not open file";    exit 56;}  # Passing a success code 1 to # the exit functionexit 1;
 
Here is how the above program works:-Step 1: Opening a file in read mode.Step 2: When it is unable to open a file, if block executes, that calls an exit function and passes an error code value 56 to the system.Step 3: If opening the file is successful then it returns 1.
In order to view the values returned by an exit function on Linux/Unix $? is used. The command echo $? is executed on the terminal in order to view the value returned by an exit function.
perl-basics
Perl-function
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | ne operator
Perl | Basic Syntax of a Perl Program
Perl | Opening and Reading a File
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Perl | File Handling Introduction
Perl | Writing to a File
Perl | Multidimensional Hashes
Perl | Data Types
Perl | qw Operator
CSS3 - Box Sizing

Box sizing property is using to change the height and width of element.
Since css2, the box property has worked like as shown below −
width + padding + border = actual visible/rendered width of an element's box
height + padding + border = actual visible/rendered height of an element's box
Means when you set the height and width, it appears little bit bigger then given size cause element boarder and padding added to the element height and width.
<html>
   <head>
      <style>
         .div1 {
            width: 200px;
            height: 100px;
            border: 1px solid green;
         }
         .div2 {
            width: 200px;
            height: 100px;    
            padding: 50px;
            border: 1px solid pink;
         }
      </style>
   </head>

   <body>
      <div class = "div1">TutorialsPoint.com</div><br />
      <div class = "div2">TutorialsPoint.com</div>
   </body>
</html>
It will produce the following result −
Above image is having same width and height of two element but giving result is different, cause second one is included padding property.
<html>
   <head>
      <style>
         .div1 {
            width: 300px;
            height: 100px;
            border: 1px solid blue;
            box-sizing: border-box;
         }
         .div2 {
            width: 300px;
            height: 100px;
            padding: 50px;
            border: 1px solid red;
            box-sizing: border-box;
         }
      </style>
   </head>

   <body>
      <div class = "div1">TutorialsPoint.com</div><br />
      <div class = "div2">TutorialsPoint.com</div>
   </body>
</html>
Above sample is having same height and width with box-sizing:border-box. here result is shown below.
It will produce the following result −
Above elements are having same height and width with box-sizing:border-box so result is always same for both elements as shown above.

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
A strictly increasing linked list in Python

Suppose we have head of a singly linked list, we have to check whether the values of the nodes are sorted in a strictly ascending order or not.
So, if the input is like [2,61,105,157], then the output will be True.
To solve this, we will follow these steps −
Define a function solve() . This will take head
Define a function solve() . This will take head
if head.next is null, thenreturn True
if head.next is null, then
return True
return True
if head.val >= head.next.val, thenreturn False
if head.val >= head.next.val, then
return False
return False
return solve(head.next)
return solve(head.next)
Let us see the following implementation to get better understanding −
 Live Demo
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
class Solution:
   def solve(self, head):
      if head.next == None:
         return True
      if head.val >= head.next.val:
         return False
      return self.solve(head.next)
ob = Solution()
head = make_list([2,61,105,157])
print(ob.solve(head))
[2,61,105,157]
True
What are identifiers in C#?

An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows −
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
It should not be a C# keyword.
It should not be a C# keyword.
The following are some examples of identifiers −
class Calculation
class Demo
void display()
void getMarks()
int a;
int marks;
int rank;
double res_marks;
Angular10 NgSwitch Directive - GeeksforGeeks

21 Jul, 2021
In this article, we are going to see what is NgSwitch in Angular 10 and how to use it.
The NgSwitch in Angular10 is used to specify the condition to show or hide the child elements.
Syntax:
<li *NgSwitch='condition'></li>
NgModule: Module used by NgSwitch is:
CommonModule
 
Selectors:
[NgSwitch]
NgSwitchCase
Approach: 
Create the angular app to be used
There is no need for any import for the NgSwitch to be used
define a variable in app.component.ts
in app.component.html use NgSwitch with NgSwitchCase directive in the element with conditions to be checked
Serve the angular app using ng serve to see the output
Example:
app.component.ts
import { Component, Inject } from '@angular/core';import { PLATFORM_ID } from '@angular/core';import { isPlatformWorkerApp } from '@angular/common';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ]})export class AppComponent  {  num = 2;}
app.component.html
<div [ngSwitch]="num">  <div *ngSwitchCase="'1'">One</div>  <div *ngSwitchCase="'2'">Two</div>  <div *ngSwitchCase="'3'">Three</div>  <div *ngSwitchCase="'4'">Four</div>  <div *ngSwitchCase="'5'">Five</div></div>
Output:
Reference: https://angular.io/api/common/NgSwitch
bunnyram19
Angular10
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to get the coordinates of an object in a Tkinter canvas?

Tkinter Canvas Widget provides GUI features to an application. It can be used to draw shapes, animate objects, and configure the existing items in a canvas. Whenever we create shapes, we have to provide the size and coordinates of the shapes in the Canvas item constructor. In order to return the coordinates of an item on the Canvas, we can use the coords(item) method. It returns a list with the coordinates of the shapes in the canvas widget.
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of Tkinter frame
win.geometry("700x250")

# Initialize a Canvas Object
canvas = Canvas(win, width= 500, height= 300)

# Draw an oval inside canvas object
c= canvas.create_oval(100,10,410,200, outline= "red", fill= "#adf123")
canvas.pack(expand= True, fill=BOTH)

#Get and Print the coordinates of the Oval
print("Coordinates of the object are:", canvas.coords(c))
win.mainloop()
If we execute the above code, it will display a window with an oval inside it.
Along with that, the code will return and print the coordinates of the object on the console.
Coordinates of the object are: [100.0, 10.0, 410.0, 200.0]
C | Pointer Basics | Question 14 - GeeksforGeeks

28 Jun, 2021
Predict the output of following program
#include<stdio.h>int main(){    int a = 12;    void *ptr = (int *)&a;    printf("%d", *ptr);    getchar();    return 0;}
(A) 12(B) Compiler Error(C) Runt Time Error(D) 0Answer: (B)Explanation: There is compiler error in line “printf(“%d”, *ptr);”.
void * type pointers cannot be de-referenced. We must type cast them before de-referencing.
The following program works fine and prints 12.
#include<stdio.h>

int main()
{
    int a = 12;
    void *ptr = (int *)&a;
    printf("%d", *(int *)ptr);
    getchar();
    return 0;
}
Quiz of this Question
C-Pointers
Pointers
C Language
C Quiz
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
std::string class in C++
TCP Server-Client implementation in C
Structures in C
Exception Handling in C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
Batch Script - Listing Folder Contents

The listing of folder contents can be done with the dir command. This command allows you to see the available files and directories in the current directory. The dir command also shows the last modification date and time, as well as the file size.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N] 
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

[drive:][path][filename]
Specifies drive, directory, or files to list
/A
Displays files with specified attributes.
attributes
D - Directories R - Read-only files
H - Hidden files A - Files ready for archiving
S - System files I - Not content indexed files
L - Reparse Points - Prefix meaning not
/B
Uses bare format (no heading information or summary).
/C
Displays the thousand separator in file sizes. This is the default. Use /-C to disable the display of the separator.
/D
Same as wide but files are list sorted by column.
/L
Uses lowercase.
/N
New long list format where filenames are on the far right.
/O
Lists by files in sorted order.
sortorder
N By name (alphabetic), S By size (smallest first), E By extension (alphabetic), D By date/time (oldest first), G Group directories first - Prefix to reverse order
/P
Pauses after each screen is full of information.
/Q
Displays the owner of the file.
/R
Displays alternate data streams of the file.
/S
Displays files in the specified directory and all subdirectories.
/T
Controls what time field is displayed or used for sorting.
timefield
C - Creation
A - Last Access
W - Last Written
/W
Uses wide list format.
/X
This displays the short names generated for non-8dot3 file names. The format is that of /N with the short name inserted before the long name. If no short name is present, blanks are displayed in its place.
/4
Displays four-digit years.
Let’s see some of the examples on how to use the DIR command.
dir *.exe

The above command lists any file that ends with the .exe file extension.
dir *.txt *.doc

The above command uses multiple filespecs to list any files ending with .txt and .doc in one command.
dir /ad

Lists only the directories in the current directory. If you need to move into one of the directories listed use the cd command.
dir /s

Lists the files in the directory that you are in and all sub directories after that directory. If you are at root "C:\>", type this command, this will list to you every file and directory on the C: drive of the computer.
dir /p

If the directory has lots of files and you cannot read all the files as they scroll by, you can use the above command and it displays all files one page at a time.
dir /w

If you don't need file information you can use the above command to list only the files and directories going horizontally, taking as little space as needed.
dir /s /w /p

The above command will list all the files and directories in the current directory and the sub directories, in wide format and one page at a time.
 Print
 Add Notes
 Bookmark this page
C++ ios Library - Fixed Function

It is used to sets the floatfield format flag for the str stream to fixed. When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.
The floatfield format flag is both a selective and a toggle flag: it can take one, both or none of the following values as shown below −
The floatfield format flag is both a selective and a toggle flag: it can take any of the following values, or none as shown below −
write floating-point values in hexadecimal format.
The value of this is the same as (fixed|scientific)
Following is the declaration for std::fixed function.
ios_base& fixed (ios_base& str);
str − Stream object whose format flag is affected.
It returns Argument str.
Basic guarantee − if an exception is thrown, str is in a valid state.
It modifies str. Concurrent access to the same stream object may cause data races.
In below example explains about std::fixed function.
#include <iostream>     

int main () {
   double a = 3.1415926534;
   double b = 2006.0;
   double c = 1.0e-10;

   std::cout.precision(5);

   std::cout << "default:\n";
   std::cout << a << '\n' << b << '\n' << c << '\n';

   std::cout << '\n';

   std::cout << "fixed:\n" << std::fixed;
   std::cout << a << '\n' << b << '\n' << c << '\n';

   std::cout << '\n';

   std::cout << "scientific:\n" << std::scientific;
   std::cout << a << '\n' << b << '\n' << c << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
default:
3.1416
2006
1e-010

fixed:
3.14159
2006.00000
0.00000

scientific:
3.14159e+000
2.00600e+003
1.00000e-010

 Print
 Add Notes
 Bookmark this page
How to select values less than or greater than a specific percentile from an R data frame column?

The percentiles divide a set of numeric values into hundred groups or individual values if the size of the values is 100. We can find percentiles for a numeric column of an R data frame, therefore, it is also possible to select values of a column based on these percentiles. For this purpose, we can use quantile function.
Consider the below data frame −
set.seed(111)
x<-sample(0:15,30,replace=TRUE) df<-data.frame(x)
df
      x
1    13
2    10
3    3
4    2
5    14
6    8
7    10
8    4
9    2
10    11
11    7
12    9
13    0
14    12
15    12
16    9
17    3
18    14
19    7
20    13
21    9
22    8
23    7
24    10
25    15
26    0
27    10
28    6
29    4
30    14
Finding values that are less than or equal to a certain percentile for x in df −
df[dfx<quantile(dfx,0.75),]
[1] 10 3 2 8 10 4 2 11 7 9 0 9 3 7 9 8 7 10 0 10 6 4
df[dfx<quantile(dfx,0.25),]
[1] 3 2 4 2 0 3 0 4
df[dfx<quantile(dfx,0.50),]
[1] 3 2 8 4 2 7 0 3 7 8 7 0 6 4
df[dfx<quantile(dfx,0.90),]
[1] 13 10 3 2 8 10 4 2 11 7 9 0 12 12 9 3 7 13 9 8 7 10 0 10 6
[26] 4
df[dfx<quantile(dfx,0.95),]
[1] 13 10 3 2 8 10 4 2 11 7 9 0 12 12 9 3 7 13 9 8 7 10 0 10 6
[26] 4
df[dfx<quantile(dfx,0.99),]
[1] 13 10 3 2 14 8 10 4 2 11 7 9 0 12 12 9 3 14 7 13 9 8 7 10 0
[26] 10 6 4 14
df[dfx<quantile(dfx,0.10),]
[1] 0 0
df[dfx<quantile(dfx,0.05),]
[1] 0 0
df[dfx<quantile(dfx,0.20),]
[1] 3 2 2 0 3 0
df[dfx<quantile(dfx,0.30),]
[1] 3 2 4 2 0 3 0 6 4
df[dfx>quantile(dfx,0.05),]
[1] 13 10 3 2 14 8 10 4 2 11 7 9 12 12 9 3 14 7 13 9 8 7 10 15 10 [26] 6 4 14
df[dfx>quantile(dfx,0.10),]
[1] 13 10 3 14 8 10 4 11 7 9 12 12 9 3 14 7 13 9 8 7 10 15 10 6 4 [26] 14
df[dfx>quantile(dfx,0.20),]
[1] 13 10 14 8 10 4 11 7 9 12 12 9 14 7 13 9 8 7 10 15 10 6 4 14
df[dfx>quantile(dfx,0.25),]
[1] 13 10 14 8 10 11 7 9 12 12 9 14 7 13 9 8 7 10 15 10 6 14
df[dfx>quantile(dfx,0.60),]
[1] 13 14 11 12 12 14 13 15 14
df[dfx>quantile(dfx,0.70),]
[1] 13 14 11 12 12 14 13 15 14
df[dfx>quantile(dfx,0.75),]
[1] 13 14 12 12 14 13 15 14
df[dfx>quantile(dfx,0.80),]
[1] 13 14 14 13 15 14
df[dfx>quantile(dfx,0.90),]
[1] 15
df[dfx>quantile(dfx,0.95),]
[1] 15
Create an Integer object in Java

To create an Integer object in Java is quite easy. Let us learn about the following two ways for this purpose.
Method1
 Live Demo
public class Demo {
   public static void main(String []args) {
      Integer obj = new Integer("199");
      System.out.println(obj);
   }
}
199
Method2 −Now let us see the second way
Public class Demo {
   public static void main(String []args) {
      Integer obj = new Integer(99);
      System.out.println(obj);
   }
}
99
MySQL Select where timestamp is in the current hour?

For this, you can use CURTIME(). Let us first create a table −
mysql> create table DemoTable
   -> (
   -> ArrivalTime timestamp
   -> );
Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-10-26 17:55:55');
Query OK, 1 row affected (0.46 sec)
mysql> insert into DemoTable values('2019-10-26 18:00:00');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('2019-10-26 18:55:00');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('2018-10-26 16:00:10');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-10-26 17:55:55 |
| 2019-10-26 18:00:00 |
| 2019-10-26 18:55:00 |
| 2018-10-26 16:00:10 |
+---------------------+
4 rows in set (0.00 sec)
The current time is as follows −
mysql> select curtime();
+-----------+
| curtime() |
+-----------+
| 18:43:55  |
+-----------+
1 row in set (0.00 sec)
Following is the query to select where the timestamp is in the current hour −
mysql> select *from DemoTable where hour(ArrivalTime)=hour(curtime());
This will produce the following output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-10-26 18:00:00 |
| 2019-10-26 18:55:00 |
+---------------------+
2 rows in set (0.00 sec)
How to use Function and BiFunction interfaces in lambda expression in Java?

The Function interface is a pre-defined functional interface that can be used as an assignment target for a lambda expression or method reference. It takes a single parameter and returns result by calling the apply() method. While the BiFunction interface is also a pre-defined functional interface that takes two parameters and returns a result. It is similar to the Function interface except it takes two parameters.
@FunctionalInterface
public interface Function<T, R>

@FunctionalInterface
public interface BiFunction<T, U, R>
import java.util.function.BiFunction;
import java.util.function.Function;

public class SampleFunctionBiFunctionTest {
   public static void main(String[] args) {
      Function<Integer, Integer> printNumber = a -> a*10;
      System.out.println("The number is: "+ printNumber.apply(10));

      BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;
      System.out.println("The addition of two numbers are: "+ add.apply(3,2));
   }
}
The number is: 100
The addition of two numbers are: 5
DAX Filter - CALCULATETABLE function

Evaluates a table expression in a context modified by the given filters.
CALCULATETABLE (<expression>, [<filter1>], [<filter2>] ...)

expression
The table expression to be evaluated.
filter1, filter2 ...
A Boolean expression or a table expression that defines a filter.
A table of values.
The expression used as the first parameter must be a function that returns a table.
If Boolean expressions are used as arguments, the following restrictions apply −
The expression cannot reference a calculated field
The expression cannot reference a calculated field
The expression cannot use a nested CALCULATE function.
The expression cannot use a nested CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
CALCULATETABLE function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter argument, any existing filters on that column are removed, and the filter used in the filter argument is applied instead.
CALCULATETABLE function is a synonym for the RELATEDTABLE function.
= SUMX ( 
   CALCULATETABLE (East_Sales, 
   FILTER (East_Sales, East_Sales[Product]=[Product])), 
   East_Sales[Sales Amount]
) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Graph k-NN decision boundaries in Matplotlib

To make graph k-NN decision boundaries in matplotlib, we can take the following Steps.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable n_neighbors for number of neighbors.
Initialize a variable n_neighbors for number of neighbors.
Load and return the iris dataset (classification).
Load and return the iris dataset (classification).
Create x and y data points.
Create x and y data points.
Make lists of dark and light colors.
Make lists of dark and light colors.
Classifier implementing the k-nearest neighbors vote.
Classifier implementing the k-nearest neighbors vote.
Create xmin, xmax, ymin and ymax  data points.
Create xmin, xmax, ymin and ymax  data points.
Create a new figure or activate an existing figure.
Create a new figure or activate an existing figure.
Create a contourf plot.
Create a contourf plot.
Create a scatter plot with X dataset.
Create a scatter plot with X dataset.
Set x and y axes labels, titles and scale of the axes.
Set x and y axes labels, titles and scale of the axes.
To display the figure, use Show() method.
To display the figure, use Show() method.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets

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

n_neighbors = 15
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
h = .02

cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
cmap_bold = ['darkorange', 'c', 'darkblue']


clf = neighbors.KNeighborsClassifier(n_neighbors, weights='uniform')
clf.fit(X, y)

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.figure()

plt.contourf(xx, yy, Z, cmap=cmap_light)

sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=iris.target_names[y],
palette=cmap_bold, alpha=1.0, edgecolor="black")

plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())

plt.title("3-Class classification (k = %i, 'uniform' = '%s')"
% (n_neighbors, 'uniform'))

plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1])

plt.Show()
It will produce the following output −