code-rag-bench/online-tutorials huggingface dataset:
Perl Numeric Equality Operators Example

These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20 then, lets check the following numeric equality operators −
== (equal to)
Checks if the value of two operands are equal or not, if yes then condition becomes true.
Example − ($a == $b) is not true.
!= (not equal to)
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
Example − ($a != $b) is true.
<=>
Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument.
Example − ($a <=> $b) returns -1.
> (greater than)
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
Example − ($a > $b) is not true.
< (less than)
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
Example − ($a < $b) is true.
>= (greater than or equal to)
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
Example − ($a >= $b) is not true.
<= (less than or equal to)
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
Example − ($a <= $b) is true.
Try the following example to understand all the numeric equality operators available in Perl. Copy and paste the following Perl program in test.pl file and execute this program.
#!/usr/local/bin/perl
 
$a = 21;
$b = 10;

print "Value of \$a = $a and value of \$b = $b\n";

if( $a == $b ) {
   print "$a == \$b is true\n";
} else {
   print "\$a == \$b is not true\n";
}

if( $a != $b ) {
   print "\$a != \$b is true\n";
} else {
   print "\$a != \$b is not true\n";
}

$c = $a <=> $b;
print "\$a <=> \$b returns $c\n";

if( $a > $b ) {
   print "\$a > \$b is true\n";
} else {
   print "\$a > \$b is not true\n";
}

if( $a >= $b ) {
   print "\$a >= \$b is true\n";
} else {
   print "\$a >= \$b is not true\n";
}

if( $a < $b ) {
   print "\$a < \$b is true\n";
} else {
   print "\$a < \$b is not true\n";
}

if( $a <= $b ) {
   print "\$a <= \$b is true\n";
} else {
   print "\$a <= \$b is not true\n";
}
When the above code is executed, it produces the following result −
Value of $a = 21 and value of $b = 10
$a == $b is not true
$a != $b is true
$a <=> $b returns 1
$a > $b is true
$a >= $b is true
$a < $b is not true
$a <= $b is not true


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How can we remove PRIMARY KEY constraint from a column of an existing MySQL table?

We can remove PRIMARY KEY constraint from a column of an existing table by using DROP keyword along with ALTER TABLE statement.
Suppose we have a table ‘Player’ having a PRIMARY KEY constraint on column ‘ID’ as follows −
mysql> DESCRIBE Player;

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    |  int(11)    | NO   | PRI | NULL    |       |
| Name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

2 rows in set (0.04 sec) 
Now if we want to remove the PRIMARY KEY constraint then we can use ALTER TABLE statement as follows −
mysql> alter table Player DROP PRIMARY KEY;
Query OK, 0 rows affected (0.31 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> DESCRIBE Player;

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    |  int(11)  | NO     |     | NULL    |       |
| Name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

2 rows in set (0.04 sec) 
The above result set shows that PRIMARY KEY constraint on column ‘ID’ has been removed.
Prime or not in Python

17 Aug, 2017
Every programmer comes across the problem of checking whether a number is prime and indeed it’s one of the basic level program in any language. I also tried it in many different languages, but the best language that I found to implement it is Python. It’s just one single line and the program does it all. Its so simple and smooth than other languages.
The concept of Any and All has really reduced this problem to a single line and yes it is fast too.The logic used in this program is based on school method to check prime.
# Returns true if n is prime else falsedef prime(n):    return all([(n % j) for j in range(2, int(n**0.5)+1)]) and n>1  # Driver coden = 41if prime(n):       print("Yes")else:    print("No")
Yes

This article is contributed by Chinmoy Lenka. 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.
Prime Number
Python
Prime Number
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
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
NumPy - Array From Existing Data

In this chapter, we will discuss how to create an array from existing data.
This function is similar to numpy.array except for the fact that it has fewer parameters. This routine is useful for converting Python sequence into ndarray.
numpy.asarray(a, dtype = None, order = None)

The constructor takes the following parameters.
a
Input data in any form such as list, list of tuples, tuples, tuple of tuples or tuple of lists
dtype
By default, the data type of input data is applied to the resultant ndarray
order
C (row major) or F (column major). C is default
The following examples show how you can use the asarray function.
# convert list to ndarray 
import numpy as np 

x = [1,2,3] 
a = np.asarray(x) 
print a
Its output would be as follows −
[1  2  3] 

# dtype is set 
import numpy as np 

x = [1,2,3]
a = np.asarray(x, dtype = float) 
print a
Now, the output would be as follows −
[ 1.  2.  3.] 

# ndarray from tuple 
import numpy as np 

x = (1,2,3) 
a = np.asarray(x) 
print a
Its output would be −
[1  2  3]

# ndarray from list of tuples 
import numpy as np 

x = [(1,2,3),(4,5)] 
a = np.asarray(x) 
print a
Here, the output would be as follows −
[(1, 2, 3) (4, 5)]

This function interprets a buffer as one-dimensional array. Any object that exposes the buffer interface is used as parameter to return an ndarray.
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

The constructor takes the following parameters.
buffer
Any object that exposes buffer interface
dtype
Data type of returned ndarray. Defaults to float
count
The number of items to read, default -1 means all data
offset
The starting position to read from. Default is 0
The following examples demonstrate the use of frombuffer function.
import numpy as np 
s = 'Hello World' 
a = np.frombuffer(s, dtype = 'S1') 
print a
Here is its output −
['H'  'e'  'l'  'l'  'o'  ' '  'W'  'o'  'r'  'l'  'd']

This function builds an ndarray object from any iterable object. A new one-dimensional array is returned by this function.
numpy.fromiter(iterable, dtype, count = -1)

Here, the constructor takes the following parameters.
iterable
Any iterable object
dtype
Data type of resultant array
count
The number of items to be read from iterator. Default is -1 which means all data to be read
The following examples show how to use the built-in range() function to return a list object. An iterator of this list is used to form an ndarray object.
# create list object using range function 
import numpy as np 
list = range(5) 
print list
Its output is as follows −
[0,  1,  2,  3,  4]

# obtain iterator object from list 
import numpy as np 
list = range(5) 
it = iter(list)  

# use iterator to create ndarray 
x = np.fromiter(it, dtype = float) 
print x
Now, the output would be as follows −
[0.   1.   2.   3.   4.]


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Python | Numpy ndarray.__abs__() - GeeksforGeeks

05 Mar, 2019
With the help of Numpy ndarray.__abs__(), one can find the absolute value of each and every element in an array. Suppose we have a values 1.34, with the help of ndarray.__abs__() it will converted into 1.
Syntax: ndarray.__abs__(self)
Return: floor(self)
Example #1 :In this example we can see that after applying ndarray.__abs__(), we get the simple array that can contain the absolute values of all the elements of an array.
# import the important module in pythonimport numpy as np  # make an array with numpygfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12])  # applying ndarray.____() methodprint(gfg.__abs__())
[ 1  2  3  4  5  6]

Example #2 :
# import the important module in pythonimport numpy as np  # make an array with numpygfg = np.array([[1.22, 2.25, -3.21, 4.45, 5.56, 6],                [-6.65, 5.55, 4.32, 3.33, 2.12, -1.05]])  # applying ndarray.__abs__() methodprint(gfg.__abs__())
[[ 1  2  3  4  5  6 ]
 [ 6  5  4  3  2  1]]

Python numpy-ndarray
Python-numpy
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 ?
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()
Python | Frequency of numbers in String - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Strings, we can have a problem in which we need to check how many of numerics are present in strings. This is a common problem and have application across many domains like day-day programming and data science. Lets discuss certain ways in which this task can be performed.
Method #1 : Using re.findall() + len()The combination of above functions can be used to perform this task. In this, we check for all numbers and put in list using findall() and the count is extracted using len().
# Python3 code to demonstrate working of # Frequency of numbers in String# Using re.findall() + len()import re  # initializing stringtest_str = "geeks4feeks is No. 1 4 geeks"  # printing original stringprint("The original string is : " + test_str)  # Frequency of numbers in String# Using re.findall() + len()res = len(re.findall(r'\d+', test_str))  # printing result print("Count of numerics in string : " + str(res)) 
The original string is : geeks4feeks is No. 1 4 geeks
Count of numerics in string : 3

 
Method #2 : Using sum() + findall()The combination of above functions can also be used to solve this problem. In this, we cumulate the sum using sum(). The task of findall() is to find all the numerics.
# Python3 code to demonstrate working of # Frequency of numbers in String# Using re.findall() + sum()import re  # initializing stringtest_str = "geeks4feeks is No. 1 4 geeks"  # printing original stringprint("The original string is : " + test_str)  # Frequency of numbers in String# Using re.findall() + sum()res = sum(1 for _ in re.finditer(r'\d+', test_str))   # printing result print("Count of numerics in string : " + str(res)) 
The original string is : geeks4feeks is No. 1 4 geeks
Count of numerics in string : 3

Python string-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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Wand deskew() function - Python - GeeksforGeeks

18 Aug, 2021
The deskew() function is an inbuilt function in the Python Wand ImageMagick library which is used to remove skew artifacts common with most scanning & optical import devices. 
Syntax:  
edge(threshold)
Parameters: This function accepts single parameter as mentioned above and defined below:  
threshold: This parameter stores the limit between foreground & background. It ranges from 0 to 1.0.
Return Value: This function returns the Wand ImageMagick object.
Original Image:  
Example 1:  
Python3
# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image:    # Clone the image in order to process    with image.clone() as deskew:        # Invoke deskew function        deskew.deskew(0.1)        # Save the image        deskew.save(filename ='deskew1.jpg')
Output:  
Example 2:  
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw:    # Set Stroke color the circle to black    draw.stroke_color = Color('black')    # Set Width of the circle to 2    draw.stroke_width = 1    # Set the fill color to 'White (# FFFFFF)'    draw.fill_color = Color('white')     # Invoke Circle function with center at 50, 50 and radius 25    draw.circle((200, 200), # Center point                (100, 100)) # Perimeter point    # Set the font style    draw.font = '../Helvetica.ttf'    # Set the font size    draw.font_size = 30         with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic:        # Set the text and its location        draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !')        # Draw the picture        draw(pic)        # Invoke deskew function        pic.deskew(0.7)        # Save the image        pic.save(filename ='deskew2.jpg')
Output:  
 
sweetyty
Image-Processing
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
SQL Query to Find all the Students with Marks Greater than Average Marks - GeeksforGeeks

19 Apr, 2021
Query in SQL is like a statement that performs a task. Here, we need to write a query to find all the students whose marks are greater than the average marks of students.
We will first create a database named “geeks” then we will create a table “Students” in that database.
We can create a Database using the command:
Syntax: CREATE DATABASE DATABASE_NAME;
So let’s create a geeks database as shown below:
CREATE DATABASE geeks;
Use the below command to use the geeks database:
USE geeks;
To add a table into the database we use the below command:
Syntax: CREATE TABLE table_name (Attribute_name datatype...);
So, let’s create a students table within the geeks database as shown below:
CREATE TABLE Students(
Id int,
Name varchar(20),
TotalMarks int);
Here Table Added Successfully.
To see the description of the table:
EXEC sp_columns Students;
For inserting records into the table we can use the below command:
Syntax: INSERT INTO table_name(column1,
                column2,
                column 3,.....)
                 VALUES( value1,
                value2,
                value3,.....);
So let’s add some records to the students table:
INSERT INTO Students VALUES (1,'Neha',90);
INSERT INTO Students VALUES (2,'Sahil',50);
INSERT INTO Students VALUES (3,'Rohan',70);
INSERT INTO Students VALUES (4,'Ankita',80);
INSERT INTO Students VALUES (5,'Rahul',65);
INSERT INTO Students VALUES (6,'Swati',55);
INSERT INTO Students VALUES (7,'Alka',75);
Now let us print the data available in the table using the SELECT statement as shown below:
SELECT * FROM department;
Note: Here * represents all. If we execute this query, the entire table will be displayed.
Output :
Use the below syntax for querying for all students with greater marks than the average of the class:
Syntax:
SELECT column1 FROM table_name
WHERE column2 > (SELECT AVG(
                            column2) 
FROM table_name);
Now use the above syntax to make the query on our students table as shown below:
SELECT Name FROM Students WHERE TotalMarks > (SELECT AVG(TotalMarks) FROM Students);
Output:
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL - ORDER BY
SQL | Subquery
Can we define an enum inside a class in Java?

Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
Live Demo
public class EnumerationExample {
   enum Enum {
      Mango, Banana, Orange, Grapes, Thursday, Apple
   }
   public static void main(String args[]) {
      Enum constants[] = Enum.values();
      System.out.println("Value of constants: ");  
      for(Enum d: constants) {
         System.out.println(d);
      }
   }
}
Value of constants:
Mango
Banana
Orange
Grapes
Thursday
Apple
Live Demo
enum Vehicles {
   //Declaring the constants of the enum
   ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
   int i; //Instance variable
   Vehicles() { //constructor
   }  
   public void enumMethod() { //method
      System.out.println("Current value: "+Vehicles.this);
   }
}
public class Sam{
   public static void main(String args[]) {
      Vehicles vehicles[] = Vehicles.values();
      for(Vehicles veh: vehicles) {
         System.out.println(veh);
      }
      vehicles[3].enumMethod();      
   }  
}
ACTIVA125
ACTIVA5G
ACCESS125
VESPA
TVSJUPITER
Current value: VESPA
Dictionary Data Type in Python

Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −
 Live Demo
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
This produce the following result −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.
Materialize - Typography

Materialize uses Roboto 2.0 as a standard font. It can be overridden using the following CSS style.
html {
   font-family: GillSans, Calibri, Trebuchet, sans-serif;
}
Following are the examples of headings, blockquotes and free-flow but responsive text.
<!DOCTYPE html>
<html>
   <head>
      <title>The Materialize Typography Example</title>
         <meta name="viewport" content="width=device-width, initial-scale=1">
         <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
         <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
   </head>
   <body class="container">
      <h2>Typography Demo</h2>
         <hr/>
         <h3>Headings</h3>
      <div class="card-panel">
         <h1>Heading 1</h1>
         <h2>Heading 2</h2>
         <h3>Heading 3</h3>
         <h4>Heading 4</h4>
         <h6>Heading 6</h6>
      </div>
         <h3>Block Quotes</h3>
      <div class="card-panel">
         <blockquote>
            The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.
         </blockquote>
      </div>
         <h3>Responsive free-flow text</h3>
      <div class="card-panel">
         <p class="flow-text">
         The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.
         </p>
      </div>
   </body>
</html>
Verify the output.
 Print
 Add Notes
 Bookmark this page
MySQL - Connection

You can establish the MySQL database using the mysql binary at the command prompt.
Here is a simple example to connect to the MySQL server from the command prompt −
[root@host]# mysql -u root -p
Enter password:******

This will give you the mysql> command prompt where you will be able to execute any SQL command. Following is the result of above command −
The following code block shows the result of above code −
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2854760 to server version: 5.0.9

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

In the above example, we have used root as a user but you can use any other user as well. Any user will be able to perform all the SQL operations, which are allowed to that user.
You can disconnect from the MySQL database any time using the exit command at mysql> prompt.
mysql> exit
Bye

PHP provides mysqli contruct or mysqli_connect() function to open a database connection. This function takes six parameters and returns a MySQL link identifier on success or FALSE on failure.
$mysqli = new mysqli($host, $username, $passwd, $dbName, $port, $socket);

$host
Optional − The host name running the database server. If not specified, then the default value will be localhost:3306.
$username
Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process.
$passwd
Optional − The password of the user accessing the database. If not specified, then the default will be an empty password.
$dbName
Optional − database name on which query is to be performed.
$port
Optional − the port number to attempt to connect to the MySQL server.
$socket
Optional − socket or named pipe that should be used.
You can disconnect from the MySQL database anytime using another PHP function close().
$mysqli->close();

Try the following example to connect to a MySQL server −
Copy and paste the following example as mysql_example.php −
<html>
   <head>
      <title>Connecting MySQL Server</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');
         $mysqli->close();
      ?>
   </body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.


    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Python - Convert List to Single valued Lists in Tuple - GeeksforGeeks

10 Jul, 2020
Conversion of data types is the most common problem across CS domain nowdays. One such problem can be converting List elements to single values lists in tuples. This can have application in data preprocessing domain. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [1, 3, 5, 6, 7, 9]Output : ([1], [3], [5], [6], [7], [9])
Input : test_list = [1]Output : ([1])
Method #1 : Using list comprehension + tuple()This is one of the ways in which this task can be performed. In this, we construct and iterate the list using list comprehension and finally convert the result list to tuple using tuple().
# Python3 code to demonstrate working of # Convert List to Single valued Lists in Tuple# Using list comprehension + tuple()  # initializing liststest_list = [6, 8, 4, 9, 10, 2]  # printing original listprint("The original list is : " + str(test_list))  # Convert List to Single valued Lists in Tuple# Using list comprehension + tuple()res = tuple([ele] for ele in test_list)  # printing result print("Tuple after conversion : " + str(res)) 
The original list is : [6, 8, 4, 9, 10, 2]
Tuple after conversion : ([6], [8], [4], [9], [10], [2])

 
Method #2 : Using map() + list() + zip() + tuple()The combination of above functions can be used to solve this problem. In this, we perform task of extending logic of conversion to each element using map(), and list conversion to each element using zip(). At end, the result is converted back to tuple using tuple().
# Python3 code to demonstrate working of # Convert List to Single valued Lists in Tuple# Using map() + list() + zip() + tuple()  # initializing liststest_list = [6, 8, 4, 9, 10, 2]  # printing original listprint("The original list is : " + str(test_list))  # Convert List to Single valued Lists in Tuple# Using map() + list() + zip() + tuple()res = tuple(map(list, zip(test_list)))  # printing result print("Tuple after conversion : " + str(res)) 
The original list is : [6, 8, 4, 9, 10, 2]
Tuple after conversion : ([6], [8], [4], [9], [10], [2])

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to print without newline in Python?
NLG for Fun — Automated Headlines Generator | by AbdulMajedRaja RS | Towards Data Science

Natural Language Generation is a very important area to be explored in our time. It forms the basis of how a bot would communicate with — not like how literates write books but like how we talk. In this Kernel, I’d like to show you a very simple but powerful Python module that does a similar exercise in (literally) a couple of lines of code.
Module: Markovify
The Py module we use here is markovify.
Descrption of Markovify:
Markovify is a simple, extensible Markov chain generator. Right now, its main use is for building Markov models of large corpora of text, and generating random sentences from that. But, in theory, it could be used for other applications.
About the Dataset:
This includes the entire corpus of articles published by the ABC website in the given time range. With a volume of 200 articles per day and a good focus on international news, we can be fairly certain that every event of significance has been captured here. This dataset can be downloaded from Kaggle Datasets.
Markov chains, named after Andrey Markov, are mathematical systems that hop from one “state” (a situation or set of values) to another. For example, if you made a Markov chain model of a baby’s behavior, you might include “playing,” “eating”, “sleeping,” and “crying” as states, which together with other behaviors could form a ‘state space’: a list of all possible states. In addition, on top of the state space, a Markov chain tells you the probabilitiy of hopping, or “transitioning,” from one state to any other state — -e.g., the chance that a baby currently playing will fall asleep in the next five minutes without crying first.
Read more about how Markov Chain works in this interactive article by Victor Powell
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)import markovify #Markov Chain Generator# Any results you write to the current directory are saved as output.
inp = pd.read_csv('../input/abcnews-date-text.csv')inp.head(3)publish_date headline_text020030219 aba decides against community broadcasting lic...120030219 act fire witnesses must be aware of defamation220030219a g calls for infrastructure protection summit
text_model = markovify.NewlineText(inp.headline_text, state_size = 2)
# Print five randomly-generated sentencesfor i in range(5):    print(text_model.make_sentence())iron magnate poised to storm cleanupmeet the png government defends stockdale appointmentthe twitter exec charged with animal cruelty trialpm denies role in pregnancyshoalhaven business boosts hunter
Now, this text could become input for a Twitter Bot, Slack Bot or even a Parody Blog. And that’s the point.
References:
Github RepoKaggle KernelMarkov Chains explained VisuallyInput Dataset
Github Repo
Kaggle Kernel
Markov Chains explained Visually
JavaScript program to retrieve clients IP address

Following is the code for retrieving clients IP address −
 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;
   }
   .result {
      font-weight: 500;
      font-size: 18px;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Retrieve clients IP address</h1>
<div class="result"></div>
<script type="application/javascript">
   let resEle = document.querySelector(".result");
   function showIP(json) {
      resEle.innerHTML = "My public IP address is: " + json.ip;
   }
</script>
<script type="application/javascript" src="http://ipinfo.io/?format=jsonp&callback=showIP"></script>
</body>
</html>
Kotlin Tail Recursion - GeeksforGeeks

28 Mar, 2022
In traditional recursion call, we perform our recursive call first, and then we take the return value of the recursive call and calculate the result. But in tail recursion, we perform the calculation first, and then we execute the recursive call, passing the results of the current step to the next recursive call. In the end, both recursion and tail recursion gives same output. The must follow rule for the tail recursion is that recursive call should be the last call of the method.
In tail recursion, function call is the last thing executed by the function and nothing left in the current function to execute. So, there is no need to save current function call in stack memory and compiler can re-use that stack space for next recursive call.In tail recursion, we do not get the StackOverflowError during the execution of program.
In tail recursion, function call is the last thing executed by the function and nothing left in the current function to execute. So, there is no need to save current function call in stack memory and compiler can re-use that stack space for next recursive call.
In tail recursion, we do not get the StackOverflowError during the execution of program.
Example 1: Find the factorial of a number using tail-recursion. 
Kotlin
// Kotlin program of factorial using tail-recursionfun Fact(num: Int, x:Int):Long{     return if(num==1)   // terminate condition        x.toLong()    else        Fact(num-1,x*num)   //tail recursion}fun main() {    var n = 1    var result = Fact(5,n)    println("Factorial of 5 is: $result")}
Output:
Factorial of 5 is: 120
Working of the above program-Example 2: Find the sum of elements of an array using tail-recursion 
Kotlin
// two parameters passed an array and size of arrayfun sum(args: Array<Int> , index:Int, s : Int = 0 ):Int{    return if(index<=0) s    else sum(args ,index-1, s + args[index-1])     // tail-recursion} fun main() {    // array initialization    val array = arrayOf(1,2,3,4,5,6,7,8,9,10)    // size of array    val n = array.size    val result = sum(array,n)             // normal function call    println("The sum of array elements is: $result")}
Output:
The sum of array elements is: 55
Explanation: Here, we have passed the array as an argument along with two other parameters in sum() function. The default value of (s) parameter is equal to zero. We are calculating the sum of elements, from the last index of the array, with each recursive call. With the last recursive call, we will have the sum of all elements in s and return it when condition satisfies.
ayushpandey3july
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android
Android Menus
MVP (Model View Presenter) Architecture Pattern in Android with Example
Kotlin Android Tutorial
How to Build a Weather App in Android?
MVC (Model View Controller) Architecture Pattern in Android with Example
How to Get Current Location in Android?
Kotlin when expression
How to Convert Kotlin Code to Java Code in Android Studio?
Difference between List and Set in Java

List and Set both interface belongs to the Collection framework. Both interfaces extend the Collection interface. They both are used to store a collection of objects as a single unit. 
Before jdk1.2, we used to use Arrays, Vectors, and Hashtable for grouping objects as a single unit. 
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class ListExample {
   public static void main(String[] args) {
      List<String> al = new ArrayList<String>();
      al.add("BMW");
      al.add("Audi");
      al.add("BMW");
      System.out.println("List Elements: ");
      System.out.print(al);
   }
}
List Elements:
[BMW, Audi, BMW]
import java.util.Set;
import java.util.HashSet;
import java.util.TreeSet;
public class SetExample {
   public static void main(String args[]) {
      int count[] = {2, 4, 3, 5};
      Set<Integer> hset = new HashSet<Integer>();
      try{
         for(int i = 0; i<4; i++){
            hset.add(count[i]);
         }
         System.out.println(hset);
      }
      catch(Exception e){
         e.printStackTrace();
      }
   }
}
[2, 4, 3, 5]
How to set sql_mode permanently in MySQL?

If you are using Windows Operating System, check your directory my.cnf or my.ini file.
mysql> select @@datadir;
The following is the output
+---------------------------------------------+
| @@datadir                                   |
+---------------------------------------------+
| C:\ProgramData\MySQL\MySQL Server 8.0\Data\ |
+---------------------------------------------+
1 row in set (0.00 sec)
Reach the above location ‘C:\ProgramData\MySQL\MySQL Server 8.0\Data\”. The screenshot is as follows for my.cnf file
Open the my.cnf file and write the sql_mode="TRADITIONAL". The syntax is as follows
sql_mode="TRADITIONAL".
After that start your server once again.
Rexx - reverse String

This method returns the characters in a reverse format.
reverse(str) 

str − The source string
str − The source string
This method returns the characters in a reverse format.
/* Main program */ 
a = "Hello World" 
say reverse(a) 
When we run the above program we will get the following result.
dlroW olleH  

 Print
 Add Notes
 Bookmark this page
Encryption of files

In Python, it is possible to encrypt and decrypt files before transmitting to a communication channel. For this, you will have to use the plugin PyCrypto. You can installation this plugin using the command given below.
pip install pycrypto

The program code for encrypting the file with password protector is mentioned below −
# =================Other Configuration================
# Usages :
usage = "usage: %prog [options] "
# Version
Version="%prog 0.0.1"
# ====================================================
# Import Modules
import optparse, sys,os
from toolkit import processor as ps
def main():
   parser = optparse.OptionParser(usage = usage,version = Version)
   parser.add_option(
      '-i','--input',type = 'string',dest = 'inputfile',
      help = "File Input Path For Encryption", default = None)
   
   parser.add_option(
      '-o','--output',type = "string",dest = 'outputfile',
      help = "File Output Path For Saving Encrypter Cipher",default = ".")
	
   parser.add_option(
      '-p','--password',type = "string",dest = 'password',
      help = "Provide Password For Encrypting File",default = None)
	
   parser.add_option(
      '-p','--password',type = "string",dest = 'password',
      help = "Provide Password For Encrypting File",default = None)
	
   (options, args)= parser.parse_args()
	
   # Input Conditions Checkings
   if not options.inputfile or not os.path.isfile(options.inputfile):
      print " [Error] Please Specify Input File Path"
      exit(0)
   if not options.outputfile or not os.path.isdir(options.outputfile):
      print " [Error] Please Specify Output Path"
      exit(0)
   if not options.password:
      print " [Error] No Password Input"
      exit(0)
   inputfile = options.inputfile

   outputfile = os.path.join(
      options.outputfile,os.path.basename(options.inputfile).split('.')[0]+'.ssb')
   password = options.password
   base = os.path.basename(inputfile).split('.')[1]
   work = "E"

   ps.FileCipher(inputfile,outputfile,password,work)
   return

   if __name__ == '__main__':
   main()
You can use the following command to execute the encryption process along with password −
python pyfilecipher-encrypt.py -i file_path_for_encryption -o output_path -p password

You can observe the following output when you execute the code given above −
The passwords are generated using MD5 hash algorithm and the values are stored in simply safe backup files in Windows system, which includes the values as displayed below −

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Scrapy - Sending an E-mail

Scrapy can send e-mails using its own facility called as Twisted non-blocking IO which keeps away from non-blocking IO of the crawler. You can configure the few settings of sending emails and provide simple API for sending attachments.
There are two ways to instantiate the MailSender as shown in the following table −
The following line sends an e-mail without attachments −
mailer.send(to = ["receiver@example.com"], subject = "subject data", body = "body data", 
   cc = ["list@example.com"])
The MailSender class uses Twisted non-blocking IO for sending e-mails from Scrapy.
class scrapy.mail.MailSender(smtphost = None, mailfrom = None, smtpuser = None, 
   smtppass = None, smtpport = None)
The following table shows the parameters used in MailSender class −
smtphost (str)
The SMTP host is used for sending the emails. If not, then MAIL_HOST setting will be used.
mailfrom (str)
The address of receiver is used to send the emails. If not, then MAIL_FROM setting will be used.
smtpuser
It specifies the SMTP user. If it is not used, then MAIL_USER setting will be used and there will be no SMTP validation if is not mentioned.
smtppass (str)
It specifies the SMTP pass for validation.
smtpport (int)
It specifies the SMTP port for connection.
smtptls (boolean)
It implements using the SMTP STARTTLS.
smtpssl (boolean)
It administers using a safe SSL connection.
Following two methods are there in the MailSender class reference as specified. First method,
classmethod from_settings(settings)
It incorporates by using the Scrapy settings object. It contains the following parameter −
settings (scrapy.settings.Settings object) − It is treated as e-mail receiver.
Another method,
send(to, subject, body, cc = None, attachs = (), mimetype = 'text/plain', charset = None)
The following table contains the parameters of the above method −
to (list)
It refers to the email receiver.
subject (str)
It specifies the subject of the email.
cc (list)
It refers to the list of receivers.
body (str)
It refers to email body data.
attachs (iterable)
It refers to the email's attachment, mimetype of the attachment and name of the attachment.
mimetype (str)
It represents the MIME type of the e-mail.
charset (str)
It specifies the character encoding used for email contents.
The following settings ensure that without writing any code, we can configure an e-mail using the MailSender class in the project.
MAIL_FROM
It refers to sender email for sending emails.
MAIL_HOST
It refers to SMTP host used for sending emails.
MAIL_PORT
It specifies SMTP port to be used for sending emails.
MAIL_USER
It refers to SMTP validation. There will be no validation, if this setting is set to disable.
MAIL_PASS
It provides the password used for SMTP validation.
MAIL_TLS
It provides the method of upgrading an insecure connection to a secure connection using SSL/TLS.
MAIL_SSL
It implements the connection using a SSL encrypted connection.

    27 Lectures 
     3.5 hours 

 Attreya Bhatt
 Print
 Add Notes
 Bookmark this page
PostgreSQL – REPLACE Function

01 Feb, 2021
In PostgreSQL, the REPLACE function is used to search and replace all occurrences of a string with a new one.
Syntax: REPLACE(source, old_text, new_text );
Let’s analyze the above syntax:
The source is a string where you want to replace the existing string.
The old_text is the string that is to be searched and subsequently replaced. The old_text can occur multiple times and each of them gets replaced on the function is executed.
The new_text is the new text string that is suppose to replace the old text ( old_text ).
Example 1:
The following statement replaces the substring  ‘tt’ with  ‘xx’ in a URL:
SELECT
    REPLACE (
        'https://www.geeksforgeeks.org',
        'tt',
        'xx'
    );
Output:
Example 2:
The below statement updates the email column to replace the domain ‘sakilacustomer.org’ with ‘geeksforgeek.org’, in the customer table of the sample database, ie, dvdrental:
UPDATE 
   customer
SET 
   email = REPLACE (
      email,
    'sakilacustomer.org',
    'geeksforgeeks.org'
   );
To verify it use the below statement:
SELECT
    first_name,
    last_name,
    email
FROM
    customer;
Output:
PostgreSQL-function
PostgreSQL-String-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Copy Table
PostgreSQL - DROP INDEX
How to use PostgreSQL Database in Django?
PostgreSQL - Identity Column
VBScript CDate() Function

20 Oct, 2021
The VBScript CDate Function is used to convert a valid date and time expression to type Date. It returns the correct order of dates. It recognizes date formats according to the locale setting of your system.
Note: We can also use the IsDate function to determine if date can be converted to a date or time.
Syntax:
CDate(date)
Parameter: This function accepts a single a parameter as mentioned above and described below.
date: It is a required attribute. It specify any valid date expression.
Example 1: Below examples illustrates the VBScript CDate Function.
VBScript
<%  gfg=CDate("May 6, 2020")  response.write(gfg)%>
Output:
5/6/2020
Example 2: Below code illustrates that how to convert numbers with separators to a date:
VBScript
<%  gfg=CDate(#4/22/10#)  response.write(gfg)%>
Output:
4/22/2010
chhabradhanvi
VBScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
find_element_by_link_text() driver method – Selenium Python

09 Sep, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. 
This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_link_text() is discussed in this article. With this strategy, the first element with the link text value matching the location will be returned. If no element has a matching link text attribute, a NoSuchElementException will be raised.
Syntax – 
driver.find_element_by_link_text("Text of Link")
Example – For instance, consider this page source:  
HTML
<html> <body>    <p>Are you sure you want to do this?</p>    <a href="continue.html">Continue</a>  <a href="cancel.html">Cancel</a></body><html>
Now after you have created a driver, you can grab an element using – 
login_form = driver.find_element_by_link_text('Continue')
Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its link text “Tutorials”. 
Create a file called run.py to demonstrate find_element_by_link_text method –  
Python3
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_link_text("Tutorials") # print complete elementprint(element)
Now run using – 
Python run.py
First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below. 
Browser Output –  
Terminal Output – 
 
 
 
NaveenArora
surinderdawra388
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.