code-rag-bench/online-tutorials huggingface dataset:
How to create a Hyperlink using JavaFX?

A Hyperlink is a UI component that responds to clicks and rollovers. You can create a hyperlink by instantiating the javafx.scene.control.Hiperlink class.
The following Example demonstrates the creation of a Hyperlink.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class HiperlinkExample extends Application {
   public void start(Stage stage) {
      //Creating a hyper link
      Hyperlink link = new Hyperlink("https://www.tutorialspoint.com");
      //Creating a vbox to hold the pagination
      VBox vbox = new VBox();
      vbox.setSpacing(5);
      vbox.setPadding(new Insets(50, 50, 50, 60));
      vbox.getChildren().addAll(link);
      //Setting the stage
      Group root = new Group(vbox);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Hyperlink");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Handling missing keys in Python dictionaries

In Python there is one container called the Dictionary. In the dictionaries, we can map keys to its value. Using dictionary the values can be accessed in constant time. But when the given keys are not present, it may occur some errors.
In this section we will see how to handle these kind of errors. If we are trying to access missing keys, it may return errors like this.
 Live Demo
country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}
print(country_dict['Australia'])
print(country_dict['Canada']) # This will return error
AU
---------------------------------------------------------------------------
KeyErrorTraceback (most recent call last)
<ipython-input-2-a91092e7ee85> in <module>()
      2 
      3 print(country_dict['Australia'])
----> 4 print(country_dict['Canada'])# This will return error

KeyError: 'Canada'

We can use the get method to check for keys. This method takes two parameters. The first one is the key, and the second one is the default value.  When the key is found, it will return the value associated with the key, but when the key is not present, it will return the default value, which is passed as second argument.
 Live Demo
country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}
print(country_dict.get('Australia', 'Not Found'))
print(country_dict.get('Canada', 'Not Found'))
AU
Not Found

This setdefault() method is similar to the get() method. It also takes two argument like get(). The first one is the key and the second one is default value. The only difference of this method is, when there is a missing key, it will add new keys with default value.
 Live Demo
country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}
country_dict.setdefault('Canada', 'Not Present') #Set a default value for Canada
print(country_dict['Australia'])
print(country_dict['Canada'])
AU
Not Present

The defaultdict is a container. It is located at the collections module in Python. The defaultdict takes the default factory as its argument. Initially the default factory is set to 0 (integer). When a key is not present, it returns the value of default factory.
We do not need to specify the methods again and again, so it provides faster method for the dictionary objects.
 Live Demo
import collections as col
#set the default factory with the string 'key not present'
country_dict = col.defaultdict(lambda: 'Key Not Present')
country_dict['India'] = 'IN'
country_dict['Australia'] = 'AU'
country_dict['Brazil'] = 'BR'
print(country_dict['Australia'])
print(country_dict['Canada'])
AU
Key Not Present
Convert string to lowercase or uppercase in Arduino

In order to convert a string to lower/upper case, the in-built .toLowerCase() and .toUpperCase() functions can be used.
Note: These functions change the original string itself, and don't return a new string with the changes.
The implementation is shown below −
void setup() {
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello World";
   Serial.println(s1);
   s1.toLowerCase();
   Serial.println(s1);
   s1.toUpperCase();
   Serial.println(s1);
}
void loop() {
   // put your main code here, to run repeatedly:
}
The corresponding Serial Monitor output is −
As you can see, the changes have been made in s1 itself. The return of .toUpperCase() and .toLowerCase() is void.
Must we implement all the methods in a class that implements an interface in Java?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.
There are only two choices −
Implement every method defined by the interface.
Declare the class as an abstract class, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects.
The only case the class do not need to implement all methods in the interface is when any class in its inheritance tree has already provided concrete (i.e. non-abstract) method implementations then the subclass is under no obligation to re-implement those methods. The subclass may not implement the interface at all and just method signature is matched.
interface MyInterface {
   void m() throws NullPointerException;
}
class SuperClass {
   // SuperClass class doesn't implements MyInterface interface
   public void m() {
      System.out.println("Inside SuperClass m()");
   }
}
class SubClass extends SuperClass implements MyInterface {
}
public class Program {
   public static void main(String args[]) {
      SubClass s = new SubClass();
      s.m();
   }
}
Inside SuperClass m()
The above code shows a concrete class SubClass that declares that it implements an interface MyInterface, but doesn't implement the m() method of the interface. The code is legal because it's parent class SuperClass implements a method called m() with the same name as the method in the interface.
How to define a Regular Expression in JavaScript?

A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on the text. A regular expression could be defined with the RegExp () constructor, as follows −
var pattern = new RegExp(pattern, attributes);

or

var pattern = /pattern/attributes;
The following are the parameters −
pattern − A string that specifies the pattern of the regular expression or another regular expression.
attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively.
How to write a JDBC application which connects to multiple databases simultaneously?

To connect with a database, you need to
Register the Driver: Select the required database, register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class.
Register the Driver: Select the required database, register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class.
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get connection: Create a connection object by passing the URL of the database, username and password (of a user in the database) in string format, as parameters to the getConnection() method of the DriverManager class.
Get connection: Create a connection object by passing the URL of the database, username and password (of a user in the database) in string format, as parameters to the getConnection() method of the DriverManager class.
Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password");
To connect to multiple databases in a single JDBC program you need to connect to the two (or more) databases simultaneously using the above steps.
Here, in this example, we are trying to connect to Oracle and MySQL Databases where following are the URLs and sample user credentials of both databases.
import java.sql.Connection;
import java.sql.DriverManager;
public class MultipleConnections {
   public static void main(String[] args) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      //Getting the connection
      String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
      Connection oracleCon = DriverManager.getConnection(oracleUrl, "system", "password");
      System.out.println("oracleConn=" + oracleCon);
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/";
      Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("mysqlConn=" + mysqlCon);
   }
}
oracleConn = oracle.jdbc.driver.T4CConnection@6477463f
mysqlConn = com.mysql.jdbc.JDBC4Connection@3059cbc
Confusing Number II in C++

Suppose we have a digit, now if we rotate that digit by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. But when 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid.
A confusing number is a number that when rotated 180 degrees becomes a new number. So, if we have a positive integer N, we have to find the number of confusing numbers between 1 and N inclusive.
So, if the input is like 20, then the output will be 6
To solve this, we will follow these steps −
Define one map mapping
Define one map mapping
Define an array valid
Define an array valid
Define a function solve(), this will take num, rotate, digit, N,
Define a function solve(), this will take num, rotate, digit, N,
if rotate is not equal to num, then −(increase ret by 1)
if rotate is not equal to num, then −
(increase ret by 1)
(increase ret by 1)
for initialize i := 0, when i < size of valid, update (increase i by 1), do −dig := valid[i]if num * 10 + dig > N, thenCome out from the loopsolve(num * 10 + dig, Define one map, digit * 10, N)
for initialize i := 0, when i < size of valid, update (increase i by 1), do −
dig := valid[i]
dig := valid[i]
if num * 10 + dig > N, thenCome out from the loop
if num * 10 + dig > N, then
Come out from the loop
Come out from the loop
solve(num * 10 + dig, Define one map, digit * 10, N)
solve(num * 10 + dig, Define one map, digit * 10, N)
From the main method do the following −
From the main method do the following −
ret := 0
ret := 0
valid := { 0, 1, 6, 8, 9 }
valid := { 0, 1, 6, 8, 9 }
mapping[0] := 0
mapping[0] := 0
mapping[1] := 1
mapping[1] := 1
mapping[6] := 9
mapping[6] := 9
mapping[9] := 6
mapping[9] := 6
mapping[8] := 8
mapping[8] := 8
solve(1, 1, 10, N)
solve(1, 1, 10, N)
solve(6, 9, 10, N)
solve(6, 9, 10, N)
solve(9, 6, 10, N)
solve(9, 6, 10, N)
solve(8, 8, 10, N)
solve(8, 8, 10, N)
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   int ret;
   map <int, int> mapping;
   vector <int> valid;
   void solve(lli num, lli rotate, lli digit, lli N){
      if (rotate != num) {
         ret++;
      }
      for (int i = 0; i < valid.size(); i++) {
         int dig = valid[i];
         if (num * 10 + dig > N) {
            break;
         }
         solve(num * 10 + dig, mapping[dig] * digit + rotate, digit * 10, N);
      }
   }
   int confusingNumberII(int N) {
      ret = 0;
      valid = { 0, 1, 6, 8, 9 };
      mapping[0] = 0;
      mapping[1] = 1;
      mapping[6] = 9;
      mapping[9] = 6;
      mapping[8] = 8;
      solve(1, 1, 10, N);
      solve(6, 9, 10, N);
      solve(9, 6, 10, N);
      solve(8, 8, 10, N);
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.confusingNumberII(20));
}
20
6
How to display a Listbox with columns using Tkinter?

To deal with lots of data in any application, Tkinter provides a Treeview widget. It has various features such as displaying data in the form of tables consisting of Rows and Columns.
Treeview widget enables the user to add tables, insert data into it, and manipulate the data from the table. The Treeview widget can be constructed by defining the Treeview(parent, column, **options) constructor.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

s = ttk.Style()
s.theme_use('clam')

# Add a Treeview widget
tree = ttk.Treeview(win, column=("c1", "c2", "c3"), show='headings', height=5)

tree.column("# 1", anchor=CENTER)
tree.heading("# 1", text="ID")
tree.column("# 2", anchor=CENTER)
tree.heading("# 2", text="FName")
tree.column("# 3", anchor=CENTER)
tree.heading("# 3", text="LName")

# Insert the data in Treeview widget
tree.insert('', 'end', text="1", values=('1', 'Joe', 'Nash'))
tree.insert('', 'end', text="2", values=('2', 'Emily', 'Mackmohan'))
tree.insert('', 'end', text="3", values=('3', 'Estilla', 'Roffe'))
tree.insert('', 'end', text="4", values=('4', 'Percy', 'Andrews'))
tree.insert('', 'end', text="5", values=('5', 'Stephan', 'Heyward'))

tree.pack()

win.mainloop()
When we execute the above code, it will display a List of items with some columns.
Python | Peak Signal-to-Noise Ratio (PSNR)

06 Feb, 2020
Peak signal-to-noise ratio (PSNR) is the ratio between the maximum possible power of an image and the power of corrupting noise that affects the quality of its representation. To estimate the PSNR of an image, it is necessary to compare that image to an ideal clean image with the maximum possible power.
PSNR is defined as follows: 
    
 Here, L is the number of maximum possible intensity levels (minimum intensity level suppose to be 0) in an image.
MSE is the mean squared error & it is defined as: 
    
  
Where, O represents the matrix data of original image. D represents the matrix data of degraded image. m represents the numbers of rows of pixels and i represents the index of that row of the image. n represents the number of columns of pixels and j represents the index of that column of the image.RMSE is the root mean squared error.
Here, we have an original image and it’s compressed version, let’s see the PSNR value for these images,
Original Image :Compressed Image :
Below is the Python implementation –
from math import log10, sqrtimport cv2import numpy as np  def PSNR(original, compressed):    mse = np.mean((original - compressed) ** 2)    if(mse == 0):  # MSE is zero means no noise is present in the signal .                  # Therefore PSNR have no importance.        return 100    max_pixel = 255.0    psnr = 20 * log10(max_pixel / sqrt(mse))    return psnr  def main():     original = cv2.imread("original_image.png")     compressed = cv2.imread("compressed_image.png", 1)     value = PSNR(original, compressed)     print(f"PSNR value is {value} dB")       if __name__ == "__main__":    main()
Output:
PSNR value is 43.862955653517126 dB 
PSNR is most commonly used to estimate the efficiency of compressors, filters, etc. The larger the value of PSNR, the more efficient is a corresponding compression or filter method.
Image-Processing
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
Python OOPs Concepts
Introduction To PYTHON
Python program to find Last date of Month

11 Jun, 2021
Given a datetime object, the task is to write a Python Program to compute the last date of datetime object Month.
Examples:
Input : test_date = datetime.datetime(2018, 6, 4)
Output : 30
Explanation : April has 30 days, each year
Input : test_date = datetime.datetime(2020, 2, 4)
Output : 29
Explanation : February had 29 days in 2020, leap year.
In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month.
Python3
# Python3 code to demonstrate working of# Get Last date of Month# Using replace() + timedelta()import datetime # initializing datetest_date = datetime.datetime(2018, 6, 4)              # printing original dateprint("The original date is : " + str(test_date)) # getting next month# using replace to get to last day + offset# to reach next monthnxt_mnth = test_date.replace(day=28) + datetime.timedelta(days=4) # subtracting the days from next month date to# get last date of current Monthres = nxt_mnth - datetime.timedelta(days=nxt_mnth.day) # printing resultprint("Last date of month : " + str(res.day))
Output:
The original date is : 2018-06-04 00:00:00
Last date of month : 30
This uses an inbuilt function to solve this problem. In this, given year and month, the range can be computed using monthrange() and its second element can get the result required.
Python3
# Python3 code to demonstrate working of# Get Last date of Month# Using calendar()from datetime import datetimeimport calendar # initializing datetest_date = datetime(2018, 6, 4)              # printing original dateprint("The original date is : " + str(test_date)) # monthrange() gets the date range# required of monthres = calendar.monthrange(test_date.year, test_date.month)[1] # printing resultprint("Last date of month : " + str(res))
Output:
The original date is : 2018-06-04 00:00:00
Last date of month : 30
sooda367
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Search Key from Value

11 Jun, 2021
The problem of finding a value from a given key is quite common. But we may have a problem in which we wish to get the back key from the input key we feed. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using Naive Method In this method, we just run a loop for each of the values and return the corresponding key or keys whose value match. This is the brute force way to perform this particular task. 
Python3
# Python3 code to demonstrate working of# Search Key from Value# Using naive method # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing valueval = 3 # Using naive method# Search key from Valuefor key in test_dict:    if test_dict[key] == val:        res = key # printing resultprint("The key corresponding to value : " + str(res))
The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3}
The key corresponding to value : CS

 Method #2 : Using items() + list comprehension This problem can be easily solved using the items(), which is used to extract both keys and values at once, hence making the search easy and can be executed using list comprehension making it a one liner. 
Python3
# Python3 code to demonstrate working of# Search Key from Value# Using items() + list comprehension # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing valueval = 3 # Using items() + list comprehension# Search key from Valueres = [key for key, value in test_dict.items() if value == val] # printing resultprint("The key corresponding to value : " + str(res))
The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3}
The key corresponding to value : ['CS']

varshagumber28
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
PHP | count() Function

23 May, 2022
This inbuilt function of PHP is used to count the current elements in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0. 
Syntax:
count($array, mode)
Parameters: The function generally takes one parameter that is the array for which the elements is needed to be counted. But in addition, the function can take a parameter mode which tells the function to count element in which normal or recursive mode.
$array (mandatory) : Refers to the array, whose elements are needed to be counted.mode (optional) : This is used to set the mode of the function. The parameter can take two possible values, either 0 or 1. 1 generally indicates to count the values of the array recursively. This helps in counting the multidimensional array. The default value is 0 or False.
$array (mandatory) : Refers to the array, whose elements are needed to be counted.
mode (optional) : This is used to set the mode of the function. The parameter can take two possible values, either 0 or 1. 1 generally indicates to count the values of the array recursively. This helps in counting the multidimensional array. The default value is 0 or False.
Return Values: The function returns the number of elements in an array. Below programs will help in understanding the working of count() function. 
Program 1: Counting normally, that is passing mode as 0 or not passing the parameter mode. 
PHP
<?php // PHP program to illustrate working of count()$array = array("Aakash", "Ravi", "Prashant", "49", "50"); print_r(count($array)); ?>
Output:
5
Program 2: Counting recursively or passing mode as 1. 
PHP
<?php // PHP program to illustrate working of count()$array = array('names' => array('Aakash', 'Ravi', 'Prashant'),               'rollno' => array('5', '10', '15')); // recursive count - mode as 1echo("Recursive count: ".count($array,1)."\n"); // normal count - mode as 0echo("Normal count: ".count($array,0)."\n"); ?>
Output:
Recursive count: 8
Normal count: 2
Reference: http://php.net/manual/en/function.count.php
simmytarika5
PHP-array
PHP-function
PHP
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 ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Calculate standard deviation of a dictionary in Python

31 Aug, 2021
Python dictionary is a versatile data structure that allows a lot of operations to be done without any hassle. Calculating the standard deviation is shown below.
Example #1: Using numpy.std()
First, we create a dictionary. Then we store all the values in a list by iterating over it. After this using the NumPy we calculate the standard deviation of the list.
Python3
# importing numpyimport numpy as np     # creating our test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84}     # declaring an empty listlistr = []     # appending all the values in the listfor value in dicti.values():    listr.append(value)         # calculating standard deviation using np.stdstd = np.std(listr)     # printing resultsprint(std)
Output: 
33.63569532505609  
Example #2: Using list comprehension
First, we create a list of values from the dictionary using a loop. Then we calculate mean, variance and then the standard deviation.
Python3
# creating our test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84} # declaring an empty listlistr = [] # appending all the values in the listfor value in dicti.values():    listr.append(value) # Standard deviation of list# Using sum() + list comprehensionmean = sum(listr) / len(listr)variance = sum([((x - mean) ** 2) for x in listr]) / len(listr)res = variance ** 0.5print(res)
Output: 
33.63569532505609  
Example #3: Using pstdev()
Pythons inbuilt statistics library provides a function to compute the standard deviation of a given list.
Python3
# importing the moduleimport statistics # creating the test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84} # declaring an empty listlistr = [] # appending all the values in the listfor value in dicti.values():    listr.append(value) # Standard deviation of list# Using pstdev()res = statistics.pstdev(listr)print(res)
Output: 
33.63569532505609
kalrap615
Python dictionary-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python Program to Print Lines Containing Given String in File

31 Aug, 2021
In this article, we are going to see how to fetch and display lines containing a given string from a given text file. Assume that you have a text file named geeks.txt saved on the location where you are going to create your python file.
Here is the content of the geeks.txt file:
Approach:
Load the text file into the python program to find the given string in the file.
Ask the user to enter the string that you want to search in the file.
Read the text file line by line using readlines() function and search for the string.
After finding the string, print that entire line and continue the search.
If the string is not found in the entire file, display the proper verdict.
Below is the implementation:
Python3
# Python Program to Print Lines# Containing Given String in File  # input file name with extensionfile_name = input("Enter The File's Name: ")  # using try catch except to# handle file not found error.  # entering try blocktry:      # opening and reading the file     file_read = open(file_name, "r")      # asking the user to enter the string to be     # searched    text = input("Enter the String: ")      # reading file content line by line.    lines = file_read.readlines()      new_list = []    idx = 0      # looping through each line in the file    for line in lines:                  # if line have the input string, get the index         # of that line and put the        # line into newly created list         if text in line:            new_list.insert(idx, line)            idx += 1      # closing file after reading    file_read.close()      # if length of new list is 0 that means     # the input string doesn't    # found in the text file    if len(new_list)==0:        print("\n\"" +text+ "\" is not found in \"" +file_name+ "\"!")    else:          # displaying the lines         # containing given string        lineLen = len(new_list)        print("\n**** Lines containing \"" +text+ "\" ****\n")        for i in range(lineLen):            print(end=new_list[i])        print()  # entering except block# if input file doesn't exist except :  print("\nThe file doesn't exist!")
Output:
Lines containing string
Picked
Python file-handling-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
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
Python | Extract numbers from string

27 Mar, 2019
Many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generally occurs in competitive programming and also in web development. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using List comprehension + isdigit() + split()This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.
# Python3 code to demonstrate# getting numbers from string # using List comprehension + isdigit() +split()  # initializing string test_string = "There are 2 apples for 4 persons"  # printing original string print("The original string : " + test_string)  # using List comprehension + isdigit() +split()# getting numbers from string res = [int(i) for i in test_string.split() if i.isdigit()]  # print resultprint("The numbers list is : " + str(res))
The original string : There are 2 apples for 4 persons
The numbers list is : [2, 4]

 
Method #2 : Using re.findall()This particular problem can also be solved using python regex, we can use the findall function to check for the numeric occurrences using matching regex string.
# Python3 code to demonstrate# getting numbers from string # using re.findall()import re  # initializing string test_string = "There are 2 apples for 4 persons"  # printing original string print("The original string : " + test_string)  # using re.findall()# getting numbers from string temp = re.findall(r'\d+', test_string)res = list(map(int, temp))  # print resultprint("The numbers list is : " + str(res))
The original string : There are 2 apples for 4 persons
The numbers list is : [2, 4]

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Defaultdict in Python
Python program to convert a list to string
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
readelf command in Linux with Examples

12 May, 2022
When we compile source code, an object file is generated of the program and with the help of linker, this object files gets converted to a binary file which, only the machine can understand. This kind of file follows some structures one of which is ELF(Executable and Linkable Format). And to get the information of these ELF files readelf command is used.
1. To display help of readelf command.
$readelf
 This displays the help section of the command containing all its parameters and their uses. 2. To check whether a file is ELF file.
$file elf_file
 If it prints ELF in the output then the file is an ELF file. Note: In our case, file name is elf_file. 3. To generate a elf file using gcc compiler.
$gcc filename.c -o elf_file
 The above command will generate an executable elffile. Note: In our case, the name of file is filename.c and the name of elf file is elf_file. 4. To display file headers of a elf file.
$readelf -h elf_file
 This will display the top-level headers of the elf file. Note: In our case, the name of elf file is elf_file. 5. To display information about the different sections of the process’ address space.
$readelf -S elf_file
  This will display the different sections of the process’ address space. Note: In our case, the name of elf file is elf_file. 6. To display symbols table.
$readelf -s elf_file
  This will display the symbols table of the file. Note: In our case, the name of elf file is elf_file. 7. To display core notes.
$readelf -n elf_files
 This will display the core notes related to the file. Note: In our case, the name of elf file is elf_file. 8. To display relocation section.
$readelf -r elf_file
 This will display the relocks(if present). Note: In our case, the name of elf file is elf_file. 9. To display the dynamic section.
$readelf -d elf_file
 This will display the dynamic section of the file. Note: In our case, the name of elf file is elf_file. 10. To get the version of the readelf command.
$readelf -v
 This will display the version information of the readelf command.
ankita_saini
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
PHP array_values() Function

30 Nov, 2021
In this article, we will see how to get an array value using the array_values() function in PHP, along with understanding their implementation through the example.
The  array_values() is an inbuilt PHP function is used to get an array of values from another array that may contain key-value pairs or just values. The function creates another array where it stores all the values and by default assigns numerical keys to the values.
Syntax:
array array_values($array)
Parameters: This function takes only one parameter $array which is mandatory and refers to the original input array, from which values need to be fetched.
Return Value: This function returns an array with the fetched values, indexed with the numerical keys.
Consider the following examples. Here, we are using the concept of Associative arrays that are used to store key-value pairs.
Input: $array = ("ram"=>25, "krishna"=>10, "aakash"=>20, "gaurav")
Output:
Array
(
    [0] => 25
    [1] => 10
    [2] => 20
    [3] => gaurav
)
Explanation: This array use named keys that we have assigned to them. 
For those array element that has not assigned any value, will display 
their index value.

Input: $array = ("ram", "krishna", "aakash", "gaurav")
Output:
Array
(
    [0] => ram
    [1] => krishna
    [2] => aakash
    [3] => gaurav
)
Explanation: This array displays the array item along with index value.
Example: The below example illustrates the array_values() function in PHP.
PHP
<?php    // PHP function to illustrate the use of array_values()  function Return_Values($array)  {      return (array_values($array));  }  $array = array("ram"=>25, "krishna"=>10, "aakash"=>20, "gaurav");  print_r(Return_Values($array));?>
Output:
Array
(
    [0] => 25
    [1] => 10
    [2] => 20
    [3] => gaurav
)
Reference: http://php.net/manual/en/function.array-values.php
bhaskargeeksforgeeks
PHP-array
PHP-function
PHP
Web technologies Questions
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 ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Remove elements from a JavaScript Array
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Tensorflow.js tf.Tensor .toString() Method

17 May, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
The tf.tensor.toString() method is used to log the tensor in the human-readable form if you console.log() just tf.tensor then it will log the whole tensor object but after using the .toString() method it will log the tensor’s value.
tf.tensor.toString(verbose?)
Parameter: This function accepts single parameter which are illustrated below:
verbose: A boolean value. If it is true then the details of the tensor (dtype, rank, shape, values) will be returned otherwise only the tensor value will be returned. Although this is an optional parameter and by default it is false.
Return value: It returns the tensor value or tensor’s details (dtype, rank, shape, values) in string form.
Example 1: In this example, we are logging the tensor value before and after applying the toString() method.
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"   // Creating the tensorvar val1 = tf.tensor([1, 2]); // Applying the toString() methodvar val2 = val1.toString() // logging the tensorconsole.log(val1)console.log(val2)
Output:
Example 2: In this example, we apply the boolean parameters in the toString() method and see the results.
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"   // Creating the tensorvar val = tf.tensor([1, 2]); // Applying the toString() methodvar val1 = val.toString(true)var val2 = val.toString(false)// logging the tensorconsole.log(val1)console.log(val2)
Output:
Tensor
  dtype: float32
  rank: 1
  shape: [2]
  values:
    [1, 2]
  Tensor
    [1, 2]
bunnyram19
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read Lines from a File in R Programming - readLines() Function - GeeksforGeeks

01 Jul, 2020
readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines.
Syntax: readLines(path)
Parameter:path: path of the file
Example 1:
# R program to illustrate# readLines() function  # Store currently used directorypath <- getwd()  # Write example text to currently used directorywrite.table(x = "the first line\nthe second line\nthe third line",            file = paste(path, "/my_txt.txt", sep = ""),            row.names = FALSE, col.names = FALSE, quote = FALSE)  # Apply readLines function to txt filemy_txt <- readLines(paste(path, "/my_txt.txt", sep = ""))my_txt
Output:
[1] "the first line"  "the second line" "the third line"
Example 2:
# R program to illustrate# readLines() function  # Store currently used directorypath <- getwd()  # Write example text to currently used directorywrite.table(x = "the first line\nthe second line\nthe third line",            file = paste(path, "/my_txt.txt", sep = ""),            row.names = FALSE, col.names = FALSE, quote = FALSE)  # Apply readLines function to first two linesmy_txt_ex2 <- readLines(paste(path, "/my_txt.txt", sep = ""),                        n = 2)my_txt_ex2
Output:
[1] "the first line"  "the second line"
R-FileHandling
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
K-Means Clustering in R Programming
How to create a file upload button with HTML?

To how to create a file upload button with HTML, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<h1>File upload button example</h1>
<p>Click on the "Choose File" button to upload a file:</p>
<form>
<input type="file" id="FILE" name="filename">
</form>
</body>
</html>
The above code will produce the following output −
On clicking the “Choose file” button −
How to resolve "Could not find or load main class package" in Java?

Once you write a Java program you need to compile it using the javac command, this shows you the compile time errors occurred (if any).
Once you resolve them and compile your program success fully, an executable file with the same name as your class name is generated in your current folder, with the .class extension.
Then you need to execute it using the java command as −
java class_name
While executing, when JVM does not find a .class file with the specified name then a run time error occurs saying “Could not found or load main class” error as −
D:\sample>java Example
Error: Could not find or load main class Example
Caused by: java.lang.ClassNotFoundException: Example
To avoid this error, you need to specify the absolute (including packages) name of the .class file (just name) which is in the current directory.
Following are the scenarios where this error could occur −
Wrong class name − You might have specified the wrong class name.
class Example {
   public static void main(String args[]){
      System.out.println("This is an example class");
   }
}
D:\>javac Example.java
D:\>java Exmple
Error: Could not find or load main class Exmple
Caused by: java.lang.ClassNotFoundException: Exmple
Solution − In this the class name is wrongly spelt, we need to correct it.
D:\>javac Example.java
D:\>java Example
This is an example class
Wrong case − You need to specify the name of the class with same case Example.java is different from example.java.
class Example {
   public static void main(String args[]){
      System.out.println("This is an example class");
   }
}
D:\>java EXAMPLE
Error: Could not find or load main class EXAMPLE
Caused by: java.lang.NoClassDefFoundError: Example (wrong name: EXAMPLE)
Solution − In this the class name is with wrong case it, it should be decorated.
D:\>javac Example.java
D:\>java Example
This is an example class
Wrong package − You might have created the .class file in a package and tried to execute without package name or with wrong package name.
package sample;
class Example {
   public static void main(String args[]){
      System.out.println("This is an example class");
   }
}
D:\>javac -d . Example.java
D:\>java samp.Example
Error: Could not find or load main class samp.Example
Caused by: java.lang.ClassNotFoundException: samp.Example
Solution − In this scenario we have mention the name of the wrong package While executing we need to specify the correct package name in which the .class file exists as −
D:\>javac -d . Example.java
D:\>java sample.Example
This is an example class
Inclusion of .class extension − While executing a file there is no need to include the .class extension in your program you just need to specify the name of the class file.
D:\sample>java Example.class
Error: Could not find or load main class Example.class
Caused by: java.lang.ClassNotFoundException: Example.class
Solution − The extension .class is not required while executing the program.
D:\sample>java Example
This is an example class
How to display the date and time of a document when it is last modified in JavaScript?

A document in its lifetime will undergo many changes. Javascript has provided a command called document.lastModified to get the instance when the document is last modified. This command will provide the exact date and time of modification.  
Time = document.lastModified;
In the following example, using the document.lastModified method the documents last modification date and time are displayed as shown in the output.
Live Demo
<html>
<body>
<script>
document.write("This document is lastly modified on" + " " +document.lastModified);
</script>
</body>
</html>
This document is lastly modified on 07/29/2019 15:19:41
In the following example, using the document.lastModified method the documents last modification date and time are displayed as shown in the output. When I modified the document the date and time are 07/29/2019 15:26:23.
Live Demo
<html>
<body>
<p>This document was last modified <span id="modify"></span>.</p>
<script>
document.getElementById("modify").innerHTML = document.lastModified
</script>
</body>
</html>
This document was last modified 07/29/2019 15:26:23.
How to save an Image in OpenCV using C++?

Here, we will understand how to save the OpenCV image to any location on your computer.  OpenCV provides imwrite() function to save an image to a specified file. The file extension represents the image format. 
The actual format of the function is −
imwrite("Destination/Name of the image with extension", Source Matrix)
Here, "Destination" is where we want to save the image. In this program, we save the image as "Lakshmi.jpg". We can give any name to the image. The "Source Matrix" is the matrix where the image has been loaded. In this program, the image is loaded as "myImage" matrix.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main(int argc,const char** argv) {
   Mat myImage;//declaring a matrix named myImage//
   myImage = imread("lena.png");//loading the image named lena in the matrix//
   imwrite("lakshmi.jpg", myImage);  
   waitKey(0);//wait till user press any key
   destroyWindow("MyWindow");//close the window and release allocate memory//
   cout << "Image is saved successfully.....";
   return 0;
}
Image is saved successfully...
How to simulate discrete uniform random variable in R?

There is no function in base R to simulate discrete uniform random variable like we have for other random variables such as Normal, Poisson, Exponential etc. but we can simulate it using rdunif function of purrr package.
The rdunif function has the following syntax −
> rdunif(n, b , a)
Here,
n = Number of random values to return
b = Maximum value of the distribution, it needs to be an integer because the distribution is discrete
a = Minimum value of the distribution, it needs to be an integer because the distribution is discrete
Let’s say you want to simulate 10 ages between 21 to 50. We can do this as follows −
> library(purrr)
> rdunif(10,b=50,a=21)
[1] 38 33 28 36 48 32 47 27 29 24
Now suppose we want to simulate 10 ages and the maximum age is 100 then it can be done as shown below −
> rdunif(10,100)
[1] 2 80 50 50 82 68 45 72 81 25
We can also simulate discrete uniform distribution for negative integers as shown in the below example −
> rdunif(10,10,-5)
[1] 3 -1 -3 3 6 5 3 5 -5 9
We can also create a table of discrete uniform random variable. Let’s say we want to generate 20 random values between -3 and +3 then it can be done as shown below −
> table(rdunif(20, 3, -3))

-3 -2 -1 0 1 3
2 4 4 3 3 4
https://www.tutorialspoint.com/what-is-the-use-of-tilde-operator-in-r
DAX Math & Trigonometric - MOD function

Returns the remainder after a number is divided by a divisor. The result always has the same sign as the divisor.
MOD (<number>, <divisor>)

number
The number for which you want to find the remainder after the division is performed.
divisor
The number by which you want to divide.
A whole number.
If the divisor is 0 (zero), MOD returns an error.
= MOD (5,2) returns 1. 
= MOD (5, -2) returns -1. 

    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