code-rag-bench/online-tutorials huggingface dataset:
Explain the use of sql LIKE operator using MySQL in Python?

LIKE is a operator in MySQL. The LIKE operator is used with the WHERE statement to search for a specific pattern in the table.
Suppose you want to search for values which start with “a” in the table, the LIKE statement is used in such scenarios.
There are two wildcard characters used with the LIKE clause.
% − This sign represents zero,one or multiple characters.
% − This sign represents zero,one or multiple characters.
_ (underscore) − This represents one single character.
_ (underscore) − This represents one single character.
Example
LIKE ‘a%’ - Searches for all the values starting with a.
LIKE ‘%a’  -Searches for all the values which end with a.
LIKE ‘_a%’ - Searches for all the values where ‘a’ is at the second position. The _ represents a single character, the second character must be ‘a’ and after a there might be some characters present or not.
SELECT * FROM table_name WHERE column_name LIKE pattern
import MySQL connector
import MySQL connector
establish connection with the connector using connect()
establish connection with the connector using connect()
create the cursor object using cursor() method
create the cursor object using cursor() method
create a query using the appropriate mysql statements
create a query using the appropriate mysql statements
execute the SQL query using execute() method
execute the SQL query using execute() method
close the connection
close the connection
Suppose we the following table named “Students” −
Students
+----------+-----------+
|    name  |    marks  |
+----------+-----------+
|    Rohit |    62     |
|    Rahul |    75     |
|    Inder |    99     |
|   Khushi |    49     |
|    Karan |    92     |
+----------+-----------+
We want to find the names of the students which start with ‘K’.
import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

query="SELECT name FROM Students WHERE name LIKE 'K%' "
cursor.execute(query)
names=cursor.fetchall()
for x in names:
   print(x)

db.close()
The above code fetches all the names from the table which start with ‘K’.
Karan
Khushi
Similary, values can be serached based on various patterns using the above wildcards in any order.
What is function() constructor in JavaScript?

The function() constructor is used in JavaScript to create a new function object. The objects created are parsed when the function is created.
You can try to run the following code to learn how to work with function() constructor
Live Demo
<html>
   <body>
      <script>
         var num = new Function('p', 'q', 'r', 'return p * q * r');
         document.write("Value after multiplication: "+num(5, 2, 9));
      </script>
   </body>
</html>
How to call a JavaScript function on submit form?

The onsubmit event occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
<script>
   <!--
      function validation() {
         all validation goes here
         .........
         return either true or false
      }
   //-->
</script>
The HTML code snippet.
<form method="POST" action="new.cgi" onsubmit="return validate()">
   ...
   <input type="submit" value="Submit" />
</form>
Converting date from 'dd/mm/yyyy' to 'yyyymmdd' in MySQL

To convert date from 'dd/mm/yyyy' to 'yyyymmdd', you can use the date_format() method. Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Admissiondate varchar(200)
);
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Admissiondate) values('21/10/2014');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(Admissiondate) values('01/12/2016');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Admissiondate) values('31/01/2017');
Query OK, 1 row affected (0.14 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+---------------+
| Id | Admissiondate |
+----+---------------+
| 1  | 21/10/2014    |
| 2  | 01/12/2016    |
| 3  | 31/01/2017    |
+----+---------------+
3 rows in set (0.00 sec)
Following is the query to convert date from 'dd/mm/yyyy' to 'yyyymmdd' −
mysql> select date_format(str_to_date(Admissiondate,'%d/%m/%Y'),'%Y%m%d') from DemoTable;
This will produce the following output −
+-------------------------------------------------------------+
| date_format(str_to_date(Admissiondate,'%d/%m/%Y'),'%Y%m%d') |
+-------------------------------------------------------------+
| 20141021                                                    |
| 20161201                                                    |
| 20170131                                                    |
+-------------------------------------------------------------+
3 rows in set (0.00 sec)
PHP | exif_read_data() Function - GeeksforGeeks

19 Feb, 2020
The exif_read_data() function is an inbuilt function in PHP which is used to read the EXIF headers from an image file.
Syntax:
array exif_read_data( mixed $stream, string $sections,
                          bool $arrays, bool $thumbnail )
Parameters: This function accepts four parameters as mentioned above and described below:
$stream: It specifies the image file.
$sections (Optional): It specifies the comma separated list of sections.
$arrays (Optional): It specifies whether not to present each section as array.
$thumbnail (Optional): It specifies whether to read thumbnail or not.
Return Value: This function returns an associative array on success or FALSE on failure.
Below examples illustrate the exif_read_data() function in PHP:
Example 1:
<?php  // Open a the file from local folder$fp = fopen('./geeksforgeeks.jpg', 'rb');  // Read the exif headers$headers = exif_read_data($fp);  // Print the headersecho 'EXIF Headers:' . '<br>';  print("<pre>".print_r($headers, true)."</pre>");?>
Output:
EXIF Headers:
Array
(
    [FileName] => geeksforgeeks.jpg
    [FileDateTime] => 1580889002
    [FileSize] => 17763
    [FileType] => 2
    [MimeType] => image/jpeg
    [SectionsFound] => 
    [COMPUTED] => Array
        (
             => width="667" height="184"
            [Height] => 184
            [Width] => 667
            [IsColor] => 1
        )

)
Example 2:
<?php     // Create an Imagick Object $image = new Imagick( 'https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg');      // Add comment to the image  $image->commentImage("GeeksforGeeks");   // Save the file to local image$image->writeImage('geeksforgeeks.jpg');  // Open a the same file$fp = fopen('./geeksforgeeks.jpg', 'rb');  // Read the exif headers$headers = exif_read_data($fp, 'COMMENT', true, true);  // Print the headersecho 'EXIF Headers:' . '<br>';  print("<pre>".print_r($headers['COMMENT'], true)."</pre>");?>
Output:
EXIF Headers:
Array
(
    [0] => GeeksforGeeks
)

Reference: https://www.php.net/manual/en/function.exif-read-data.php
PHP-function
PHP-image-functions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to receive JSON POST with PHP ?
How to pass JavaScript variables to PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Pretty Print JSON in Python - GeeksforGeeks

26 Mar, 2020
JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json.
Note: For more information, refer to Read, Write and Parse JSON using Python
Whenever data is dumped into Dictionary using the inbuilt module “json” present in Python, the result displayed is same as the dictionary format. Here the concept of Pretty Print Json comes into picture where we can display the JSON loaded into a presentable format.
Example 1:
# Write Python3 code here   import json   json_data = '[{"Employee ID":1,"Name":"Abhishek","Designation":"Software Engineer"},' \            '{"Employee ID":2,"Name":"Garima","Designation":"Email Marketing Specialist"}]'   json_object = json.loads(json_data)   # Indent keyword while dumping the# data decides to what level # spaces the user wants.print(json.dumps(json_object, indent = 1))   # Difference in the spaces # near the brackets can be seenprint(json.dumps(json_object, indent = 3))
Output:
[
 {
  "Employee ID": 1,
  "Name": "Abhishek",
  "Designation": "Software Engineer"
 },
 {
  "Employee ID": 2,
  "Name": "Garima",
  "Designation": "Email Marketing Specialist"
 }
]
[
   {
      "Employee ID": 1,
      "Name": "Abhishek",
      "Designation": "Software Engineer"
   },
   {
      "Employee ID": 2,
      "Name": "Garima",
      "Designation": "Email Marketing Specialist"
   }
]

Example 2: Let’s suppose we want to pretty-print the data from the JSON file.
JSON File:
import json      # Opening JSON file f = open('myfile.json',)      # returns JSON object as  # a dictionary data = json.load(f)      print(json.dumps(data, indent = 1)     # Closing file f.close() 
Output:
{
 "emp1": {
  "name": "Lisa",
  "designation": "programmer",
  "age": "34",
  "salary": "54000"
 },
 "emp2": {
  "name": "Elis",
  "designation": "Trainee",
  "age": "24",
  "salary": "40000"
 }
}

Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to Undo a Commit in Git ? - GeeksforGeeks

16 Jan, 2022
Basically, you did the last commit in your local repository and have not pushed back to the public repository or simply you want to change, basically, you do not want to do that commit so you wanted to undo the commit but in generic, there arise two cases where undo a commit is needed and possible sometimes as follows:
Undo a commit From the local repositoryUndo a commit from the public repository
Undo a commit From the local repository
Undo a commit from the public repository
Case 1: Undo a commit from the local repository 
1.1 First check your all commits
#git log
Output: commits are just examples or sample commits
commit 2: second commit  
commit 1:  First commit  
Perception drawn are as follows:
commit 2 is the commit you want to undo, the current head is here
commit1 is the first commit where you want to go after undo
1.2 To restore everything or undo all the changes we have to reset the commit.
#git reset --soft HEAD^      
#git reset --hard HEAD^  
Note: 
soft is used if you want to keep your changes
hard is used if you don’t want to keep your changes
1.3 To check your commit is reset or not
#git log
Output:  
commit 1: First commit   
//undo the second commit, now head is at first or previous commit
 One can clearly see last commit (i.e. second commit) is removed.
Case 2: Undo a commit from the public repository
Now if we have already made your commit public then you will have to create a new commit which will “revert” the changes you made in your previous commit (current HEAD) then do follow the certain commands:
Reverting changes
Checking all commits to see the list of commits
2.1 revert your changes 
#git revert HEAD  
We are now ready for your new commit in order to restore the file that we accidentally have remove with the below command as follows:
#git commit -m 
2.2 Now check your all commits to see the list of commits
#git log
Output:
commit 3: restoring the file that we accidentally remove  
commit 2: removing a file we don't need 
commit 1: Needed file 
Now we can revert your last commit.
Also do note that we use the command below specified to undo the last commits in git where the head is a pointer pointing to the last commit in our branch 
git reset HEAD~<no-of-commits>
saurabh1990aror
TrueGeek-2021
Git
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Git Push Origin and Git Push Origin Master
Git - Difference Between Git Fetch and Git Pull
How to Push Git Branch to Remote?
How to Export Eclipse projects to GitHub?
Merge Conflicts and How to handle them
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Basics of API Testing Using Postman
SQL Statement to Remove Part of a String
Types of Internet Protocols
PHP | trim() Function - GeeksforGeeks

19 Apr, 2018
The trim() function in PHP is an inbuilt function which removes whitespaces and also the predefined characters from both sides of a string that is left and right.
Related Functions:
PHP | ltrim() Function
PHP | rtrim() Function
Syntax:
trim($string, $charlist)

Parameters:The function accepts one mandatory parameter and one optional parameter as shown in the above syntax and described below.
$string: This parameter specifies the string from which the whitespace and predefined characters from left and right are to be removed$charlist: This is an optional parameter which specifies the characters that are to be removed from the string. If this is not mentioned then all of the following characters will be removed:“\0” – NULL“\t” – tab“\n” – new line“\x0B” – vertical tab“\r” – carriage return” ” – ordinary white space
$string: This parameter specifies the string from which the whitespace and predefined characters from left and right are to be removed
$charlist: This is an optional parameter which specifies the characters that are to be removed from the string. If this is not mentioned then all of the following characters will be removed:“\0” – NULL“\t” – tab“\n” – new line“\x0B” – vertical tab“\r” – carriage return” ” – ordinary white space
“\0” – NULL
“\t” – tab
“\n” – new line
“\x0B” – vertical tab
“\r” – carriage return
” ” – ordinary white space
Return Value: It returns the modified string by removing the whitespace and also the predefined characters from both sides of a string that is left and right.
Below programs illustrate the trim() function:
Program 1:
<?php// PHP program to demonstrate the use of trim() // function when second parameter is present  // removes the predefined characters from // front and back $str = "Hello World!";echo trim($str, "Hell!");?>
Output:
o World

Program 2:
<?php// PHP program to demonstrate the use of trim() // function when second parameter is absent  $str = "  geeks for geeks ";  // removes all leading and trailing whitespaces echo trim($str);?>
Output:
geeks for geeks

Reference: http://php.net/manual/en/function.trim.php
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to replace all occurrences of a string using Vue.js filters ? - GeeksforGeeks

27 Oct, 2021
In this article, we are going to learn how to replace all occurrences of a particular word with some other word using filters in VueJS. Vue is a progressive framework for building user interfaces. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template.
The replacement of the occurrence of a particular word in a given string with some other word can be done by applying a filter on the required string. We will use the JavaScript split() method to split the string on the target word or character that has to be replaced. This will return an array that contains all the words that were in string except the word or character that was used to split the string. We will then join the array back using the join() method. This method accepts a parameter that denotes the string that will be used when joining the array back. This will make it possible to add the replacement words needed. We will finally return the resulting string.
Example:
index.html
<html><head>  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">  </script></head><body>  <div id='parent'>    <p>      <strong>Original String: </strong>      {{st1}}    <div>      <strong>After Replacing words: </strong>      {{ st1 | replace('cse','computer science') }}    </div>    </p>      <p>      <strong>Original String: </strong>{{st2}}    <div>      <strong>After Replacing characters: </strong>      {{ st2 | replace('!','.') }}    </div>    </p>    </div>  <script src='app.js'></script></body></html>
app.js
const parent = new Vue({  el: '#parent',  data: {    st1: `GfG is a CSE portal.\          CSE is the study of algorithmic          processes, CSE is a particular\          stream of a Engineering also`,      st2: '172!198!108!202',  },    filters: {    replace: function (st, rep, repWith) {      const result = st.split(rep).join(repWith)      return result;    }  }})
Output:
sagartomar9927
HTML-Tags
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python - Alternate Elements operation on Tuple - GeeksforGeeks

02 Jun, 2020
Sometimes, while working with Python Tuples, we can have problem in which we need to perform operations of extracted alternate chains of tuples. This kind of operation can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed.
Input : test_tuple = (5, 6, 3)Output :The alternate chain sum 1 : 6The alternate chain sum 2 : 8
Input : test_tuple = (5, 6)Output :The alternate chain sum 1 : 6The alternate chain sum 2 : 5
Method #1 : Using loop + enumerate()The combination of above functions provide brute force solution to this problem. In this, we extract the elements along with indices using enumerate() and perform chaining using condition.
# Python3 code to demonstrate working of # Alternate Elements operation on Tuple# Using loop + enumerate()  # initializing tupletest_tuple = (5, 6, 3, 6, 10, 34)  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Alternate Elements operation on Tuple# Using loop + enumerate()sum1 = 0sum2 = 0for idx, ele in enumerate(test_tuple):    if idx % 2:        sum1 += ele    else :        sum2 += ele  # printing result print("The alternate chain sum 1 : " + str(sum1))print("The alternate chain sum 2 : " + str(sum2)) 
The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 46
The alternate chain sum 2 : 18

 
Method #2 : Using list slicingThis problem can also be performed using slicing operations. In this, we perform the task of extracting alternate chains using list slicing technique.
# Python3 code to demonstrate working of # Alternate Elements operation on Tuple# Using list slicing  # initializing tupletest_tuple = (5, 6, 3, 6, 10, 34)  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Alternate Elements operation on Tuple# Using list slicingsum1 = sum(test_tuple[1::2])sum2 = sum(test_tuple[0::2])  # printing result print("The alternate chain sum 1 : " + str(sum1))print("The alternate chain sum 2 : " + str(sum2)) 
The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 46
The alternate chain sum 2 : 18

Python tuple-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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
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?
How to specify the width of an input element in HTML5 ? - GeeksforGeeks

12 Mar, 2021
In this article, we are going to specify the width of input element. This can be done by using the size attribute or by width attribute to set the width of an element.
The size attribute works with the following input types: text, search, tel, url, email, and password and not on type date, image, time for these we can use width attribute.
Create a div in which we are putting our input. We will take 2 inputs names and dates. For inputting name we will use input type – name and size attribute. To put date we will use input type – date and width attribute(size attribute will not work for date type).
Syntax: For size attribute.
<input type="text" id="name" size=5>
Syntax: For CSS width.
<input type="text" id="name" style="width: 200px;">
Example: Here we used two inputs with different input type i.e. name and date. The name uses size attribute and date uses date attribute both these inputs are separated using <br> and basic styling is used in the head attribute.
HTML
<!DOCTYPE html> <html lang="en"> <head>    <style type="text/css">          label {          font: 18px;        }          input {          margin: 7px;          padding: 2px        }    </style></head><body>     <h1>Specify width of input elements</h1>     <div>           <label for="name">Enter Name:</label>        <input type="text" id="name" size=10>        <br>        <label for="name">Enter Date:</label>        <input type="date" id="last name"                style="width: 200px;">            </div> </body>   </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Questions
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to calculate Power of a number using recursion in C#?

To calculate power of a number using recursion, try the following code.
Here, if the power is not equal to 0, then the function call occurs which is eventually recursion −
if (p!=0) {
   return (n * power(n, p - 1));
}
Above, n is the number itself and the power reduces on every iteration as shown below −
 Live Demo
using System;
using System.IO;

public class Demo {
   public static void Main(string[] args) {
      int n = 5;
      int p = 2;
      long res;
      res = power(n, p);
      Console.WriteLine(res);
   }

   static long power (int n, int p) {
      if (p!=0) {
         return (n * power(n, p - 1));
      }
      return 1;
   }
}
25
Return a C# tuple from a method

Firstly, create a tuple as shown below that calls a method.
var tuple = Show();
The above statement calls the following method −
static Tuple<int, int, int, int, int> Show()
Under the method, return the tuple as shown below −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      var tuple = Show();
      Console.WriteLine(tuple.Item1);
      Console.WriteLine(tuple.Item2);
      Console.WriteLine(tuple.Item3);
      Console.WriteLine(tuple.Item4);
      Console.WriteLine(tuple.Item5);
   }
   static Tuple<int, int, int, int, int> Show() {
      return Tuple.Create(3, 5, 7, 9, 11);
   }
}
3
5
7
9
11
Get all declared fields from a class in Java

An array of field objects is returned by the method java.lang.Class.getDeclaredFields(). These field objects include the objects with the public, private, protected and default access but not the inherited fields.
Also, the getDeclaredFields() method returns a zero length array if the class or interface has no declared fields or if a primitive type, array class or void is represented in the Class object.
A program that demonstrates this is given as follows −
 Live Demo
package Test;
import java.lang.reflect.*;
public class Demo {
   int i;
   char c;
   public Demo(int i, char c) {
      this.i = i;
      this.c = c;
   }
   public static void main(String[] args) {
     try {
         Demo obj = new Demo(7, 'A');
         Class c = obj.getClass();
         Field[] fields = c.getDeclaredFields();
         for(int i = 0; i < fields.length; i++) {
           System.out.println("The field is: " + fields[i].toString());
         }
      } catch(Exception e) {
         System.out.println(e.toString());
      }
   }
}
The field is: int Test.Demo.i
The field is: char Test.Demo.c
Now let us understand the above program.
An object of class Demo is created in the main() method. Then the array fields[] stores the field objects that are obtained using the method getDeclaredFields(). Then the fields are displayed using a for loop. A code snippet which demonstrates this is as follows −
Demo obj = new Demo(7, 'A');
Class c = obj.getClass();
Field[] fields = c.getDeclaredFields();
for(int i = 0; i < fields.length; i++) {
   System.out.println("The field is: " + fields[i].toString());
}
jQuery - trigger( event, [data] ) Method

The trigger( event, [data] ) method triggers an event on every matched element.
Triggered events aren't limited to browser-based events, you can also trigger custom events registered with bind.
Here is the simple syntax to use this method −
selector.trigger( event, [data] )

Here is the description of all the parameters used by this method −
event − An event object or type to trigger.
event − An event object or type to trigger.
data − This is an optional parameters and represents additional data to pass as arguments (after the event object) to the event handler.
data − This is an optional parameters and represents additional data to pass as arguments (after the event object) to the event handler.
Following is a simple example a simple showing the usage of this method. Here you would trigger a click event on square TWO by clicking on square ONE −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
			
            $("#div1").click( function () {
               $("#div2").trigger('click');
            });

            $("#div2").click( function () {
               alert( "Square TWO is clicked");
            });
				
         });
      </script>
		
      <style>
         div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
	
   <body>
	
      <span>Click square ONE to see the result:</span>
		
      <div id = "div1" style = "background-color:blue;">ONE</div>
      <div id = "div2" style = "background-color:blue;">TWO</div>
   </body>
</html>
This will produce following result −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
How do I convert a double into a string in C++?

A double can be converted into a string in C++ using std::to_string. The parameter required is a double value and a string object is returned that contains the double value as a sequence of characters.
A program that demonstrates this in C++ is given as follows.
 Live Demo
#include <iostream>
#include <string.h>
using namespace std;
int main() {
   double d = 238649.21316934;
   string s = to_string(d);
   cout << "Conversion of double to string: " << s;
   return 0;
}
The output of the above program is as follows.
Conversion of double to string: 238649.213169
Now let us understand the above program.
A variable d of double type is initialized with a value 238649.21316934. This double value is converted to a string using to_string. Finally this is displayed. The code snippet that shows this is as follows.
double d = 238649.21316934;
string s = to_string(d);
cout << "Conversion of double to string: " << s;
Downsampling an image using OpenCV

In this program, we will down sample an image. Downsampling is decreasing the spatial resolution while keeping the 2D representation of an image. It is typically used for zooming out of an image. We will use the pyrdown() function in the openCV library to complete this task.
Step 1: Fead the image.
Step 2: Pass the image as a parameter to the pyrdown() function.
Step 3: Display the output.
import cv2

image = cv2.imread('testimage.jpg')
print("Size of image before pyrDown: ", image.shape)

image = cv2.pyrDown(image)
print("Size of image after pyrDown: ", image.shape)
cv2.imshow('DownSample', image)
Size of image before pyrDown:  (350, 700, 3)
Size of image after pyrDown:  (175, 350, 3)
If we observe the size of the image before and after using the pyrDown function, we see that the size is decreased, i.e., we have downsampled the image.
How to move files using FileUtils in Java?

The class named File of the java.io package represents a file or directory (pathnames) in the system. This class provides various methods to perform various operations on files/directories.
This class provides various methods to manipulate files, The rename() method of the File class accepts a String representing a destination file and, renames the abstract file path of the current file to the given one.
This method actually moves the file from the source path to the destination path.
 Live Demo
import java.io.File;
public class MovingFile {
   public static void main(String args[]) {
      //Creating a source file object
      File source = new File("D:\\source\\sample.txt");
      //Creating a destination file object
      File dest = new File("E:\\dest\\sample.txt");
      //Renaming the file
      boolean bool = source.renameTo(dest);
      if(bool) {
         System.out.println("File moved successfully ........");
      }
      else {
         System.out.println("Unable to move the file ........");
      }
   }
}
File moved successfully . . . . . . .
Since Java 7 the Files class was introduced this contains (static) methods that operate on files, directories, or other types of files.
The move method of this class accepts two path objects source and destination (and a variable argument to specify the move options) respectively and moves the file represented by the source path to the destination path.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MovingFile {
   public static void main(String args[]) throws Exception {
      //Creating a source Path object
      Path source = Paths.get("D:\\source\\sample.txt");
      //Creating a destination Path object
      Path dest = Paths.get("E:\\dest\\sample.txt");
      //copying the file
      Files.move(source, dest);
      System.out.println("File moved successfully ........");
   }
}
File moved successfully . . . . . . .
How to rotate an image in OpenCV using C++?

Rotating image using built-in functions of OpenCV is an effortless task. To rotate image, we have to use 'highgui.hpp' and 'imgproc.hpp' header files and we will introduce more functions in this program which deal with image rotation.
The following program how to rotate an image in OpenCV using C++.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
   Mat before_rotation = imread("bright.jpg");//loading image to a matrix
   namedWindow("BeforeRotation");//Declaring window to show the original image//
   imshow("BeforeRotation", before_rotation);//showing the image before rotation//
   namedWindow("AfterRotation");//declaring window to show rotated image//
   int Rotation = 180;//initialization rotation angle//
   createTrackbar("Rotation", "AfterRotation", &Rotation, 360);//creating trackbar//
   int Height = before_rotation.rows / 2;//getting middle point of rows//
   int Width = before_rotation.cols / 2;//getting middle point of height//
   while (true) {
      Mat for_Rotation = getRotationMatrix2D(Point(Width, Height), (Rotation - 180), 1);//affine transformation matrix for 2D rotation//
      Mat for_Rotated;//declaring a matrix for rotated image
      warpAffine(before_rotation, for_Rotated, for_Rotation, before_rotation.size());//applying affine transformation//
      imshow("AfterRotation", for_Rotated);//show rotated image//
      int termination = waitKey(30);//allow system 30 millisecond time to create the rottion effect//
      if (termination == 27){ //terminate if Esc button is pressed//
         break;
      }
   }
   return 0;
}
SQL Tryit Editor v1.6

SELECT COUNT(DISTINCT Country) FROM Customers;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Change the default background color for Matplotlib plots

To change the default background color for Matplotlib plots, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Get the current axis.
Add a subplot to the current figure, with nrows=1, ncols=2 and index=1.
Plot random x and y data points using plots() method.
Set the title of the subplot.
Add a subplot to the current figure with nrows=1, ncols=2 and index=2.
Get the current axis.
Set the customize face color.
Plot x and y data points using plot() method.
Set the title of the plot.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

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

ax = plt.gca()

print("Default face color is: ", ax.get_facecolor())

plt.subplot(121)
plt.plot(np.random.rand(10), np.random.rand(10))
plt.title("With default face color")
plt.subplot(122)

ax = plt.gca()
ax.set_facecolor("orange")

plt.plot(np.random.rand(10), np.random.rand(10))
plt.title("With customize face color")

plt.show()
Python program multiplication of two matrix.

Given two user input matrix. Our task is to display the addition of two matrix. In these problem we use nested List comprehensive.
Step1: input two matrix.
Step 2: nested for loops to iterate through each row and each column.
Step 3: take one resultant matrix which is initially contains all 0. Then we multiply each row elements of first matrix with each elements of second matrix, then add all multiplied value. That is the value of resultant matrix.

# Program to multiply two matrices
A=[]
n=int(input("Enter N for N x N matrix: "))         
print("Enter the element ::>")
for i in range(n): 
   row=[]                                      #temporary list to store the row
   for j in range(n): 
      row.append(int(input()))           #add the input to row list
      A.append(row)                      #add the row to the list
print(A)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
   for j in range(n):
      print(A[i][j], end=" ")
   print()                                        #new line
B=[]
n=int(input("Enter N for N x N matrix : "))           #3 here
#use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
print("Enter the element ::>")
for i in range (n): 
   row=[]                                      #temporary list to store the row
   for j in range(n): 
      row.append(int(input()))           #add the input to row list
      B.append(row)                       #add the row to the list
print(B)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
   for j in range(n):
      print(B[i][j], end=" ")
   print()                                           
result = [[0,0,0], [0,0,0], [0,0,0]] 
for i in range(len(A)): 
   for j in range(len(B[0])): 
      for k in range(len(B)): 
         result[i][j] += A[i][k] * B[k][j] 
print("The Resultant Matrix Is ::>")
for r in result: 
   print(r) 
Enter N for N x N matrix: 3
Enter the element ::>
2
1
4
2
1
2
3
4
3
[[2, 1, 4], [2, 1, 2], [3, 4, 3]]
Display Array In Matrix Form
2 1 4 
2 1 2 
3 4 3 
Enter N for N x N matrix : 3
Enter the element ::>
1
2
3
4
5
6
7
8
9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Display Array In Matrix Form
1 2 3 
4 5 6 
7 8 9 
The Resultant Matrix Is ::>
[34, 41, 48]
[20, 25, 30]
[40, 50, 60]
Tryit Editor v3.7

HTML Form elements
Tryit: HTML button element
Performing F-Test in R programming – var.test() Method

07 Jan, 2022
var.test() Method in R Programming language perform the f-test between two normal populations with some hypothesis that variances of two populations are equal in R programming. 
Syntax: var.test()
Return: Returns the F-Test score for some hypothesis.  
Example 1: 
R
x <- rnorm(50, mean=0)y <- rnorm(50, mean=1) # Using var.test() methodgfg <- var.test(x, y) print(gfg)
Output:
F test to compare two variances
data:  x and y
F = 1.0779, num df = 49, denom df = 49, p-value = 0.794
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
 0.6116778 1.8994484
sample estimates:
ratio of variances 
          1.077892 
Example 2:
R
x <- rnorm(50, mean=1.2)y <- rnorm(50, mean=1.8) # Using var.test() methodgfg <- var.test(x, y) print(gfg)
Output:
F test to compare two variances
data:  x and y
F = 2.382, num df = 49, denom df = 49, p-value = 0.002911
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
 1.351715 4.197491
sample estimates:
ratio of variances 
          2.381976 
kumar_satyam
sweetyty
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Display All X-Axis Labels of Barplot in R

09 May, 2021
While working on bar plots, there might be a situation where all the labels in the X-axis might not be visible due to the length of the variable names. This article deals with resolving the problem in the R programming language.
In R language barplot() function is used to create a barplot. It takes the x and y-axis as required parameters and plots a barplot. To display all the labels, we need to rotate the axis, and we do it using the las parameter. To rotate the label perpendicular to the axis we set the value of las as 2, and for horizontal rotation, we set the value as 1. Secondly, to increase the font size of the labels we use cex.names to set the font size of the labels.
Syntax: barplot(data, xlab, ylab)
Parameter:
data is the data vector to be represented on y-axisxlab is the label given to x-axisylab is the label given to y-axis
Example:
R
rm(list = ls())  # Create the datadata <- data.frame(value = c(10,20,30,40,50,60,70,80,90),                      group = paste0("100_", 1:9))  # Original plotbarplot(data$value ~ data$group)  # Modify x-axis labelsbarplot(data$value ~ data$group,             las = 2,        cex.names = 1)
Output:
Another most popular library for drawing plots in R is ggplot2. We draw box plots using geom_bar() functions in ggplot2. To specify the changes are for the x-axis we use axis.text.x parameter in theme() function and use element_text() to specify the angle and font size. 
Example:
R
rm(list = ls())  # import librarylibrary("ggplot2")  # Create the datadata <- data.frame(value = c(90,80,70,60,50,40,30,20,10),                      UID = paste0("10012210_", 1:9))head(data)  # creating a bot plotggplot(data, aes(UID, value)) +   geom_bar(stat = "identity")       # ggplot2 plot with modified x-axis labelsggplot(data, aes(UID, value)) +      geom_bar(stat = "identity") +  theme(axis.text.x = element_text(angle = 90, size = 10))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Circle of Squares using Python

05 Jun, 2020
Turtle library enables users to draw pictures or shapes using commands, providing them with a virtual canvas. turtle comes with Python’s Standard Library. It needs a version of Python with Tk support, as it uses tkinter for the graphics. In this article, we will generate a circular pattern out of squares using Python’s turtle module.
Examples:
Pattern for different number of squares
Approach:
For drawing the circle, we need to draw n number of square, each time rotating the turtle cursor by d degrees. n and d are chosen such that n*d=360, so as to complete a full circle. In the implementation below we will draw a circle of 60 squares, rotating the cursor each time by 6 degrees.
Functions used:
fd(x) : draw the cursor forward by x pixels.
rt(x) : rotates the facing direction of the cursor by x degrees to the right.
Below is the implementation.
from turtle import *    # loop for number of squaresfor i in range(60):          # loop for drawing each square    for j in range(4):                  # drawing each side of        # square of length 100         fd(100)                  # turning 90 degrees        # to the right        rt(90)              # turning 6 degrees for    # the next square    rt(6)
Output:
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | imagecreate() Function

23 Aug, 2019
The imagecreate() function is an inbuilt function in PHP which is used to create a new image. This function returns the blank image of given size. In general imagecreatetruecolor() function is used instead of imagecreate() function because imagecreatetruecolor() function creates high quality images.
Syntax:
imagecreate( $width, $height )
Parameters: This function accepts two parameters as mentioned above and described below:
$width: It is mandatory parameter which is used to specify the image width.
$height: It is mandatory parameter which is used to specify the image height.
Return Value: This function returns an image resource identifier on success, FALSE on errors.
Below programs illustrate the imagecreate() function in PHP:
Program 1:
<?php  // Create the size of image or blank image$image = imagecreate(500, 300);  // Set the background color of image$background_color = imagecolorallocate($image, 0, 153, 0);  // Set the text color of image$text_color = imagecolorallocate($image, 255, 255, 255);  // Function to create image which contains string.imagestring($image, 5, 180, 100,  "GeeksforGeeks", $text_color);imagestring($image, 3, 160, 120,  "A computer science portal", $text_color);  header("Content-Type: image/png");  imagepng($image);imagedestroy($image);  ?>
Output:
Program 2:
<?php  // Create the size of image or blank image$image = imagecreate(500, 300);  // Set the vertices of polygon$values = array(            50,  50,  // Point 1 (x, y)            50, 250,  // Point 2 (x, y)            250, 50,  // Point 3 (x, y)            250,  250 // Point 3 (x, y)        );// Set the background color of image$background_color = imagecolorallocate($image,  0, 153, 0);     // Fill background with above selected colorimagefill($image, 0, 0, $background_color);   // Allocate a color for the polygon$image_color = imagecolorallocate($image, 255, 255, 255);     // Draw the polygonimagepolygon($image, $values, 4, $image_color);     // Output the picture to the browserheader('Content-type: image/png');     imagepng($image);?>
Output:
Related Articles:
PHP | imagepolygon() Function
PHP | imagecolorat() function
Reference: http://php.net/manual/en/function.imagecreate.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to handle Python exception in Threads?

The given code is rewritten to catch the exception
import sys
import threading
import time
import Queue
def thread(args1, stop_event, queue_obj):
print "start thread"
stop_event.wait(12)
if not stop_event.is_set():
try:
raise Exception("boom!")
except Exception:
queue_obj.put(sys.exc_info())
pass
try:
queue_obj = Queue.Queue()
t_stop = threading.Event()
t = threading.Thread(target=thread, args=(1, t_stop, queue_obj))
t.start()
time.sleep(15)
print "stop thread!"
t_stop.set()
try:
exc = queue_obj.get(block=False)
except Queue.Empty:
pass
else:
exc_type, exc_obj, exc_trace = exc
print exc_obj
except Exception as e:
print "It took too long"
OUTPUT
C:/Users/TutorialsPoint1/~.py
start thread
stop thread!
boom!