code-rag-bench/online-tutorials huggingface dataset:
Count number of digits after decimal on dividing a number in C++

We are given two integer numbers let’s say num1 and num2 and the task is to divide the num1 with num2 and calculate the count of digits after decimal on dividing these given numbers.
Input − num1 = 2, num2 = 5
Output − count is 1
Explanation − when we divide 2 with 5 i.e. ? = 0.4, so digits after decimal is 1 therefore count is 1.
Input − num1 = 2, num2 = 0
Output − Floating point exception (core dumped)
Explanation − when we divide any number with 0 it will return an error and terminate the program abnormally.
Input − num1 = 2, num2 = 3
Output − Infinite
Explanation − when we divide 2 with 3 i.e. 2/3 = 0.666..., digits after decimal is infinite therefore we will print infinite.
Input two variables let’s say, num1 and num2
Input two variables let’s say, num1 and num2
Create a variable count to store the count of decimal numbers and initializes it with 0
Create a variable count to store the count of decimal numbers and initializes it with 0
Create a variable um of unordered_map type
Create a variable um of unordered_map type
Start loop while num1%num2 != 0
Start loop while num1%num2 != 0
Inside the loop, set num1 with num1%num2
Inside the loop, set num1 with num1%num2
Increment the value of count by 1
Increment the value of count by 1
Check if um.find(num1) != um.end() then return -1
Check if um.find(num1) != um.end() then return -1
Outside the loop, return the value in count.
Outside the loop, return the value in count.
Print the result.
Print the result.
 Live Demo
#include <iostream>
#include <unordered_map>
using namespace std;
int countdigits(int x, int y){
   int result = 0; // result variable
   unordered_map<int, int> mymap;
   // calculating remainder
   while (x % y != 0){
      x = x % y;
      result++;
      if (mymap.find(x) != mymap.end()){
         return -1;
      }
      mymap[x] = 1;
      x = x * 10;
   }
   return result;
}
int main(){
   int res = countdigits(2, 5);
   (res == -1)? cout << "count is Infinty" : cout <<"count is "<<res;
   return 0;
}
If we run the above code we will get the following output −
count is 1
MySQL truncate text with ellipsis?

You can truncate the text with ellipsis using LENGTH() with CASE statement. If your length is greater than 7 then truncate the text and add some number otherwise print the number as it is.
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table TruncateText
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Number longtext,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.66 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into TruncateText(Number) values('64575868667687');
Query OK, 1 row affected (0.11 sec)
mysql> insert into TruncateText(Number) values('7654332');
Query OK, 1 row affected (0.17 sec)
mysql> insert into TruncateText(Number) values('25434656');
Query OK, 1 row affected (0.19 sec)
mysql> insert into TruncateText(Number) values('6457586');
Query OK, 1 row affected (0.17 sec)
mysql> insert into TruncateText(Number) values('958567686868675757574');
Query OK, 1 row affected (0.13 sec)
mysql> insert into TruncateText(Number) values('374785868968787');
Query OK, 1 row affected (0.21 sec)
mysql> insert into TruncateText(Number) values('58969678685858585858585858585');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from TruncateText;
The following is the output:
+----+-------------------------------+
| Id | Number                        |
+----+-------------------------------+
|  1 | 64575868667687                |
|  2 | 7654332                       |
|  3 | 25434656                      |
|  4 | 6457586                       |
|  5 | 958567686868675757574         |
|  6 | 374785868968787               |
|  7 | 58969678685858585858585858585 |
+----+-------------------------------+
7 rows in set (0.00 sec)
In the above sample output, we have some numbers whose length is greater than 7. If the length is greater than 7 then we need to append a numeric number after 7th digit. If the length is 7 or equal to 7 then there is no need to append the numeric number.
The query is as follows:
mysql> SELECT *, CASE WHEN LENGTH(Number) > 7
   -> THEN CONCAT(SUBSTRING(Number, 1, 7), '99999999')
   -> ELSE Number END AS AddNumber
   -> FROM TruncateText;
The following is the output:
+----+-------------------------------+-----------------+
| Id | Number                        | AddNumber       |
+----+-------------------------------+-----------------+
|  1 | 64575868667687                | 645758699999999 |
|  2 | 7654332                       | 7654332         |
|  3 | 25434656                      | 254346599999999 |
|  4 | 6457586                       | 6457586         |
|  5 | 958567686868675757574         | 958567699999999 |
|  6 | 374785868968787               | 374785899999999 |
|  7 | 58969678685858585858585858585 | 589696799999999 |
+----+-------------------------------+-----------------+
7 rows in set (0.00 sec)
Look at the above sample output. If the number is greater than 7, then we have truncated all the values from the number and added a number '99999999' after 7th digit.
How to remove arrows/spinners from input type number with CSS?

Following is the code to remove arrows/spinners from input type using CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
   -webkit-appearance: none;
   margin: 0;
}
input[type="number"] {
   -moz-appearance: textfield;
}
</style>
</head>
<body>
<h1>Input Numbers Hide Arrows</h1>
<input type="number" value="10">
<h2>Only numbers can be entered in the above field</h2>
</body>
</html>
his will produce the following output −
Why we can't initialize static final variable in try/catch block in java?

In Java you can declare three types of variables namely, instance variables, static variables and, local variables.
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword.
In the same way, static variables belong to the class and can be accessed anywhere within the class, which contradicts with the definition of the local variable. Therefore, declaring a static variable inside a method, block or, constructor is not allowed. Still, if you try to declare a static variable within a block a compile time error will be generated.
In the following Java example we are trying to declare a String variable path in the try block.
import java.io.File;
import java.io.FileInputStream;
public class Example {
   public static void main(String args[]){
      System.out.println("Hello");
      try{
         static String path = "my_file";
         File file =new File(path);
         FileInputStream fis = new FileInputStream(file);
      }catch(Exception e){
         System.out.println("Given file path is not found");
      }
   }
}
on compiling, the above program generates the following error.
Example.java:7: error: illegal start of expression
   static String path = "my_file";
   ^
1 error
If you compile the same program in eclipse it generates the following message.
Convert an Object into a Vector in R Programming - as.vector() Function - GeeksforGeeks

17 Jun, 2020
as.vector() function in R Language is used to convert an object into a vector.
Syntax: as.vector(x)
Parameters:x: Object to be converted
Example 1:
# R program to convert an object to vector  # Creating an arrayx <- array(c(2, 3, 4, 7, 2, 5), c(3, 2))x  # Calling as.vector() Functionas.vector(x)
Output:
     [, 1] [, 2]
[1, ]    2    7
[2, ]    3    2
[3, ]    4    5
[1] 2 3 4 7 2 5

Example 2:
# R program to convert an object to vector  # Creating a matrixx <- matrix(c(1:9), 3, 3)x  # Calling as.vector() Functionas.vector(x)
Output:
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1] 1 2 3 4 5 6 7 8 9

R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
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
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
Program to calculate Area Of Octagon

An octagon is a polygon with eight sides. To calculate the area of octagon the following formula is used,
Area of octagon = ((a2*2) / *tan (22.5°)) = ((2*a*a)(1+√2))
Code Logic, The area of a polygon with eight side is calculated by using the above formula. The expression uses sqrt function to find the square root of 2. The value of expression is evaluated as a floating point value that is put into the float area variable.
 Live Demo
#include <stdio.h>
#include <math.h>
int main(){
   int a = 7;
   float area;
   float multiplier = 6.18;
   printf("Program to find area of octagon \n");
   printf("The side of the octagon is %d \n", a);
   area = ((2*a*a)*(1 + sqrt(2)));
   printf("The area of Enneagon is %f \n", area);
   return 0;
}
Program to find area of octagon
The side of the octagon is 7
The area of Enneagon is 236.592926
Read last line from file in PHP

To read last line from file in PHP, the code is as follows −
$line = '';
$f = fopen('data.txt', 'r');
$cursor = -1;
fseek($f, $cursor, SEEK_END);
$char = fgetc($f);
//Trim trailing newline characters in the file
while ($char === "\n" || $char === "\r") {
   fseek($f, $cursor--, SEEK_END);
   $char = fgetc($f);
}
//Read until the next line of the file begins or the first newline char
while ($char !== false && $char !== "\n" && $char !== "\r") {
   //Prepend the new character
   $line = $char . $line;
   fseek($f, $cursor--, SEEK_END);
   $char = fgetc($f);
}
echo $line;
Output will be the last line of the text file will be read and displayed.
The text file is opened in read mode, and the cursor is set to point to -1, i.e. nothing initially. The ‘fseek’ function is used to move to the end of the file or the last line. The line is read until a newline is encountered. After this, the read characters are displayed.
How  to Convert Decimal to Binary Using Recursion in Python?

Binary equivalent of a decimal number is obtained by printing in reverse order the remainder of successive division by 2. The recursive solution to this conversion is as follows:
def tobin(x):
    strbin=''
    if x>1:
        tobin(x//2)
    print (x%2, end='')

num=int(input('enter a number'))
tobin(num)

To test the output, run above code
enter a number25
11001
enter a number16
10000
Quickly convert Decimal to other bases in Python - GeeksforGeeks

05 Jul, 2017
Given a number in decimal number convert it into binary, octal and hexadecimal number. Here is function to convert decimal to binary, decimal to octal and decimal to hexadecimal.
Examples:
Input : 55
Output : 55  in Binary :  0b110111
         55 in Octal :  0o67
         55  in Hexadecimal :  0x37

Input : 282
Output : 282  in Binary :  0b100011010
         282 in Octal :  0o432
         282  in Hexadecimal :  0x11a

One solution is to use the approach discussed in below post.
Convert from any base to decimal and vice versa
Python provides direct functions for standard base conversions like bin(), hex() and oct()
# Python program to convert decimal to binary,# octal and hexadecimal  # Function to convert decimal to binarydef decimal_to_binary(dec):    decimal = int(dec)      # Prints equivalent decimal    print(decimal, " in Binary : ", bin(decimal))  # Function to convert decimal to octaldef decimal_to_octal(dec):    decimal = int(dec)      # Prints equivalent decimal    print(decimal, "in Octal : ", oct(decimal))  # Function to convert decimal to hexadecimaldef decimal_to_hexadecimal(dec):    decimal = int(dec)      # Prints equivalent decimal    print(decimal, " in Hexadecimal : ", hex(decimal))  # Driver programdec = 32decimal_to_binary(dec)decimal_to_octal(dec)decimal_to_hexadecimal(dec)
Output:
32  in Binary :  0b100000
32 in Octal :  0o40
32  in Hexadecimal :  0x20

This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
base-conversion
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Convert integer to string in Python
How to add drag behavior in kivy widget ? - GeeksforGeeks

30 Jun, 2021
In this article, we will develop a GUI window using kivy framework of python, and we will add a Label having drag behavior on this window
Note: You can follow the same pattern for implementing drag events on other widgets also.
Actually what we are doing is we are using are just using the concept of inheritance, and we are making a new widget(DraggableLabel) by combining the properties of Kivy Label widget and Kivy’s DragBehaviour class. And from the code, you can check that we have defined three properties 
drag_rectangle: it is the area in which we want to enable dragging you can see from the code the have used ourselves with the values of this property because we want to enable dragging in the whole Layout.
drag_timeout: it specifies the time after which dragging will be disabled from the Label if Label is not dragged, but it will come into play again if we start dragging.
drag_distance: Distance to move before dragging the DragBehavior, in pixels. As soon as the distance has been traveled, the DragBehavior will start to drag, and no touch event will be dispatched to the children.
And after defining properties we are simply just using our newly created widget as we use others.
Below is the Implementation:
Python3
from kivy.app import Appfrom kivy.uix.label import Label  # importing builder from kivyfrom kivy.lang import Builderfrom kivy.uix.behaviors import DragBehavior  # using this class we will combine# the drag behaviour to our label widgetclass DraggableLabel(DragBehavior, Label):    pass  # this is the main class which# will render the whole applicationclass uiApp(App):      # method which will render our application    def build(self):        return Builder.load_string("""<DraggableLabel>:    drag_rectangle: self.x, self.y, self.width, self.height    drag_timeout: 10000    drag_distance: 0DraggableLabel:    text:"[size=40]GeeksForGeeks[/size]"    markup:True                                   """)  # running the applicationuiApp().run()
Output:
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
F# - Variables

A variable is a name given to a storage area that our programs can manipulate. Each variable has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
The let keyword is used for variable declaration −
For example,
let x = 10

It declares a variable x and assigns the value 10 to it.
You can also assign an expression to a variable −
let x = 10
let y = 20
let z = x + y

The following example illustrates the concept −
let x = 10
let y = 20
let z = x + y

printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z
When you compile and execute the program, it yields the following output −
x: 10
y: 20
z: 30

Variables in F# are immutable, which means once a variable is bound to a value, it can’t be changed. They are actually compiled as static read-only properties.
The following example demonstrates this.
let x = 10
let y = 20
let z = x + y

printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z

let x = 15
let y = 20
let z = x + y

printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z
When you compile and execute the program, it shows the following error message −
Duplicate definition of value 'x'
Duplicate definition of value 'Y'
Duplicate definition of value 'Z'

A variable definition tells the compiler where and how much storage for the variable should be created. A variable definition may specify a data type and contains a list of one or more variables of that type as shown in the following example.
let x:int32 = 10
let y:int32 = 20
let z:int32 = x + y

printfn "x: %d" x
printfn "y: %d" y
printfn "z: %d" z

let p:float = 15.99
let q:float = 20.78
let r:float = p + q

printfn "p: %g" p
printfn "q: %g" q
printfn "r: %g" r
When you compile and execute the program, it shows the following error message −
x: 10
y: 20
z: 30
p: 15.99
q: 20.78
r: 36.77

At times you need to change the values stored in a variable. To specify that there could be a change in the value of a declared and assigned variable, in later part of a program, F# provides the mutable keyword. You can declare and assign mutable variables using this keyword, whose values you will change.
The mutable keyword allows you to declare and assign values in a mutable variable.
You can assign some initial value to a mutable variable using the let keyword. However, to assign new subsequent value to it, you need to use the ← operator.
For example,
let mutable x = 10
x ← 15

The following example will clear the concept −
let mutable x = 10
let y = 20
let mutable z = x + y

printfn "Original Values:"
printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z

printfn "Let us change the value of x"
printfn "Value of z will change too."

x <- 15
z <- x + y

printfn "New Values:"
printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z
When you compile and execute the program, it yields the following output −
Original Values:
x: 10
y: 20
z: 30
Let us change the value of x
Value of z will change too.
New Values:
x: 15
y: 20
z: 35

 Print
 Add Notes
 Bookmark this page
How to check whether a data frame exists or not in R?

Sometimes we keep writing codes in the programming console and suddenly we need to use something that was used in the upper side of programming console then recalling it becomes a little ambiguous if we forget about it. In this case, we might want to check whether something exists or not and that something could be a data frame in R programming. For this purpose, we can use the below syntax −
exists("data_frame_name")&&is.data.frame(get("data_frame_name "))
Consider the below data frame −
 Live Demo
set.seed(101)
x1<-rnorm(20,1,0.5)
x2<-rnorm(20,1,0.25)
df1<-data.frame(x1,x2)
df1
x1 x2
1 0.83698175 0.9590611
2 1.27623093 1.1771305
3 0.66252808 0.9330049
4 1.10717973 0.6340196
5 1.15538461 1.1861090
6 1.58698314 0.6474025
7 1.30939493 1.1167669
8 0.94363284 0.9701700
9 1.45851414 1.1168097
10 0.88837032 1.1245339
11 1.26322405 1.2237343
12 0.60257778 1.0697880
13 1.71387777 1.2519664
14 0.26659015 0.4817234
15 0.88165831 1.2974633
16 0.90333102 0.8189064
17 0.57512263 1.0419959
18 1.02923275 1.2300838
19 0.59116482 0.5820988
20 -0.02515391 1.1121173
exists("df1")&&is.data.frame(get("df1"))
[1] TRUE
Let’s have a look at another example −
 Live Demo
y1<-rpois(20,1)
y2<-rpois(20,5)
y3<-rpois(20,2)
y4<-rpois(20,8)
df2<-data.frame(y1,y2,y3,y4)
df2
   y1 y2  y3 y4
1  2   2  2  11
2  0   4  1  8
3  1   1  1  9
4  0   2  2  4
5  2   8  0  8
6  2   6  3  4
7  0   5  2  11
8  0   5  3  11
9  0   5  5  9
10 2   5  1  7
11 3   4  2  9
12 0   5  0  8
13 0   6  4  13
14 2  5   2  8
15 1  3   1  9
16 0  3  1  10
17 0  6  1  7
18 1  3  3  9
19 0  8  0  5
20 1  4  2  9
exists("df2")&&is.data.frame(get("df2"))
[1] TRUE
How to set NULL values in a table column and insert the same

To set NULL values, set the type as NULL as in the below syntax −
yourColumnName dataType NULL;
Let us first create a table −
mysql> create table DemoTable759 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(100) NULL
);
Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable759(FirstName) values('John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable759(FirstName) values(NULL);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable759(FirstName) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable759(FirstName) values(NULL);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable759;
This will produce the following output. NULL values are also visible in the column −
+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | John      |
|  2 | NULL      |
|  3 | Carol     |
|  4 | NULL      |
+----+-----------+
4 rows in set (0.00 sec)
Maximum distance between two occurrences of same element in array in C

We are given with an array of integers. The array has multiple occurrences of the same elements. The task here is to find the maximum distance between any two same elements of the array. We will pick each element from the array starting from the left. Then we will find the last occurrence of that same number and store the difference between indexes. Now if this difference is maximum then return it.
Input 
Arr[] = { 1,2,4,1,3,4,2,5,6,5 }
Output −Maximum distance between two occurrences of same element in array − 4
Explanation − The repeating numbers with indexes −
1. 1, first index 0, last index 3 distance=3-0-1=2
2. 2, first index 1, last index 6 distance=6-1-1=4
3. 5, first index 7, last index 9 distance=9-7-1=1
Maximum distance between two occurrences of same element : 4
Input 
Arr[] = { 10,20,1,10,10,21,12,0 }
Output −Maximum distance between two occurrences of same element in array − 3
Explanation − The repeating numbers with indexes −
1. 10 first index 0, last index 4 distance=4-0-1=3
Maximum distance between two occurrences of same element : 3
Note − if the input array has no repeating number, then return -1
We take an integer array having repeating numbers as Arr[]
We take an integer array having repeating numbers as Arr[]
The function maxDistance( int arr[],int n) is used to calculate the Maximum distance between two occurrences of the same element.
The function maxDistance( int arr[],int n) is used to calculate the Maximum distance between two occurrences of the same element.
We initialize the variable maxD with -1.
We initialize the variable maxD with -1.
Inside the for loop traverse the array of integers from the beginning.
Inside the for loop traverse the array of integers from the beginning.
In nested for loop traverse the remaining elements and search for repetitions if any. ( if ( arr[i] == arr[j] ).
In nested for loop traverse the remaining elements and search for repetitions if any. ( if ( arr[i] == arr[j] ).
If it is true then calculate the difference between numbers by subtracting the indexes. ( temp=j-i-1)
If it is true then calculate the difference between numbers by subtracting the indexes. ( temp=j-i-1)
If this value is maximum found so far, then store it in maxD
If this value is maximum found so far, then store it in maxD
Return maxD after traversing the whole array.
Return maxD after traversing the whole array.
 Live Demo
#include <stdio.h>
#include <math.h>
int maxDistance(int arr[],int n){
   int size = n;
   int maxD = -1;
   for (int i = 0; i < n - 1; i++)
      for (int j = i + 1; j < n; j++)
         if (arr[i] == arr[j]){
            int temp=abs(j-i-1);
            maxD = maxD>temp?maxD:temp;
         }
   return maxD;
}
// Driver code
int main(){
   int Arr[] = {1,2,4,1,3,4,2,5,6,5};
   printf("Maximum distance between two occurrences of same element in array:%d", maxDistance(Arr,10) );
   return 0;
}
If we run the above code it will generate the following output −
Maximum distance between two occurrences of same element in array − 4
Python - Find the Levenshtein distance using Enchant - GeeksforGeeks

26 May, 2020
Levenshtein distance between two strings is defined as the minimum number of characters needed to insert, delete or replace in a given string string1 to transform it to another string string2.
Examples :
Input : string1 = “geek”, string2 = “gesek”Output : 1Explanation : We can convert string1 into str2 by inserting a ‘s’.
Input : str1 = “cat”, string2 = “cut”Output : 1Explanation : We can convert string1 into str2 by replacing ‘a’ with ‘u’.
Input : string1 = “sunday”, string2 = “saturday”Output : 3Explanation : Last three and first characters are same. We basically need to convert “un” to “atur”. This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a
The Levenshtein distance between two strings can be found using the enchant.utils.levenshtein() method of the enchant module.
Syntax : enchant.utils.levenshtein(string1, string2)
Parameters :string1 : the first string to be comparedstring2 : the second string to be compared
Returns : an integer denoting the Levenshtein distance
# import the enchant moduleimport enchant  # determining the values of the parametersstring1 = "abc"string2 = "aef"  # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2))
Output :
2
Example 2:
# import the enchant moduleimport enchant  # determining the values of the parametersstring1 = "Hello World"string2 = "Hello d"  # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2))
Output :
4
Example 3:
# import the enchant moduleimport enchant  # determining the values of the parametersstring1 = "Computer Science Portal"string2 = "Computer Portal"  # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2))
Output :
8
Python Enchant-module
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions
Reading and Writing to text files in Python
sum() function in Python
Search for partial value match in an Array in PHP

The array_filter function can be used to match a partial value in an array. A callback can be provided, that helps in deciding which elements would remain in the array and which would be removed.
When the callback returns false, it means the given element needs to be removed. Below is a code example demonstrating the same −
$arr = array(0 => 'abc', 1 => 'def', 2 => 'ghijk', 3 => 'lmnxyz');
$results = array();
foreach ($arr as $value) {
   if (strpos($value, 'xyz') !== false) { $results[] = $value; }
}
if( empty($results) ) { echo 'No matches found.'; }
else { echo "'xyz' was found in: " . implode('; ', $results); }
Parsing JSON array with PHP foreach −
'xyz' was found in: lmnxyz
Multiplication Table Generator using Python - GeeksforGeeks

25 Feb, 2021

Prerequisites: Python GUI- Tkinter
We all know that Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. In this article, we will learn How to create a Times-table using Tkinter.
Approach:
Import Tkinter Library
Create Function of Multiplication Table
Create the main window (container)
Create Variabletext field that store value of Number
Call the function By Generate Table Button
Execute code
Program:
Python
 

 
 










#import library 
import sys 
from tkinter import *
  
  
def MultiTable(): 
  
    print("\n:Multiplication Table:\n") 
    print("\nTimes-Table of Number", (EnterTable.get()), '\n') 
  
    for x in range(1, 13): 
        number = int(EnterTable.get()) 
        print('\t\t', (number), 'x', (x), '=', (x*number),) 
  
  
# Create Main window 
Table = Tk() 
Table.geometry('250x250+700+200') 
Table.title('Multiplication Table') 
  
# Variable Declaration 
EnterTable = StringVar() 
  
label1 = Label(Table, text='Enter Your Times-table Number:', 
               font=30, fg='Black').grid(row=1, column=6) 
label1 = Label(Table, text='                     ').grid(row=2, column=6) 
  
# Store Number in Textvariable 
entry = Entry(Table, textvariable=EnterTable, 
              justify='center').grid(row=3, column=6) 
label1 = Label(Table, text='                     ').grid(row=4, column=6) 
  
# Call the function 
button1 = Button(Table, text="Generate Table", fg="Blue", 
                 command=MultiTable).grid(row=5, column=6) 
label1 = Label(Table, text='                     ').grid(row=6, column=6) 
  
# Exit 
EXIT = Button(Table, text="Quit", fg="red", 
              command=Table.destroy).grid(row=7, column=6) 
  
Table.mainloop() 






Output:

Python Tkinter-exercises


Python-tkinter


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 ?
Selecting rows in pandas DataFrame based on conditions
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
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
How to sort a matrix based on one column in R?

Since a matrix contain only numeric values, sorting can be also done for matrices. There might be multiple reasons to sort a matrix such as we want to convert the matrix to a data frame, the data stored in matrix needs to be sorted prior to matrix calculations so that the view of the result after calculations becomes clearer, etc. To sort a matrix based on one column, we can use order function.
set.seed(123)
M1 <-matrix(sample(1:100,20),ncol=2)
M1
[,1] [,2]
[1,] 31 90
[2,] 79 69
[3,] 51 57
[4,] 14 9
[5,] 67 72
[6,] 42 26
[7,] 50 7
[8,] 43 95
[9,] 97 87
[10,] 25 36
Sorting matrix M1 based on column 1 −
M1[order(M1[,1],decreasing=FALSE),]
[,1] [,2]
[1,] 14 9
[2,] 25 36
[3,] 31 90
[4,] 42 26
[5,] 43 95
[6,] 50 7
[7,] 51 57
[8,] 67 72
[9,] 79 69
[10,] 97 87
M1[order(M1[,1],decreasing=TRUE),]
[,1] [,2]
[1,] 97 87
[2,] 79 69
[3,] 67 72
[4,] 51 57
[5,] 50 7
[6,] 43 95
[7,] 42 26
[8,] 31 90
[9,] 25 36
[10,] 14 9
M2 <-matrix(sample(1:10,20,replace=TRUE),ncol=2)
M2
[,1] [,2]
[1,] 1 7
[2,] 7 5
[3,] 5 6
[4,] 10 9
[5,] 7 2
[6,] 9 5
[7,] 9 8
[8,] 10 2
[9,] 7 1
[10,] 5 9
Sorting matrix M2 based on column 2 −
M2[order(M2[,2],decreasing=TRUE),]
[,1] [,2]
[1,] 10 9
[2,] 5 9
[3,] 9 8
[4,] 1 7
[5,] 5 6
[6,] 7 5
[7,] 9 5
[8,] 7 2
[9,] 10 2
[10,] 7 1
M2[order(M2[,2],decreasing=FALSE),]
[,1] [,2]
[1,] 7 1
[2,] 7 2
[3,] 10 2
[4,] 7 5
[5,] 9 5
[6,] 5 6
[7,] 1 7
[8,] 9 8
[9,] 10 9
[10,] 5 9
M3 <-matrix(sample(1:50,20),ncol=2)
M3
[,1] [,2]
[1,] 27 6
[2,] 25 8
[3,] 38 22
[4,] 21 48
[5,] 15 43
[6,] 41 17
[7,] 26 34
[8,] 31 4
[9,] 16 13
[10,] 30 5
Sorting matrix M3 based on column 3 −
M3[order(M3[,2],decreasing=FALSE),]
[,1] [,2]
[1,] 31 4
[2,] 30 5
[3,] 27 6
[4,] 25 8
[5,] 16 13
[6,] 41 17
[7,] 38 22
[8,] 26 34
[9,] 15 43
[10,] 21 48
M3[order(M3[,2],decreasing=TRUE),]
[,1] [,2]
[1,] 21 48
[2,] 15 43
[3,] 26 34
[4,] 38 22
[5,] 41 17
[6,] 16 13
[7,] 25 8
[8,] 27 6
[9,] 30 5
[10,] 31 4
Pascal - Booleans

Pascal provides data type Boolean that enables the programmers to define, store and manipulate logical entities, such as constants, variables, functions and expressions, etc.
Boolean values are basically integer type. Boolean type variables have two pre-defined possible values True and False. The expressions resolving to a Boolean value can also be assigned to a Boolean type.
Free Pascal also supports the ByteBool, WordBool and LongBool types. These are of type Byte, Word or Longint, respectively.
The value False is equivalent to 0 (zero) and any nonzero value is considered True when converting to a Boolean value.  A Boolean value of True is converted to -1 in case it is assigned to a variable of type LongBool.
It should be noted that logical operators and, or and not are defined for Boolean data types.
 A variable of Boolean type is declared using the var keyword.
var
boolean-identifier: boolean;
for example,
var
choice: boolean;
program exBoolean;
var
exit: boolean;

choice: char;
   begin
   writeln('Do you want to continue? ');
   writeln('Enter Y/y for yes, and N/n for no');
   readln(choice);

if(choice = 'n') then
   exit := true
else
   exit := false;

if (exit) then
   writeln(' Good Bye!')
else
   writeln('Please Continue');

readln;
end.
When the above code is compiled and executed, it produces the following result −
Do you want to continue?
Enter Y/y for yes, and N/n for no
N
Good Bye!
Y
Please Continue


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to convert XML file into array in PHP?

To convert the XML document into PHP array, we have to utilize some PHP functions. The procedure is explained underneath with an example.
We have to create an XML file that needs to convert into the array.
abc.xml
<?xml version='1.0'?>
<userdb>
   <firstname name='Alex'>
      <symbol>AL</symbol>
      <code>A</code>
   </firstname>
      <firstname name='Sandra'>
         <symbol>SA</symbol>
         <code>S</code>
   </firstname>
</userdb>


The above XML file will import into PHP using file_get_contents() function which read the entire file as a string and stores into a variable.
After the above step, we can easily convert the string into an object through the inbuilt functions simplexml_load_string() of PHP.
After the above step, we can use json_encode() function to present the object in the json encoded string.
The json_decode() function decode a JSON string. It converts a JSON encoded string into a PHP array.
<?php
// xml file path
   $path = "abc.xml";
   $xmlfile = file_get_contents($path);
   $new = simplexml_load_string($xmlfile);
   $jsonfile = json_encode($new);
   $myarray = json_decode($jsonfile, true);
   print_r($myarray);
?>
Tryit Editor v3.7

Tryit: HTML attribute quotes
Find the length of a set in Python - GeeksforGeeks

07 Jan, 2022
In Python, a Set is a collection data type that is unordered and mutable. A set cannot have duplicate elements. Here, the task is to find out the number of elements present in a set. See the below examples.
Examples:
Input: a = {1, 2, 3, 4, 5, 6}
Output: 6

Input: a = {'Geeks', 'For'}
Output: 2

The idea is use len() in Python
Example 1:
Python3
# Python program to find the length# of set  set1 = set()      # Adding element and tuple to the Set set1.add(8) set1.add(9) set1.add((6, 7))   print("The length of set is:", len(set1))
Output:
The length of set is: 3

Example 2:
Python3
n = len({1, 2, 3, 4, 5})  print("The length of set is:", n)
Output:
The length of set is: 5

How does len() work?len() works in O(1) time as the set is an object and has a member to store its size. Below is description of len() from Python docs.
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
sumitgumber28
python-set
Python
Python Programs
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Capturing JavaScript error in Selenium.

We can capture Javascript error in Selenium. This type of error appears at the Console Tab on opening the Developer tools in the browser. This can occur due to some functional issue in the page or due to extra logs which may cause performance issues.
We can handle the Javascript errors with the driver object and manage method.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import java.util.ArrayList;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import java.util.logging.Level;
import java.util.Set;
public class JavascrptLogErs{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String u = "https://the−internet.herokuapp.com/javascript_error";
      driver.get(u);
      // maximize browser
      driver.manage().window().maximize();
      // to obtain browser errors
      Set<String> logtyp = driver.manage().logs().getAvailableLogTypes();
      for (String s : logtyp) {
         System.out.println(logtyp);
      }
      LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
      List<LogEntry> lg = logEntries.filter(Level.ALL);
      for(LogEntry logEntry : lg) {
         System.out.println(logEntry);
      }
      driver.quit();
   }
}
Python - Convert a list of lists into tree-like dict

Given a nested list we want to convert it to a dictionary whose elements can be considered as part of a tree data structure. In this article we will see the two approaches to convert a nested list into to add dictionary whose elements represent a tree like data structure.
We reverse the items in the list aby slicing and then check if the item is present in the list. If it is not present we ignore it else we add it to the tree.
def CreateTree(lst):
   new_tree = {}
   for list_item in lst:
      currTree = new_tree

      for key in list_item[::-1]:
         if key not in currTree:
            currTree[key] = {}
         currTree = currTree[key]
      return new_tree
# Given list
listA = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']]
print(CreateTree(listA))
Running the above code gives us the following result −
{'X': {'Y': {}, 'Z': {'P': {}}}}
We use the functools and operator module to get the functions reduce and getitem. Using these functions we define two functions to get the items from the list and set the items into a tree structure. Here also we use the slicing approach to reverse the elements of the list and then apply the two created functions to create the dictionaries whose elements are in tree structure.
from functools import reduce
from operator import getitem

def getTree(tree, mappings):
   return reduce(getitem, mappings, tree)

def setTree(tree, mappings):
   getTree(tree, mappings[:-1])[mappings[-1]] = dict()

# Given list
lst = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']]
tree = {}
for i in lst:
   setTree(tree, i[::-1])
print(tree)
Running the above code gives us the following result −
{'X': {'Y': {}, 'Z': {'P': {}}}}
GATE | GATE CS 2010 | Question 65 - GeeksforGeeks

28 Jun, 2021
A system has n resources R0,...,Rn-1,and k processes P0,....Pk-1.The implementation of the resource request logic of each process Pi is as follows: 
 if (i % 2 == 0) {
      if (i < n) request Ri
      if (i+2 < n) request Ri+2
}
else {
      if (i < n) request Rn-i
      if (i+2 < n) request Rn-i-2
}
In which one of the following situations is a deadlock possible?(A) n=40, k=26(B) n=21, k=12(C) n=20, k=10(D) n=41, k=19Answer: (B)Explanation:
Option B is answer

No. of resources, n = 21
No. of processes, k = 12

Processes {P0, P1....P11}  make the following Resource requests:
{R0, R20, R2, R18, R4, R16, R6, R14, R8, R12, R10, R10}

For example P0 will request R0 (0%2 is = 0 and 0< n=21). 

Similarly, P10 will request R10.

P11 will request R10 as n - i = 21 - 11 = 10.

As different processes are requesting the same resource, deadlock
may occur. 
Quiz of this Question
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | Gate IT 2007 | Question 30
Find a triplet that sum to a given value in C++

In this tutorial, we are going to write a program that finds the triplet in the array whose sum is equal to the given number.
Let's see the steps to solve the problem.
Create the array with dummy data.
Create the array with dummy data.
Write three inner loops for three elements which iterate until the end of the array.Add the three elements.Compare the sum with the given number.If both are equal, then print the elements and break the loops.
Write three inner loops for three elements which iterate until the end of the array.
Add the three elements.
Add the three elements.
Compare the sum with the given number.
Compare the sum with the given number.
If both are equal, then print the elements and break the loops.
If both are equal, then print the elements and break the loops.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
bool findTriplet(int arr[], int arr_size, int sum) {
   for (int i = 0; i < arr_size - 2; i++) {
      for (int j = i + 1; j < arr_size - 1; j++) {
         for (int k = j + 1; k < arr_size; k++) {
            if (arr[i] + arr[j] + arr[k] == sum) {
               cout << arr[i] << " " << arr[j] << " " << arr[k] << endl;
               return true;
            }
         }
      }
   }
   return false;
}
int main() {
   int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
   findTriplet(arr, 7, 12);
   return 0;
}
If you execute the above program, then you will get the following result.
1 4 7
If you have any queries in the tutorial, mention them in the comment section.
Getting the Cursor position in Tkinter Entry widget

We are already familiar with input forms where various single Entry fields are created to capture the user input. With Tkinter, we can also create a single input field using the Entry widget. Each character in the Entry field that the user enters is indexed. Thus, you can retrieve this index to get the current position of the cursor by using the index() method. To retrieve the current location of the cursor, you can pass the INSERT argument in this function.
# Import required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter window
win = Tk()
win.geometry("700x350")
win.title("Get the Cursor Position")

# Create an instance of style class
style=ttk.Style(win)

# Function to retrieve the current position of the cursor
def get_current_info():
   print ("The cursor is at: ", entry.index(INSERT))

# Create an entry widget
entry=ttk.Entry(win, width=18)
entry.pack(pady=30)


# Create a button widget
button=ttk.Button(win, text="Get Info", command=get_current_info)
button.pack(pady=30)

win.mainloop()
Running the above code will display a window with an Entry widget and a button which can be used to get the current index of the cursor.
Type some text in the Entry widget and click the "Get Info" button. It will print the current location of the cursor on the console.
The cursor is at: 15
JavaScript JSON.stringify() with Example

The JavaScript JSON.stringify() is used for converting JavaScript object into a string. It is particularly useful when sending data to a web server.
Following is the code for JSON stringify() method −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JSON.stringify()</h1>
<div class="sample"></div>
<div style="font-weight: bold;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to convert the above object into a JSON string
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resultEle = document.querySelector(".result");
   let obj = {name: "Rohan",sports: ["Cricket", "Football"],Country: "India",};
   sampleEle.innerHTML ="Name = " +obj.name +"<br>" +" Country = " +obj.Country +
      " <br>" +"sports = " +obj.sports;
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML = JSON.stringify(obj);
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
How to select last 10 rows from MySQL?

To select last 10 rows from MySQL, we can use a subquery with SELECT statement and Limit concept. The following is an example.
Creating a table.
mysql> create table Last10RecordsDemo
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.75 sec)
Inserting records into the table.
mysql> insert into Last10RecordsDemo values(1,'John'),(2,'Carol'),(3,'Bob'),(4,'Sam'),(5,'David'),(6,'Taylor');
Query OK, 6 rows affected (0.12 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> insert into Last10RecordsDemo values(7,'Sam'),(8,'Justin'),(9,'Ramit'),(10,'Smith'),(11,'Clark'),(12,'Johnson');
Query OK, 6 rows affected (0.14 sec)
Records: 6  Duplicates: 0  Warnings: 0
To display all records.
mysql> select *from Last10RecordsDemo;
The following is the output.
+------+---------+
| id   | name    |
+------+---------+
|    1 | John    |
|    2 | Carol   |
|    3 | Bob     |
|    4 | Sam     |
|    5 | David   |
|    6 | Taylor  |
|    7 | Sam     |
|    8 | Justin  |
|    9 | Ramit   |
|   10 | Smith   |
|   11 | Clark   |
|   12 | Johnson |
+------+---------+
12 rows in set (0.00 sec)

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause.
SELECT * FROM (
   SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10
)Var1
   ORDER BY id ASC;
Let us now implement the above query.
mysql> SELECT * FROM (
   ->     SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10
   -> )Var1
   ->
   -> ORDER BY id ASC;
The following is the output that displays the last 10 records.
+------+---------+
| id   | name    |
+------+---------+
|    3 | Bob     |
|    4 | Sam     |
|    5 | David   |
|    6 | Taylor  |
|    7 | Sam     |
|    8 | Justin  |
|    9 | Ramit   |
|   10 | Smith   |
|   11 | Clark   |
|   12 | Johnson |
+------+---------+
10 rows in set (0.00 sec)

We can match both records with the help of the SELECT statement.