code-rag-bench/online-tutorials huggingface dataset:
sciPy stats.binned_statistic() function | Python - GeeksforGeeks

18 Feb, 2019
stats.binned_statistic(x, values, statistic='mean', bins=10, range=None) function computes the binned statistics value for the given data (array elements).It works similar to histogram function. As histogram function makes bins and counts the no. of points in each bin; this function computes the sum, mean, median, count or other statistics of the values for each bin.
Parameters :arr : [array_like]input array to be binned.values : [array_like]on which stats to be calculated.statistics : Statistics to compute {mean, count, median, sum, function}. Default is mean.bin : [int or scalars]If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges.range : (float, float) Lower and upper range of the bins and if not provided, range is from x.max() to x.min().
Results : Statistics value for each bin; bin edges; bin number.
Code #1 :
# stats.binned_statistic() method import numpy as npfrom scipy import stats   # 1D arrayarr = [20, 2, 7, 1, 34]print("\narr : \n", arr)     # median  print("\nbinned_statistic for median : \n", stats.binned_statistic(        arr, np.arange(5), statistic ='median', bins = 4)) 
Output :
arr : 
 [20, 2, 7, 1, 34]

binned_statistic for median : 
 BinnedStatisticResult(statistic=array([ 2., nan,  0.,  4.]), 
bin_edges=array([ 1.,  9.25, 17.5, 25.75, 34.  ]), 
binnumber=array([3, 1, 1, 1, 4], dtype=int64))

 Code #2 :
# stats.binned_statistic() method import numpy as npfrom scipy import stats  # mean  arr = [20, 2, 7, 1, 34]print("\nbinned_statistic for mean : \n", stats.binned_statistic(        arr, np.arange(5), statistic ='mean', bins = 2)) 
Output :
binned_statistic for mean : 
 BinnedStatisticResult(statistic=array([2., 2.]), 
bin_edges=array([ 1., 17.5, 34. ]), 
binnumber=array([2, 1, 1, 1, 2], dtype=int64))
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Python None Keyword - GeeksforGeeks

12 Nov, 2020
None is used to define a null value. It is not the same as an empty string, False, or a zero. It is a data type of the class NoneType object. 
Assigning a value of None to a variable is one way to reset it to its original, empty state.
Example 1:
Python3
# we will check the type of Noneprint(type(None))
<class 'NoneType'>

Example 2:
Python3
# declaring a variable as Nonevar = None  # checking it's valueif var is None:    print("var has a value of None")else:    print("var has a value")
var has a value of None

Note: If a function does not return anything, it returns None in python.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
What is the yield keyword in JavaScript?

The yield keyword is used in JavaScript to pause and resume a generator function. The value of the expression is returned to the generator's caller.
Here are the Examples −
function* displayRank () {
   var selPlayers= [1, 2, 3, 4];
   for (var a = 0; a < selPlayers.length; a++) {
      yield selPlayers[i];
   }
}
After defining a generator function, use it like the following. HHere displayRank() is the generator function −
var rank = displayRank(); //
// value: 1
alert(rank.next());
// value: 2
alert(rank.next());
// value: 3
alert(rank.next());
// value: 4
alert(rank.next());
// value: undefined
alert(rank.next());
PyQt5 QToolButton - GeeksforGeeks

17 Sep, 2019
Tool button is a PyQt5 widget which looks like the buttons used in Toolbar. This button contains icon which gives an idea about its utility. For adding this button in application QToolButton class is used.
Example:
A window having a Tool button with an exit icon. When the user clicks this button the application gets closed.
import sysfrom PyQt5 import QtCore, QtGui, QtWidgets  class Ui_MainWindow(object):    def setupUi(self, MainWindow):        MainWindow.resize(506, 312)        self.centralwidget = QtWidgets.QWidget(MainWindow)        self.centralwidget.setObjectName("centralwidget")          self.toolButton = QtWidgets.QToolButton(self.centralwidget)        self.toolButton.setGeometry(QtCore.QRect(220, 120, 41, 41))          icon = QtGui.QIcon()        icon.addPixmap(QtGui.QPixmap("exiticon.png [exact location of image]"),                                          QtGui.QIcon.Normal, QtGui.QIcon.Off)                  # adding icon to the toolbutton        self.toolButton.setIcon(icon)        MainWindow.setCentralWidget(self.centralwidget)          self.retranslateUi(MainWindow)        QtCore.QMetaObject.connectSlotsByName(MainWindow)                  # adding signal and slot         self.toolButton.clicked.connect(self.exitapp)      def retranslateUi(self, MainWindow):        _translate = QtCore.QCoreApplication.translate        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))          # For closing the application    def exitapp(self):        sys.exit()  if __name__ == "__main__":     app = QtWidgets.QApplication(sys.argv)         MainWindow = QtWidgets.QMainWindow()     ui = Ui_MainWindow()     ui.setupUi(MainWindow)     MainWindow.show()     sys.exit(app.exec_())          
Output:
When user clicks this button, application get closed.
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
SAP ABAP - While Loop

A WHILE loop statement repeatedly executes a target statement as long as a given condition is true.
The general format for the WHILE command is as follows −
WHILE <logical expression>  

<statement block>. 
    
ENDWHILE.

The statement block may be a single statement or a block of statements.
The WHILE loop executes the statements enclosed by the WHILE and ENDWHILE commands until the logical expression becomes false.
The WHILE command is preferable while considering the performance of programs. The loop continues until the logical statement is found to be untrue and exits the loop if a false statement is found, and the first statement after the WHILE loop is executed.
REPORT YS_SEP_15.
  
DATA: a type i. 
 
a = 0.
  
WHILE a <> 8.
  
   Write: / 'This is the line:', a.  
   a = a + 1.
   
ENDWHILE.
The above code produces the following output −
This is the line: 0 
This is the line: 1 
This is the line: 2 
This is the line: 3 
This is the line: 4 
This is the line: 5 
This is the line: 6 
This is the line: 7


    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
How to get String Length in PHP ? - GeeksforGeeks

20 May, 2021
In this article, we learn how to find the length of the string in PHP. 
Approach: This task can be done by using the built-in function strlen() in PHP. This method is used to return the length of the string. It returns a numeric value that represents the length of the given string. 
Syntax:
strlen($string)
Example 1: 
PHP
<?php// PHP program to count all// characters in a string$str = "GeeksforGeekslover";      // Using strlen() function to// get the length of string$len = strlen($str);  // Printing the resultecho $len;?>
Output:
18
Example 2: Below code demonstrates the use of strlen() function in PHP where the string has special characters and escape sequences.
PHP
<?php// PHP program to find the length of// a given string which has special// characters$str = "\n LuckyGeeks ;";      // Here '\n' has been counted as 1echo strlen($str);?>
Output:
14
PHP-function
PHP-Questions
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
How to generate PDF file using PHP ?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP | Ternary Operator
How to pass form variables from one page to other page in PHP ?
Program to check idempotent matrix in C++

Given a matrix M[r][c], ‘r’ denotes number of rows and ‘c’ denotes number of columns such that r = c forming a square matrix. We have to check whether the given square matrix is an Idempotent matrix or not.
Idempotent Matrix
A matrix ‘M’ is called Idempotent matrix if and only the matrix ‘M’ multiplied by itself returns the same matrix ‘M’ i.e. M * M = M.
Like in the given example below −
We can say that the above matrix is multiplied by itself and returns the same matrix; hence the matrix is Idempotent matrix. 
Input: m[3][3] = { {2, -2, -4},
   {-1, 3, 4},
   {1, -2, -3}}
Output: Idempotent
Input: m[3][3] == { {3, 0, 0},
   {0, 2, 0},
   {0, 0, 3} }
Output: Not Idempotent
Start
Step 1 -> define macro as #define size 3
Step 2 -> declare function for matrix multiplication
   void multiply(int arr[][size], int res[][size])
      Loop For int i = 0 and i < size and i++
         Loop For int j = 0 and j < size and j++
            Set res[i][j] = 0
            Loop for int k = 0 and k < size and k++
               Set res[i][j] += arr[i][k] * arr[k][j]
            End
      End
   End
Step 3 -> declare function to check idempotent or not
   bool check(int arr[][size])
   declare int res[size][size]
   call multiply(arr, res)
      Loop For int i = 0 and i < size and i++
      Loop For int j = 0 and j < size and j++
         IF (arr[i][j] != res[i][j])
            return false
         End
      End
   End
   return true
step 4 -> In main()
   declare int arr[size][size] = {{1, -1, -1},
      {-1, 1, 1},
      {1, -1, -1}}
   IF (check(arr))
      Print its an idempotent matrix
   Else
      Print its not an idempotent matrix
Stop
#include<bits/stdc++.h>
#define size 3
using namespace std;
//matrix multiplication.
void multiply(int arr[][size], int res[][size]){
   for (int i = 0; i < size; i++){
      for (int j = 0; j < size; j++){
         res[i][j] = 0;
         for (int k = 0; k < size; k++)
            res[i][j] += arr[i][k] * arr[k][j];
      }
   }
}
//check idempotent or not
bool check(int arr[][size]){
   int res[size][size];
   multiply(arr, res);
   for (int i = 0; i < size; i++)
   for (int j = 0; j < size; j++)
      if (arr[i][j] != res[i][j])
         return false;
   return true;
}
int main(){
   int arr[size][size] = {{1, -1, -1},
      {-1, 1, 1},
      {1, -1, -1}};
   if (check(arr))
      cout << "its an idempotent matrix";
   else
      cout << "its not an idempotent matrix";
   return 0;
}
its an idempotent matrix
Check if user inputted string is in the array in JavaScript

We are required to write a JavaScript program that provides the user an input to enter a string value.
The program should then check the input value against some hard-coded array values. Our program should print true to the screen if the input string value is included in the array, false otherwise.
The code for this will be −
<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>CHECK EXISTENCE</title>
</head>
<body>
   <script>
      const arr = ['arsenal', 'chelsea', 'everton', 'fulham',
      'swansea'];
      const checkExistence = () => {
         const userInput = document.getElementById("input").value;
         const exists = arr.includes(userInput);
         document.getElementById('result').innerText = exists;
      };
   </script>
   <input type="text" id="input">
   <button onclick="checkExistence()">Check</button>
   <p id='result'></p>
</body>
</html>
And the output on the screen will be −
How to remove empty tags using BeautifulSoup in Python?

26 Nov, 2020
Prerequisite: Requests, BeautifulSoup, strip
The task is to write a program that removes the empty tag from HTML code. In Beautiful Soup there is no in-built method to remove tags that has no content.
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4

requests:  Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests

Get HTML Code
Iterate through each tagFetching text from the tag and remove whitespaces using the strip.After removing whitespace, check If the length of the text is zero remove the tag from HTML code.
Fetching text from the tag and remove whitespaces using the strip.
After removing whitespace, check If the length of the text is zero remove the tag from HTML code.
Example 1: Remove empty tag.
Python3
# Import Modulefrom bs4 import BeautifulSoup  # HTML Objecthtml_object = """  <p><p></p><strong>some<br>text<br>here</strong></p>  """  # Get HTML Codesoup = BeautifulSoup( html_object , "lxml")  # Iterate each linefor x in soup.find_all():      # fetching text from tag and remove whitespaces    if len(x.get_text(strip=True)) == 0:                  # Remove empty tag        x.extract()  # Print HTML Code with removed empty tagsprint(soup)
Output:
<html><body><strong>sometexthere</strong>
</body></html>

Example 2: Remove empty tag from a given URL.
Python3
# Import Modulefrom bs4 import BeautifulSoupimport requests  # Page URLURL = "https://www.geeksforgeeks.org/"  # Page content from Website URLpage = requests.get( URL )  # Get HTML Codesoup = BeautifulSoup( page.content , "lxml" )  # Iterate each linefor x in soup.find_all():      # fetching text from tag and remove whitespaces    if len( x.get_text ( strip = True )) == 0:          # Remove empty tag        x.extract()  # Print HTML Code with removed empty tagsprint(soup)
Output:
Python BeautifulSoup
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Add elements to HashSet in Java

First, create a HashSet −
HashSet hs = new HashSet();
Now, add some elements using the add() method. Set the elements as a parameter. Here, we have set string −
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
The following is an example to add elements to a HashSet −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      hs.add("K");
      hs.add("M");
      hs.add("N");
      System.out.println(hs);
   }
}
[A, B, C, D, E, F, K, M, N]
C++ set for user define data type

19 Apr, 2018
The C++ STL set is a data structure used to store the distinct value in ascending or descending order. By default, we can use it to store system defined data type only(eg. int, float, double, pair etc.).
And if we want to store user-defined datatype in a set (eg. structure) then the compiler will show an error message. That is because of the property of the set that value kept in the set must be ascending or descending order. And while doing so the compiler cant compare two structures(as they are user-defined) and that’s the reason to why the compiler shows us the error message.So, in order to store a structure in a set, some comparison function need s to be designed. Implementation of this is given below:
Examples:
Input  : 110 102 101 115
Output : 101 102 110 115

Explanation:Here we insert a random list to the set, and when we output the set the list gets sorted in ascending order based on the comparison function we made.
Input  : 3  2  34   0 76 
Output : 0  2   3  34 76

// CPP implementation to use // user-defined data type in// structures#include<bits/stdc++.h>using namespace std;  // Structure definitionstruct Test {    int id;          // This function is used by set to order    // elements of Test.    bool operator<(const Test& t) const    {        return (this->id < t.id);    }};  // Driver methodint main(){    // put values in each     // structure define below.    Test t1 = { 110 }, t2 = { 102 },          t3 = { 101 }, t4 = { 115 };      // define a set having     // structure as its elements.    set<struct Test> s;           // insert structure in set    s.insert(t1);     s.insert(t2);    s.insert(t3);    s.insert(t4);          // define an iterator to iterate the whole set.    set<struct Test>::iterator it;           for (it = s.begin(); it != s.end(); it++)    {        // print in ascending order as required.        cout << (*it).id << endl;     }          return 0;}
Output:
101
102
110
115

Application:a) Very useful while printing all distinct structure in sorted order.b) Insert new structure in a sorted list of structures.
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
How to declare and access pointer variable in Golang?

10 May, 2020
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).
Before we start there are two important operators which we will use in pointers i.e.
* Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address.
& operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer.
Declaring a pointer:
var pointer_name *Data_Type
Example: Below is a pointer of type string which can store only the memory addresses of string variables.
var s *string
Initialization of Pointer: To do this you need to initialize a pointer with the memory address of another variable using the address operator as shown in the below example:
// normal variable declaration
var a = 45

// Initialization of pointer s with 
// memory address of variable a
var s *int = &a

Example: In the following example, using pointer we will access the value of the variable whose address is stored in pointer.
// Golang program to show how to declare// and access pointer variable in Golangpackage main  import (    "fmt")  func main() {      // variable declaration    var dummyVar string = "Geeks For Geeks"      // pointer declaration    var pointerVariable *string      // assigning variable address to pointer variable    pointerVariable = &dummyVar      // Prints the address of the dummyVar variable    fmt.Printf("\nAddress of the variable: %v", &dummyVar)      // Prints the address stored in pointer    fmt.Printf("\nAddress stored in the pointer variable: %v", pointerVariable)      // Value of variable    fmt.Printf("\nValue of the Actual Variable: %s", dummyVar)      // Value of variable whose address is stored in pointer    fmt.Printf("\nValue of the Pointer variable: %s", *pointerVariable)}
Output:
Address of the variable: 0xc00010a040
Address stored in the pointer variable: 0xc00010a040
Value of the Actual Variable: Geeks For Geeks
Value of the Pointer variable: Geeks For Geeks

Explanation: Here (&) symbol is used to get the address of the variable storing the value as “Geeks for Geeks”. The address owned by this variable is the same which is stored in the pointer. Therefore, the output of &dummyVar and pointerVariable is the same. To access the value stored at the address, which is stored in pointer we user (*) symbol.
Golang-Pointers
Picked
Go Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove rows with NA in one column of R DataFrame

01 Apr, 2021
Columns of DataFrame in R Programming Language can have empty values represented by NA. In this article, we are going to see how to remove rows with NA in one column. We will see various approaches to remove rows with NA values.
Data in use:
Approach
Create a data frame
Select the column on the basis of which rows are to be removed
Traverse the column searching for na values
Select rows
Delete such rows using a specific method
Method 1: Using drop_na()
drop_na() Drops rows having values equal to NA. To use this approach we need to use “tidyr” library, which can be installed.
install.packages(“tidyverse”)
Syntax:
drop_na(name_of_the_column)
Example:
R
# Creating dataframestudent=data.frame(name=c("Ram","Geeta","John","Paul",                          "Cassie","Jim","Dwight")                   ,maths=c(7,8,NA,9,10,8,9)                   ,science=c(5,7,6,8,NA,7,8)                   ,history=c(7,NA,7,7,NA,7,7))  print(student)  library(tidyr)student %>% drop_na(maths)
Output:
Method 2: Using is.na()
is.na() function first looks for na values in a column and then discards such rows.
Syntax:
is.na(name of the column)
Example:
R
# Creating dataframestudent=data.frame(name=c("Ram","Geeta","John","Paul",                          "Cassie","Jim","Dwight")                   ,maths=c(7,8,NA,9,10,8,9)                   ,science=c(5,7,6,8,NA,7,8)                   ,history=c(7,NA,7,7,NA,7,7))  print(student)  student[!is.na(student$science),]
Output:
Method 3:Using complete.cases() 
This function functions similar to the above two methods
Syntax:
complete.cases(name of the column)
Example:
R
# Creating dataframestudent=data.frame(name=c("Ram","Geeta","John","Paul",                          "Cassie","Jim","Dwight")                   ,maths=c(7,8,NA,9,10,8,9)                   ,science=c(5,7,6,8,NA,7,8)                   ,history=c(7,NA,7,7,NA,7,7))  print(student)  student[complete.cases(student$history),]
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
Python – Get Random Range Average

28 Jul, 2020
Given range and Size of elements, extract random numbers within a range, and perform average of it.
Input : N = 3, strt_num = 10, end_num = 15Output : 13.58Explanation : Random elements extracted between 10 and 15, averaging out to 13.58.
Input : N = 2, strt_num = 13, end_num = 18Output : 15.82Explanation : 2 elements average to 15.82 in this case.
Method #1 : Using loop + uniform()The combination of above functions can be used to solve this problem. In this, we perform the task of extracting numbers using uniform() and loop is used to perform addition of numbers. The average is computed at end by dividing by size.
# Python3 code to demonstrate working of # Random Range Average# Using loop + uniform()import random  # initializing Nnum = 4  # Initialize strt_numstrt_num = 15  # Initialize end_numend_num = 60  # Using loop + uniform()res = 0.0for _ in range(num):               # performing summation of range elements    res += random.uniform(strt_num, end_num)  # performing averageres = res / num  # printing result print("The average value : " + str(res)) 
The average value : 42.980287235196116

 
Method #2 : Using sum() + uniform() + generator expressionThe combination of above functions can be used to solve this problem. In this, we perform the task of performing average using sum() to compute sum() and whole logic is encapsulated in one-liner using generator expression.
# Python3 code to demonstrate working of # Random Range Average# Using sum() + uniform() + generator expressionimport random  # initializing Nnum = 4  # Initialize strt_numstrt_num = 15  # Initialize end_numend_num = 60  # Using sum() + uniform() + generator expression# shorthand, using generator expression to form sum and division by Sizeres = sum(random.uniform(strt_num, end_num) for _ in range(num)) / num  # printing result print("The average value : " + str(res))
The average value : 42.980287235196116

Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tcl - Error Handling

Error handling in Tcl is provided with the help of error and catch commands. The syntax for each of these commands is shown below.
error message info code

In the above error command syntax, message is the error message, info is set in the global variable errorInfo and code is set in the global variable errorCode.
catch script resultVarName

In the above catch command syntax, script is the code to be executed, resultVarName is variable that holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an error.
An example for simple error handling is shown below −
#!/usr/bin/tclsh

proc Div {a b} {
   if {$b == 0} {
      error "Error generated by error" "Info String for error" 401
   } else {
      return [expr $a/$b]
   }
}

if {[catch {puts "Result = [Div 10 0]"} errmsg]} {
   puts "ErrorMsg: $errmsg"
   puts "ErrorCode: $errorCode"
   puts "ErrorInfo:\n$errorInfo\n"
}

if {[catch {puts "Result = [Div 10 2]"} errmsg]} {
   puts "ErrorMsg: $errmsg"
   puts "ErrorCode: $errorCode"
   puts "ErrorInfo:\n$errorInfo\n"
}
When the above code is executed, it produces the following result −
ErrorMsg: Error generated by error
ErrorCode: 401
ErrorInfo:
Info String for error
   (procedure "Div" line 1)
   invoked from within
"Div 10 0"

Result = 5

As you can see in the above example, we can create our own custom error messages. Similarly, it is possible to catch the error generated by Tcl. An example is shown below −
#!/usr/bin/tclsh

catch {set file [open myNonexistingfile.txt]} result
puts "ErrorMsg: $result"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
When the above code is executed, it produces the following result −
ErrorMsg: couldn't open "myNonexistingfile.txt": no such file or directory
ErrorCode: POSIX ENOENT {no such file or directory}
ErrorInfo:
couldn't open "myNonexistingfile.txt": no such file or directory
Resize image proportionally with CSS

10 May, 2022
The resize image property is used in responsive web where image is resizing automatically to fit the div container. The max-width property in CSS is used to create resize image property. The resize property will not work if width and height of image defined in the HTML. 
Syntax:
img {
    max-width:100%;
    height:auto;
}
Width can also be used instead of max-width if desired. The key is to use height:auto to override any height=”...” attribute already present on the image. The CSS properties max-width and max-height work great, but aren’t supported many browsers. Example 1: 
html
<!DOCTYPE html><html>    <head>        <title>cell padding</title>        <style>            .gfg {                width:auto;                text-align:center;                padding:20px;            }            img {                max-width:100%;                        height:auto;            }        </style>    </head>    <body>        <div class = "gfg">            <p id="my-image"><img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png">            </p>        </div>    </body></html>
Output: 
A common use is to set max-width: 100%; height: auto; so large images don’t exceed their containers width. Another way is the use of object-fit property, this will fit image, without changing the proportionally. 
Example 2: 
html
<!DOCTYPE html><html>    <head>        <title>cell padding</title>        <style>            .gfg {                width:auto;                text-align:center;                padding:20px;            }            img {                width: 100%;                height: 100%;                object-fit: contain;            }        </style>    </head>    <body>        <div class = "gfg">                <p id="my-image"><img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-17.png">            </p>        </div>    </body></html>                   
Output: 
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
hardikkoriintern
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PIL | putpixel() method

19 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The PixelAccess class provides read and write access to PIL.Image data at a pixel level.Accessing individual pixels is fairly slow. If you are looping over all of the pixels in an image, there is likely a faster way using other parts of the Pillow API.
putpixel() Modifies the pixel at x, y. The color is given as a single numerical value for single band images, and a tuple for multi-band images
Syntax: putpixel(self, xy, color)
Parameters:
xy :The pixel coordinate, given as (x, y)value: – The pixel value.
Returns: An Image with pixel .
Image Used:
   # Importing Image from PIL package from PIL import Image      # creating a image objectimage = Image.open(r'C:\Users\System-Pc\Desktop\python.png')   width, height = image.size  for x in range(height):    image.putpixel( (x, x), (0, 0, 0, 255) )  image.show()
Output:
Another example:Here we change the color parameter.Image Used
# Importing Image from PIL package from PIL import Image      # creating a image objectimage = Image.open(r'C:\Users\System-Pc\Desktop\ybear.jpg')   width, height = image.size  for x in range(height):    image.putpixel( (x, x), (10, 10, 10, 255) )  image.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
C++ Array of Strings

In this section we will see how to define an array of strings in C++. As we know that
in C, there was no strings. We have to create strings using character array. So to
make some array of strings, we have to make a 2-dimentional array of characters.
Each rows are holding different strings in that matrix.
In C++ there is a class called string. Using this class object we can store string
type data, and use them very efficiently. We can create array of objects so we can
easily create array of strings.
After that we will also see how to make string type vector object and use
them as an array.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   string animals[4] = {"Elephant", "Lion", "Deer", "Tiger"}; //The
   string type array
   for (int i = 0; i < 4; i++)
      cout << animals[i] << endl;
}
Elephant
Lion
Deer
Tiger
Now let us see how to create string array using vectors. The vector is available in C++
standard library. It uses dynamically allocated array.
 Live Demo
#include<iostream>
#include<vector>
using namespace std;
int main() {
   vector<string> animal_vec;
   animal_vec.push_back("Elephant");
   animal_vec.push_back("Lion");
   animal_vec.push_back("Deer");
   animal_vec.push_back("Tiger");
   for(int i = 0; i<animal_vec.size(); i++) {
      cout << animal_vec[i] << endl;
   }
}
Elephant
Lion
Deer
Tiger
How to compare Year, Month and Day in a MySQL query and display matching records

For this, you can use DATE(). Let us first create a table −
mysql> create table DemoTable864(DueDateTime timestamp);
Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable864 values('2019-01-10 12 −34 −55');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable864 values('2016-12-11 11 −12 −00');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable864 values('2015-04-01 10 −00 −00');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable864 values('2017-05-20 04 −40 −10');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable864;
This will produce the following output −
+---------------------+
| DueDateTime         |
+---------------------+
|2019-01-10 12 −34 −55|
|2016-12-11 11 −12 −00|
|2015-04-01 10 −00 −00|
|2017-05-20 04 −40 −10|
+---------------------+
4 rows in set (0.00 sec)
Following is the query to compare year, month and day −
mysql> select *from DemoTable864 where date(DueDateTime)='2015-04-01';
This will produce the following output −
+-----------------------+
| DueDateTime           |
+-----------------------+
| 2015-04-01 10 −00 −00 |
+-----------------------+
1 row in set (0.04 sec)
Construct a DataFrame in Pandas using string data - GeeksforGeeks

26 Jan, 2019
As we know that data comes in all shapes and sizes. They often come from various different sources having different formats. For an aspiring data scientist, it is very important that they know their way around data i.e. loading and storing data present in various formats.
We have some data present in string format, discuss ways to load that data into pandas dataframe.
Solution #1: One way to achieve this is by using the StringIO() function. It will act as a wrapper and it will help use read the data using the pd.read_csv() function.
# importing pandas as pdimport pandas as pd  # import the StrinIO function# from io modulefrom io import StringIO  # wrap the string data in StringIO functionStringData = StringIO("""Date;Event;Cost    10/2/2011;Music;10000    11/2/2011;Poetry;12000    12/2/2011;Theatre;5000    13/2/2011;Comedy;8000    """)  # let's read the data using the Pandas# read_csv() functiondf = pd.read_csv(StringData, sep =";")  # Print the dataframeprint(df)
Output :As we can see in the output, we have successfully read the given data in string format into a Pandas DataFrame. Solution 2 : Another fantastic approach is to use the pandas pd.read_clipboard() function.
# importing pandas as pdimport pandas as pd  # This is our string dataStringData ="""Date;Event;Cost    10/2/2011;Music;10000    11/2/2011;Poetry;12000    12/2/2011;Theatre;5000    13/2/2011;Comedy;8000    """  # Now we copy the data to our clipboard.
Output :This is what it looks like after we copy the data to clipboard.
Now we will use pandas pd.read_clipboard() function to read the data into a DataFrame
# Read data df = pd.read_clipboard(sep = ';')  # Print the DataFrameprint(df)
Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
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
Iterate over a list in Python
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
Split String with Comma (,) in Java

Let’s say the following is our string.
String str = " This is demo text, and demo line!";
To split a string with comma, use the split() method in Java.
str.split("[,]", 0);
The following is the complete example.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       String str = "This is demo text, and demo line!";
       String[] res = str.split("[,]", 0);
       for(String myStr: res) {
          System.out.println(myStr);
       }
    }
}
This is demo text
and demo line!
How to see if a widget exists in Tkinter?

To make a particular Tkinter application fully functional and operational, we can use as many widgets as we want. If we want to check if a widget exists or not, then we can use the winfo_exists() method. The method can be invoked with the particular widget we want to check. It returns a Boolean value where True(1) specifies that the widget exists in the application, and False(0) specifies that the widget doesn't exist in the application.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of Tkinter Frame
win = Tk()

# Set the geometry
win.geometry("700x250")

# Define a function to check if a widget exists or not
def check_widget():
   exists = label.winfo_exists()
   if exists == 1:
      print("The widget exists.")
   else:
      print("The widget does not exist.")

# Create a Label widget
label = Label(win, text="Hey There! Howdy?", font=('Helvetica 18 bold'))
label.place(relx=.5, rely=.3, anchor=CENTER)

# We will define a button to check if a widget exists or not
button = ttk.Button(win, text="Check", command=check_widget)
button.place(relx=.5, rely=.5, anchor=CENTER)

win.mainloop()
Running the above code will display a window with a button and a label widget. In the application, we can check if the label widget is present or not.
If you click the button "Check", it will print whether the label widget exists or not.
The widget exists.
LPAD() Function in MySQL

21 Jun, 2021
LPAD() function in MySQL is used to pad or add a string to the left side of the original string. 
Syntax :  
LPAD(str, len, padstr)
Parameter : This function accepts three parameter as mentioned above and described below –  
str – The actual string which is to be padded. If the length of the original string is larger than the len parameter, this function removes the overfloating characters from string.  
 
len – This is the length of a final string after the left padding.  
 
padstr – String that to be added to the left side of the Original Str.  
 
Returns : It returns a new string of length len after padding. 
Example-1 : Applying LPAD() Function to a string to get a new padded string.  
SELECT LPAD("geeksforgeeks", 20, "*") AS LeftPaddedString;
Output : 
 
Example-2 : Applying LPAD() Function to a string when the original string is larger than the len parameter.  
SELECT LPAD("geeksforgeeks", 10, "*") AS LeftPaddedString;
Output : 
 
Example-3 : LPAD Function can also be used to add a string for column data. To demonstrate create a table named Student. 
 
CREATE TABLE Student
(
Student_id INT AUTO_INCREMENT,  
Student_name VARCHAR(100) NOT NULL,
Student_Class VARCHAR(20) NOT NULL,
PRIMARY KEY(Student_id )
);
Now inserting some data to the Student table :  
INSERT INTO Student
(Student_name, Student_Class)
VALUES
('Ananya Majumdar', 'IX'),
('Anushka Samanta', 'X'),
('Aniket Sharma', 'XI'),
('Anik Das', 'X'),
('Riya Jain', 'IX'),
('Tapan Samanta', 'X');
So, the Student Table is as follows. 
 
Now, we are going to add some string to every string presented in the Student_Class column. 
 
SELECT Student_id, Student_name,
LPAD(Student_Class, 10, ' _') AS LeftPaddedString
FROM Student;
Output : 
 
 
sumitgumber28
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to convert a pixel value to a number value using JavaScript ?

11 Oct, 2019
The task is to convert the string value containing ‘px’ to the Integer Value with the help of JavaScript. Here, Few approaches are discussed.Approach 1:
Use parseInt() method which takes string as first argument and return the Integer value.
Example 1: This example uses approach as discussed above
<!DOCTYPE HTML><html>  <head>    <title>        Convert a pixel value to a number value using JavaScript.    </title></head>  <body style="text-align:center;">    <h1 style="color:green;">          GeeksForGeeks     </h1>    <p id="GFG_UP" style="font-size: 19px; font-weight: bold;">    </p>    <button onclick="GFG_Fun()">        click here    </button>    <p id="GFG_DOWN"        style="color: green;              font-size: 24px;               font-weight: bold;">    </p>    <script>        var el_up = document.getElementById("GFG_UP");        var el_down = document.getElementById("GFG_DOWN");        var n = el_up.style.fontSize;        el_up.innerHTML =           "Click on the button to get the number value "+          "from pixel value.<br>Pixel Value - '" + n + "'";          function GFG_Fun() {            el_down.innerHTML = "Integer value is " + parseInt(n, 10);        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Use RegExp which replaces the ‘px’ by empty string and then convert the result to Integer using Number().
Example 2: This example uses approach as discussed above.
<!DOCTYPE HTML><html>  <head>    <title>        Convert a pixel value to a number value using JavaScript.    </title></head>  <body style="text-align:center;">    <h1 style="color:green;">          GeeksForGeeks     </h1>    <p id="GFG_UP" style="font-size: 19px; font-weight: bold;">    </p>    <button onclick="GFG_Fun()">        click here    </button>    <p id="GFG_DOWN"        style="color: green;               font-size: 24px;               font-weight: bold;">    </p>    <script>        var el_up = document.getElementById("GFG_UP");        var el_down = document.getElementById("GFG_DOWN");        var n = el_up.style.fontSize;        el_up.innerHTML = "Click on the button to get the "+          "number value from pixel value.<br>Pixel Value - '" + n + "'";          function GFG_Fun() {            el_down.innerHTML =               "Integer value is " + Number(n.replace(/px$/, ''));        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get all HTML tags with BeautifulSoup

25 Feb, 2021
Web scraping is a process of using bots like software called web scrapers in extracting information from HTML or XML content. Beautiful Soup is one such library used for scraping data through python. Beautiful Soup parses through the HTML content of the web page and collects it to provide iteration, searching and modification features on it. To provide these functionalities it works with a parser that converts the content to a parse tree. Using a parser you are comfortable with It’s fairly easy to crawl through the web pages using BeautifulSoup.  
To get all the HTML tags of a web page using the BeautifulSoup library first import BeautifulSoup and requests library to make a GET request to the web page.
Step-by-step Approach:
Import required modules.
Python3
from bs4 import BeautifulSoupimport requests
After importing the library now assign a URL variable with the URL of the web page and make a GET request to fetch the raw HTML content:
Python3
# Assign URLurl = "https://www.geeksforgeeks.org/"  # Make a GET request to fetch the raw HTML contenthtml_content = requests.get(url).text
Now parse the HTML content:
Python3
# Parse the html content using any parser soup = BeautifulSoup(html_content,"html.parser")
Now to get all the HTML tags of the web page run a loop for the .name attribute of the tag using the find_all() function:
Python3
[tag.name for tag in soup.find_all()]
Below is the complete program:
Python3
# Import modulesfrom bs4 import BeautifulSoupimport requests  # Assign URLurl = "https://www.geeksforgeeks.org/"  # Make a GET request to fetch the raw HTML contenthtml_content = requests.get(url).text  # Parse the html content using any parsersoup = BeautifulSoup(html_content, "html.parser")  # Display HTML tags[tag.name for tag in soup.find_all()]
Output:
['html',
 'head',
 'meta',
 'meta',
 'meta',
 'link',
 'meta',
 'meta',
 'meta',
 'meta',
 'meta',
 'script',
 'script',
 'link',
 'title',
 'link',
 'link',
 'script',
 'script']
Picked
Python BeautifulSoup
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python