code-rag-bench/online-tutorials huggingface dataset:
Python Tweepy – Getting the number of tweets a user has tweeted - GeeksforGeeks

18 Jun, 2020
In this article we will see how we can get number of statuses/tweets a user has tweeted/updated. The statuses_count attribute provides us with an integer which denotes the number of statuses the user has posted.
Identifying the date when a user was created in the GUI :
In the above mentioned profile, number of statuses the user has posted : 13.2K (13, 200+)
In order to get the number of statuses a user has posted, we have to do the following :
Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the statuses_count attribute present in it.
Identify the user ID or the screen name of the profile.
Get the User object of the profile using the get_user() method with the user ID or the screen name.
From this object, fetch the statuses_count attribute present in it.
Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the userid = 57741058  # fetching the useruser = api.get_user(id)  # fetching the statuses_count attributestatuses_count = user.statuses_count   print("The number of statuses the user has posted are : " + str(statuses_count))
Output :
The number of statuses the user has posted are : 13239

Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG.
# the screen name of the userscreen_name = "PracticeGfG"  # fetching the useruser = api.get_user(screen_name)  # fetching the statuses_count attributestatuses_count = user.statuses_count   print("The number of statuses the user has posted are : " + str(statuses_count))
Output :
The number of statuses the user has posted are : 2265

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Python - Create Nested Dictionary using given List - GeeksforGeeks

29 Aug, 2020
Given a list and dictionary, map each element of list with each item of dictionary, forming nested dictionary as value.
Input : test_dict = {‘Gfg’ : 4, ‘best’ : 9}, test_list = [8, 2]Output : {8: {‘Gfg’: 4}, 2: {‘best’: 9}}Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4} and so on.
Input : test_dict = {‘Gfg’ : 4}, test_list = [8]Output : {8: {‘Gfg’: 4}}Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4}.
Method #1 : Using loop + zip() 
This is one of the ways in which this task can be performed. In this, we combine both the lists using zip() and loop is used to do iteration of zipped keys and dictionary construction.
Python3
# Python3 code to demonstrate working of # Nested Dictionary with List# Using loop + zip()  # initializing dictionary and listtest_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9} test_list = [8, 3, 2]  # printing original dictionary and listprint("The original dictionary is : " + str(test_dict))print("The original list is : " + str(test_list))  # using zip() and loop to perform # combining and assignment respectively.res = {}for key, ele in zip(test_list, test_dict.items()):    res[key] = dict([ele])          # printing result print("The mapped dictionary : " + str(res)) 
The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}
The original list is : [8, 3, 2]
The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}

Method #2 : Using dictionary comprehension + zip()
This is yet another way in which this task can be performed. In this, we perform similar task as above method, but in one liner using dictionary comprehension
Python3
# Python3 code to demonstrate working of # Nested Dictionary with List# Using dictionary comprehension + zip()  # initializing dictionary and listtest_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9} test_list = [8, 3, 2]  # printing original dictionary and listprint("The original dictionary is : " + str(test_dict))print("The original list is : " + str(test_list))  # zip() and dictionary comprehension mapped in one liner to solveres = {idx: {key : test_dict[key]} for idx, key in zip(test_list, test_dict)}          # printing result print("The mapped dictionary : " + str(res)) 
The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}
The original list is : [8, 3, 2]
The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}

Python dictionary-programs
Python list-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?
Console.SetCursorPosition() Method in C# - GeeksforGeeks

14 Mar, 2019
Console.SetCursorPosition(Int32, Int32) Method is used to set the position of cursor. Basically, it specifies where the next write operation will begin in the console window. The window origin changes automatically to make the cursor visible if the specified cursor position is outside the area that is currently visible in the console window.
Syntax: public static void SetCursorposition(int left, int top);
Parameters:left: It is the column position of the cursor. Columns are numbered from left to right starting at 0.top: It is the row position of the cursor. Rows are numbered from top to bottom starting at 0.
Exceptions:
ArgumentOutOfRangeException: If the left or top is less than 0 or left >= BufferWidth or top >= BufferHeight.
SecurityException: If the user doesn’t have the permission to perform this action.
Example:
// C# Program to illustrate // Console.CursorPosition() methodusing System;  class GFG {      // Main Method    public static void Main()    {          // setting the window size        Console.SetWindowSize(40, 40);          // setting buffer size of console        Console.SetBufferSize(80, 80);          // using the method        Console.SetCursorPosition(20, 20);        Console.WriteLine("Hello GFG!");        Console.Write("Press any key to continue . . . ");          Console.ReadKey(true);    } } 
Output:
When Console.SetCursorPosition() method is not used:
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.console.setcursorposition?view=netframework-4.7.2
CSharp-Console-Class
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Class and Object
Extension Method in C#
C# | Delegates
C# | Data Types
HashSet in C# with Examples
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
Partial Classes in C#
Top 50 C# Interview Questions & Answers
How to find the length of an Array in C#
C# | How to insert an element in an Array?
How to install Tkinter in Python?

Tkinter is a standard library in Python which is used for GUI application. Tkinter has various controls which are used to build a GUI-based application.
To install Tkinter, we need Python pre-installed. Tkinter actually comes along when we install Python. While installing Python, we need to check the td/tk and IDLE checkbox. This will install the tkinter and we need not install it separately.
However, if we missed installing Tkinter while installing Python, we can do it later using the pip command.
Type the following commands in command propmt to check is python and pip is installed on your system.
python --version
If python is successfully installed, the version of python installed on your system will be displayed.
pip -V
The version of pip will be displayed, if it is successfully installed on your system.
Tkinter can be installed using pip. The following command is run in the command prompt to install Tkinter.
pip install tk
This command will start downloading and installing packages related to the Tkinter library. Once done, the message of successful installation will be displayed.
Python Pandas - Format Timedelta as ISO 8601

To format Timedelta as ISO 8601, use the timedelta.isoformat() method. At first, import the required libraries −
import pandas as pd
Create a Timedelta object
timedelta = pd.Timedelta('4 days 11 hours 38 min 20 s 35 ms 55 ns')
Display the Timedelta
print("Timedelta...\n", timedelta)
Format as ISO 8601
timedelta.isoformat()

Following is the code
import pandas as pd

# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('4 days 11 hours 38 min 20 s 35 ms 55 ns')

# display the Timedelta
print("Timedelta...\n", timedelta)

# format as ISO 8601
res = timedelta.isoformat()

# display the Timedelta as ISO 8601
print("\nFormat Timedelta as ISO 8601...\n", res)
This will produce the following code
Timedelta...
4 days 11:38:20.035000055

Format Timedelta as ISO 8601...
P4DT11H38M20.035000055S
Redis - Connection Echo Command

Redis ECHO command is used to print the given string.
String reply.
Following is the basic syntax of Redis ECHO command.
redis 127.0.0.1:6379> ECHO SAMPLE_STRING

redis 127.0.0.1:6379> ECHO "Hello World" 
"Hello World" 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Write a MySQL statements for rollback commit and save points

Theory of Computation
Like other databases, MySQL also provides facility for rollback commit and save points. In this article, we will explain these in details with examples.
The MySQL ROLLBACK command is used to restore the database to the last committed state. Like, suppose we deleted some records from MySQL database and later realised that we have deleted necessary record, then we can easily rollback this by using ROLLBACK command. This is effective only when the session has not expired and we have not committed the statement.
ROLLBACK [To SAVEPOINT_NAME];
Here, SAVEPOINT_NAME is the name given to save point that we rollback.
The MySQL COMMIT command is used to save the transaction permanently. As without session expires, we can rollback any changes made by INSERT, UPDATE or DELETE command. As they are not permanent, so with the help of COMMIT command we can make any changes permanently.
COMMIT;
The COMMIT statement is written after the MySQL statement, that we want to be permanent in the database. It returns 'Commit complete.' on successfully committed.
The MySQL SAVEPOINTS command is used to save the transaction temporarily, so that we can ROLLBACK this to that point when required.
SAVEPOINT SAVEPOINT_NAME;
Here, SAVEPOINT_NAME is the name given to save point.
Here, we have created an item_order table -
mysql> CREATE TABLE item_order(item_id INT, name CHAR (20), INDEX (item_id));
Next, do a transaction with AUTOCOMMIT turned on -
mysql> START TRANSACTION;
Query OK, 0 rows affected (0.07 sec)
Next, insert data in 'item_order' -
mysql> INSERT INTO item_order VALUES (101, 'Milk');
Query OK, 1 row affected (0.04 sec)
Next, commit this statement, if you want to insert this permanently -
mysql> COMMIT;
Query OK, 0 rows affected (0.00 sec)
Let's make the autocommit off -
mysql> SET autocommit=0;
And, check the ROLLBACK functionality -
mysql> INSERT INTO item_order VALUES (102, 'Biscuit');
Query OK, 1 row affected (0.00 sec)
mysql>INSERT INTO item_order VALUES (103, 'Cake');
Query OK, 1 row affected (0.00 sec)
Let's delete one row and call the ROLLBACK statement-
mysql> SAVEPOINT C;
Query OK, 0 rows affected (0.00 sec)
mysql> DELETE FROM item_order WHERE name = 'Biscuit';
Query OK, 1 row affected (0.04 sec)
ROLLBACK TO C;
After ROLLBACK statement call, the records in the database are shown as -
mysql> SELECT * FROM item_order;
+---------+------+
| item_id | name |
+---------+------+
|     101 | Milk |
|     103 | Cake |
RESTful Web Services - Statelessness

As per the REST architecture, a RESTful Web Service should not keep a client state on the server. This restriction is called Statelessness. It is the responsibility of the client to pass its context to the server and then the server can store this context to process the client's further request. For example, session maintained by server is identified by session identifier passed by the client.
RESTful Web Services should adhere to this restriction. We have seen this in the RESTful Web Services - Methods chapter, that the web service methods are not storing any information from the client they are invoked from.
Consider the following URL −
https://localhost:8080/UserManagement/rest/UserService/users/1
If you hit the above url using your browser or using a java based client or using Postman, result will always be the User XML whose Id is 1 because the server does not store any information about the client.
<user> 
   <id>1</id> 
   <name>mahesh</name> 
   <profession>1</profession> 
</user>
Following are the benefits of statelessness in RESTful Web Services −
Web services can treat each method request independently.
Web services can treat each method request independently.
Web services need not maintain the client's previous interactions. It simplifies the application design.
Web services need not maintain the client's previous interactions. It simplifies the application design.
As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols.
As HTTP is itself a statelessness protocol, RESTful Web Services work seamlessly with the HTTP protocols.
Following are the disadvantages of statelessness in RESTful Web Services −
Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of.
Web services need to get extra information in each request and then interpret to get the client's state in case the client interactions are to be taken care of.

    71 Lectures 
     10 hours 

 Chaand Sheikh

    27 Lectures 
     2 hours 

 Vinod Kumar Kayartaya

    517 Lectures 
     57 hours 

 Chaand Sheikh

    35 Lectures 
     3.5 hours 

 Antonio Papa
 Print
 Add Notes
 Bookmark this page
qmgr - Unix, Linux Command

qmgr [generic Postfix daemon options]


Mail addressed to the local double-bounce address is
logged and discarded.  This stops potential loops caused by
undeliverable bounce notifications.









RFC 3463 (Enhanced status codes)
RFC 3464 (Delivery status notifications)




Depending on the setting of the notify_classes parameter,
the postmaster is notified of bounces and of other trouble.




The text below provides only a parameter summary. See
postconf(5) for more details including examples.


In the text below, transport is the first field in a
master.cf entry.















/var/spool/postfix/incoming, incoming queue
/var/spool/postfix/active, active queue
/var/spool/postfix/deferred, deferred queue
/var/spool/postfix/bounce, non-delivery status
/var/spool/postfix/defer, non-delivery status
/var/spool/postfix/trace, delivery status

trivial-rewrite(8), address routing
bounce(8), delivery status reports
postconf(5), configuration parameters
master(5), generic daemon options
master(8), process manager
syslogd(8), system logging



SCHEDULER_README, scheduling algorithm
QSHAPE_README, Postfix queue analysis



Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA

Scheduler enhancements:
Patrik Rak
Modra 6
155 00, Prague, Czech Republic


Scheduler enhancements:
Patrik Rak
Modra 6
155 00, Prague, Czech Republic


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
HTML Form action Attribute

The HTML form action attribute defines where to send the form data when a form is submitted in an HTML document.
Following is the syntax −
<form action=”URL”></form>
Let us see an example of HTML Form action Attribute −
 Live Demo
<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
      text-align: center;
   }
   input {
      width: 315px;
      display: block;
      margin: 1rem auto;
      border: 2px solid #fff;
      padding: 8px;
      background: transparent;
      border-radius: 20px;
      outline: none;
   }
   ::placeholder {
      color: #000;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 20px;
      width: 330px;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
</style>
<body>
<h1>HTML Form action Attribute Demo</h1>
<form action="/action_page.php" method="get">
<input type="text" name="firstname" placeholder="Enter First Name">
<input type="text" name="lastname" placeholder="Enter Last Name">
<input type="submit" value="SUBMIT" class="btn">
</form>
</body>
</html>
Enter the form details and then submit the form using “SUBMIT” button to observe how action attribute works.
C++ Program to Implement Sorting containers in STL

In this C++ program, we implement Sorting containers in STL.
Functions used here:
   l.push_back() = It is used to push elements into a list from the front.
   l.sort() = Sorts the elements of the list.
   Where l is a list object.
#include <iostream>
#include <list>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
   list<int> l;
   list<int>::iterator it;
   int c, i;
   while (1) {
      cout<<"1.Insert Element to the list"<<endl;
      cout<<"2.Display the List"<<endl;
      cout<<"3.Exit"<<endl;
      cout<<"Enter your Choice: ";
      cin>>c;
      switch(c) {
         case 1:
            cout<<"Enter value to be inserted";
            cin>>i;
            l.push_back(i);
         break;
         case 2:
            l.sort();
            cout<<"Elements of the List: ";
            for (it = l.begin(); it != l.end(); it++)
               cout<<*it<<" ";
            cout<<endl;
         break;
         case 3:
            exit(1);
         break;
         default:
            cout<<"Wrong Choice"<<endl;
      }
   }
   return 0;
}
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 1
Enter value to be inserted7
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 1
Enter value to be inserted10
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 1
Enter value to be inserted6
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 1
Enter value to be inserted4
1.Insert Element to the list
2.Display the List
3.Exit

Enter your Choice: 2
Elements of the List: 4 6 7 10
1.Insert Element to the list
2.Display the List
3.Exit
Enter your Choice: 3

Exit code: 1
Set unique index in MongoDB

To set unique index in MongoDB, use unique:true. Let us create a collection with documents −
> db.demo257.ensureIndex({Name:1},{unique:true});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo257.insertOne({Name:"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47a5e51627c0c63e7dba91")
}
> db.demo257.insertOne({Name:"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47a5e81627c0c63e7dba92")
}
> db.demo257.insertOne({Name:"Chris"});
2020-02-15T13:33:54.064+0530 E QUERY    [js] WriteError: E11000 duplicate key error collection: test.demo257 index: Name_1 dup key: { : "Chris" } :
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: test.demo257 index: Name_1 dup key: { : \"Chris\" }",
   "op" : {
      "_id" : ObjectId("5e47a5ea1627c0c63e7dba93"),
      "Name" : "Chris"
   }
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
Display all documents from a collection with the help of find() method −
> db.demo257.find();
This will produce the following output −
{ "_id" : ObjectId("5e47a5e51627c0c63e7dba91"), "Name" : "Chris" }
{ "_id" : ObjectId("5e47a5e81627c0c63e7dba92"), "Name" : "Bob" }
Apache Presto - substr(string,start,length)

presto:default> select substr('tutorialspoint',10,2) as substring; 
 substring 
----------- 
    po


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Wildcards in column name for MySQL?

To work with wildcards in column name for MySQL, first, you need to select column_name and then apply LIKE operator to the wildcard.
The syntax is as follows −
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ’yourTableName’
AND COLUMN_NAME LIKE 'yourWildCards%';
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table WildcardDemo
   -> (
   -> ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ProductName varchar(10),
   -> Shippingdatetime datetime,
   -> ProductPrice int
   -> );
Query OK, 0 rows affected (1.31 sec)
Now you can check the description of the table. The query is as follows −
mysql> desc WildcardDemo;
+------------------+-------------+------+-----+---------+----------------+
| Field            | Type        | Null | Key | Default | Extra          |
+------------------+-------------+------+-----+---------+----------------+
| ProductId        | int(11)     | NO   | PRI | NULL    | auto_increment |
| ProductName      | varchar(10) | YES  |     | NULL    |                |
| Shippingdatetime | datetime    | YES  |     | NULL    |                |
| ProductPrice     | int(11)     | YES  |     | NULL    |                |
+------------------+-------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)
We have four fields and out of which three of them begin from the word Product. Now apply the wildcards in column names. The query is as follows −
mysql> select column_name from information_schema.columns
   -> where table_name = 'WildcardDemo'
   -> and column_name LIKE 'product%';
+--------------+
| COLUMN_NAME  |
+--------------+
| ProductId    |
| ProductName  |
| ProductPrice |
+--------------+
3 rows in set (0.10 sec)
How to save a vector in R as CSV file?

To save a vector in R as CSV file, we can follow the below steps −
First of all, create a vector.
Then, use write.csv function to save the vector in CSV file.
Let’s create a vector as shown below −
 Live Demo
x<-rnorm(20)
x
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[1] 0.1771119 0.1380003 -0.3802071 -1.1502674 -0.9965625 -0.3693598
[7] -0.5193763 1.4656757 -0.3345711 -0.4971942 -0.3540402 1.3554071
[13] 0.3902927 1.7747777 -2.3264197 -1.3224475 -1.0591576 0.1597807
[19] 3.3330014 -0.1953936
Using write.csv file to save the file −
x<-rnorm(20)
write.csv(x,file=”x.csv”,row.names=F)
Let’s create a vector as shown below −
 Live Demo
y<-sample(1:50000,20)
y
[1] 41211 37043 14530 17196 41975 28659 9982 42846 12751 37142 20830 32292
[13] 21529 1369 43475 10858 8845 48025 19639 39265
Using write.csv file to save the file −
y<-sample(1:50000,20)
write.csv(y,file="y.csv",row.names=F)
OpenCV - Sobel Operator

Using the sobel operation, you can detect the edges of an image in both horizontal and vertical directions. You can apply sobel operation on an image using the method sobel(). Following is the syntax of this method −
Sobel(src, dst, ddepth, dx, dy)

This method accepts the following parameters −
src − An object of the class Mat representing the source (input) image.
src − An object of the class Mat representing the source (input) image.
dst − An object of the class Mat representing the destination (output) image.
dst − An object of the class Mat representing the destination (output) image.
ddepth − An integer variable representing the depth of the image (-1)
ddepth − An integer variable representing the depth of the image (-1)
dx − An integer variable representing the x-derivative. (0 or 1)
dx − An integer variable representing the x-derivative. (0 or 1)
dy − An integer variable representing the y-derivative. (0 or 1)
dy − An integer variable representing the y-derivative. (0 or 1)
The following program demonstrates how to perform Sobel operation on a given image.
import org.opencv.core.Core;
import org.opencv.core.Mat;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class SobelTest {
   public static void main(String args[]) {
      // Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

      // Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap16/sobel_input.jpg";
      Mat src = Imgcodecs.imread(file);

      // Creating an empty matrix to store the result
      Mat dst = new Mat();

      // Applying sobel on the Image
      Imgproc.Sobel(src, dst, -1, 1, 1);

      // Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap16/sobel_output.jpg", dst);

      System.out.println("Image processed");
   }
}
Assume that following is the input image sobel_input.jpg specified in the above program.
On executing the program, you will get the following output −
Image Processed

If you open the specified path, you can observe the output image as follows −
On passing different values to the last to parameters (dx and dy) (among 0 and 1), you will get different outputs −
// Applying sobel on the Image
Imgproc.Sobel(src, dst, -1, 1, 1);

The following table lists various values for the variables dx and dy of the method Sobel() and their respective outputs.

    70 Lectures 
     9 hours 

 Abhilash Nelson

    41 Lectures 
     4 hours 

 Abhilash Nelson

    20 Lectures 
     2 hours 

 Spotle Learn

    12 Lectures 
     46 mins

 Srikanth Guskra

    19 Lectures 
     2 hours 

 Haithem Gasmi

    67 Lectures 
     6.5 hours 

 Gianluca Mottola
 Print
 Add Notes
 Bookmark this page
Find possible numbers in array that can sum to a target value JavaScript

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument.
The function should pick such elements from the array that when added gives the sum specified by the second argument of the array. The function should return an array of all such subarrays of numbers that when added gives the required sum.
Note that the order is not important and if needed we have the liberty to use one number more than once in order to generate the sum.
For example −
If the input array and the sum are −
const arr = [14, 6, 10];
const sum = 40;
Then the output should be −
const output = [
   [ 14, 14, 6, 6 ],
   [ 14, 6, 10, 10 ],
   [ 6, 6, 6, 6, 6, 10 ],
   [ 10, 10, 10, 10 ]
];
const arr = [14, 6, 10];
const sum = 40;
const findSum = (arr, sum) => {
   const res = [];
   const search = (index, part = []) => {
      const s = part.reduce((a, b) => a + b, 0);
      if (s === sum){
         res.push(part)
      };
      if (s >= sum || index >= arr.length){ return; };
         search(index, part.concat(arr[index]));
         search(index + 1, part);
   };
   search(0);
   return res;
}
console.log(findSum(arr, sum));
This will produce the following output −
[
   [ 14, 14, 6, 6 ],
   [ 14, 6, 10, 10 ],
   [ 6, 6, 6, 6, 6, 10 ],
   [ 10, 10, 10, 10 ]
]
Reduce the fraction to its lowest form in C++

Given two integers Num1 and Num2 as input. The integers can be represented as fraction Num1/Num2. The goal is to reduce this fraction to its lowest form.
We will calculate the greatest common divisor of both numbers.
We will calculate the greatest common divisor of both numbers.
Divide both numbers by that gcd
Divide both numbers by that gcd
Set both variables as quotient after division.
Set both variables as quotient after division.
Lowest fraction will be Num1/Num2.
Lowest fraction will be Num1/Num2.
Input − Num1=22 Num2=10
Output − Num1 = 11 Num2 = 5
Lowest Fraction : 11/5
Explanation− GCD of 22 and 10 is 2.
22/2=11 and 10/2=5
Lowest fraction is 11/5
Input− Num1=36 Num2=40
Output− Num1 = 9 Num2 = 10
Lowest Fraction : 9/10
Explanation − GCD of 36 and 40 is 4.
40/4=10 and 36/4=9
Lowest fraction is 9/10
In this approach we will first calculate the GCD of input numbers using a recursive approach. Divide both numbers by GCD and obtain quotients. These quotients will be part of the lowest fraction.
Take the input variables Num1 and Num2.
Take the input variables Num1 and Num2.
Function findGCD(int a, int b) takes num1 and num2 and returns the gcd of both.
Function findGCD(int a, int b) takes num1 and num2 and returns the gcd of both.
If b is 0 return a else return findGCD(b,a%b).
If b is 0 return a else return findGCD(b,a%b).
Function lowestFraction(int num1, int num2) takes both numbers as input and prints the lowest fraction.
Function lowestFraction(int num1, int num2) takes both numbers as input and prints the lowest fraction.
Take variable denom for gcd.
Take variable denom for gcd.
Set num1=num1/denom and num2=num2/denom.
Set num1=num1/denom and num2=num2/denom.
Print num1 and num2.
Print num1 and num2.
Print the lowest fraction as num1/num2.
Print the lowest fraction as num1/num2.
#include <bits/stdc++.h>
using namespace std;
int findGCD(int a, int b) {
   if (b == 0)
      return a;
      return findGCD(b, a % b);
   }
   void lowestFraction(int num1, int num2){
      int denom;
      denom = findGCD(num1,num2);
      num1/=denom;
      num2/=denom;
      cout<< "Num1 = " << num1<<endl;
      cout<< "Num2 = " << num2<<endl;
      cout<< "Lowest Fraction : "<<num1<<"/"<<num2;
}
int main(){
   int Num1 = 14;
   int Num2 = 8;
   lowestFraction(Num1,Num2);
   return 0;
}
If we run the above code it will generate the following Output
Num1 = 7
Num2 = 4
Lowest Fraction : 7/4
Calculating distance between two geo-locations in Python | by Ashutosh Bhardwaj | Towards Data Science

A few months back I was working on a freelance project of visualizing geo-location data(i.e. latitude and longitude) in which I have to visualize central facilities and customers location on a map. As per one of the client’s requirements, I have to find all the customers locations that are within the range of 3 km from different facilities. To do this I have to calculate the distance between all the locations. It was the first time I was working with raw coordinates, so I tried a naive attempt to calculate distance using Euclidean distance, but sooner realized that this approach was wrong.
Euclidean Distance works for the flat surface like a Cartesian plain however, Earth is not flat. So we have to use a special type of formula known as Haversine Distance.
Haversine Distance can be defined as the angular distance between two locations on the Earth’s surface.
Haversine distance can be calculated as:
Looks Daunting, yes it would be daunting if you have to apply it using raw python code, but thanks to the python’s vibrant developers community that we have a dedicated library to calculate Haversine distance called haversine(one of the perks of using python).
That’s it with the introduction lets get started with its implementation:
Step 1: Installing “haversine”
To install haversine type following command in jupyter notebook.
!pip install haversine
If you are installing through anaconda prompt remove the “!” mark from the above command.
Step 2: Importing library
After installing the library import it
import haversine as hs
Step 3: Calculating distance between two locations
loc1=(28.426846,77.088834)loc2=(28.394231,77.050308)hs.haversine(loc1,loc2)
Output: 5.229712941541709
By default the haversine function returns distance in km. If you want to change the unit of distance to miles or meters you can use unit parameter of haversine function as shown below:
from haversine import Unit#To calculate distance in meters hs.haversine(loc1,loc2,unit=Unit.METERS)
Output: 5229.7129415417085
#To calculate distance in miles hs.haversine(loc1,loc2,unit=Unit.MILES)
Output: 3.2495929643035977
Similarly you can calculate distance in inches also.
Calculating distance between two locations is a basic requirement if you are working with raw location data. It not only helps you to visualize better but it also provides an edge to your Machine learning algorithm. It might give an edge to your model and improves its overall efficiency by adding a new dimension “distance”.
This is the output of the project that i mentioned earlier in this article:
If you want to see the whole code you can visit my github page: https://github.com/ashutoshb418/Foodies-Visualization
What data type to use for hashed password field in MySQL?

The hashed password data type depends upon which hashing algorithm we are using. The hashing algorithm does not depends upon the input size because it produces a result of the same length. It gives the result in a series of hexadecimal digits, and we can reduce the hexadecimal digits by half with the help of UNHEX() function.
There are various algorithms and data types to store values.
MD5 − It can use char(32) or BINARY(16).
MD5 − It can use char(32) or BINARY(16).
SHA-1 − It can use data type char(40) or BINARY(20).
SHA-1 − It can use data type char(40) or BINARY(20).
The following is an example −
mysql> select MD5('This is a hashed password');
Here is the output.
+----------------------------------+
| MD5('This is a hashed password') |
+----------------------------------+
| e9d4c42db40abbb4724a0047f7e91e67 |
+----------------------------------+
1 row in set (0.03 sec)

To know the length of the hashed password.
mysql>  SELECT CHARACTER_LENGTH(MD5('This is a hashed password'));
+----------------------------------------------------+
| CHARACTER_LENGTH(MD5('This is a hashed password')) |
+----------------------------------------------------+
|                                                 32 |
+----------------------------------------------------+
1 row in set (0.04 sec)
mysql> select SHA1('This is a hashed password');
The following is the output.
+------------------------------------------+
| SHA1('This is a hashed password')        |
+------------------------------------------+
| 4e2e1a39dba84a0b5a91043bb0e4dbef23970837 |
+------------------------------------------+
1 row in set (0.00 sec)

We can know the length with the help of character_length() function.
mysql>  SELECT CHARACTER_LENGTH(SHA1('This is a hashed password'));
The following is the output.
+-----------------------------------------------------+
| CHARACTER_LENGTH(SHA1('This is a hashed password')) |
+-----------------------------------------------------+
|                                                  40 |
+-----------------------------------------------------+
1 row in set (0.00 sec)
Java Program to Convert Enum to String - GeeksforGeeks

17 Jun, 2021
Given an enum containing a group of constants, the task is to convert the enum to a String.
Methods:
We can solve this problem using two methods:
Using name() MethodUsing toString() Method
Using name() Method
Using toString() Method
Let us discuss both of them in detail and implementing them to get a better understanding of the same.
Method 1: Using name() Method
 It returns the name of the enum constant same as declared in its enum declaration. 
We would be using name() method to return the name of the enum constant.
In the main class, we just have to print it.
The value given inside is first the name of the enum class that we will create further, then calling the constant that is named, finally using the name() method.
Now create another java enum file named Fruits.java in the same folder where you created the main file, and declare the enum as follows:
Example
public enum Fruits {
    Orange, Apple, Banana, Mango;
}
Java
// Java Program to Convert Enum to String// using   // Importing input output classesimport java.io.*;  // Enumenum Fruits {    Orange,    Apple,    Banana,    Mango;}  // Main classclass GFG {      // Main driver method    public static void main(String[] args) {          // Printing all the values        System.out.println(Fruits.Orange.name());        System.out.println(Fruits.Apple.name());        System.out.println(Fruits.Banana.name());        System.out.println(Fruits.Mango.name());    }}
Orange
Apple
Banana
Mango

 Method 2: Using toString() Method
 It is used to get a string object which represents the value of the number object.
We will be following the same procedure as earlier used but the only difference here is that we will be using toString() method. So just replace name() method with toString() method.
Note: Do not forgot to create a Fruits.java enum file in the same folder.
Illustration: 
public enum Fruits {
    Orange, Apple, Banana, Mango;
}
Example 2
Java
// Java Program to Convert Enum to String// Using toString() Method  // Importing input output classes import java.io.*;  // Enumenum Fruits {    // Custom entries     Orange,    Apple,    Banana,    Mango;}  // Main class class Main {        // Main driver method     public static void main (String[] args) {                // Printing all the values        System.out.println(Fruits.Orange.toString());        System.out.println(Fruits.Apple.toString());        System.out.println(Fruits.Banana.toString());        System.out.println(Fruits.Mango.toString());    }}
Orange
Apple
Banana
Mango

Java-Enumeration
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
java.util.regex.Pattern.matcher() Method

The java.util.regex.Pattern.matcher(CharSequence input) method creates a matcher that will match the given input against this pattern.
Following is the declaration for java.util.regex.Pattern.matcher(CharSequence input) method.
public Matcher matcher(CharSequence input)

input − The character sequence to be matched.
input − The character sequence to be matched.
A new matcher for this pattern.
The following example shows the usage of java.util.regex.Pattern.matcher(CharSequence input) method.
package com.tutorialspoint;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternDemo {
   private static final String REGEX = "(.*)(\\d+)(.*)";
   private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      if(matcher.find()) {
         //get the MatchResult Object 
         MatchResult result = matcher.toMatchResult();

         //Prints the offset after the last character matched.
         System.out.println("First Capturing Group - Match String end(): "+result.end());         
      }
   }
}
Let us compile and run the above program, this will produce the following result −
First Capturing Group - Match String end(): 53

 Print
 Add Notes
 Bookmark this page
Convert string (varchar) to timestamp format in MySQL?

To convert string to timestamp format, use STR_TO_DATE() along with DATE_FORMAT(). Let us first create a table −
mysql> create table DemoTable1602
   -> (
   -> ReportingDate varchar(40)
   -> );
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1602 values('Wed Oct 02 16:10:45 IST 2019');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1602 values('Fri May 31 13:00:10 IST 2019');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1602 values('Mon Dec 31 14:20:00 IST 2018');
Query OK, 1 row affected (0.23 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1602;
This will produce the following output −
+------------------------------+
| ReportingDate                |
+------------------------------+
| Wed Oct 02 16:10:45 IST 2019 |
| Fri May 31 13:00:10 IST 2019 |
| Mon Dec 31 14:20:00 IST 2018 |
+------------------------------+
3 rows in set (0.00 sec)
Following is the query to convert string to timestamp format in MySQL −
mysql> select date_format(str_to_date(ReportingDate,'%a %b %d %T IST %Y'),'%d-%m-%Y %H:%i:%s') from DemoTable1602;
This will produce the following output −
+----------------------------------------------------------------------------------+
| date_format(str_to_date(ReportingDate,'%a %b %d %T IST %Y'),'%d-%m-%Y %H:%i:%s') |
+----------------------------------------------------------------------------------+
| 02-10-2019 16:10:45                                                              |
| 31-05-2019 13:00:10                                                              |
| 31-12-2018 14:20:00                                                              |
+----------------------------------------------------------------------------------+
3 rows in set (0.03 sec)
C# | Check if the Hashtable contains a specific Value - GeeksforGeeks

01 Feb, 2019
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.ContainsValue(Object) Method is used to check whether the Hashtable contains a specific value or not.
Syntax:
public virtual bool ContainsValue(object value);

Parameter:
value: The value of type System.Object to locate in the Hashtable. The value can be null.
Return Type: This method returns true if the Hashtable contains an element with the specified value otherwise it returns false. The return type of this method is System.Boolean.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to check if the HashTable// contains a specific Valueusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Hashtable        Hashtable myTable = new Hashtable();          // Adding elements in Hashtable        myTable.Add("g", "geeks");        myTable.Add("c", "c++");        myTable.Add("d", "data structures");        myTable.Add("q", "quiz");          // check if the HashTable contains        // the required Value or not.        if (myTable.ContainsValue("c++"))            Console.WriteLine("myTable contains the Value");        else            Console.WriteLine("myTable doesn't contain the Value");    }}
myTable contains the Value

Example 2:
// C# code to check if the HashTable// contains a specific Valueusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Hashtable        Hashtable myTable = new Hashtable();          // Adding elements in Hashtable        myTable.Add("India", "Country");        myTable.Add("Chandigarh", "City");        myTable.Add("Mars", "Planet");        myTable.Add("China", "Country");          // check if the HashTable contains        // the required Value or not.        if (myTable.ContainsKey("Ocean"))            Console.WriteLine("myTable contains the Value");        else            Console.WriteLine("myTable doesn't contain the Value");    }}
myTable doesn't contain the Value

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.containsvalue?view=netframework-4.7.2
CSharp-Collections-Hashtable
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Lambda Expressions in C#
Depth of an N-Ary tree in C++ Program

In this tutorial, we are going to learn how to find the depth of the n-ary tree.
An n-ary tree is a tree in which each node of the tree has no more than n child nodes.
We have to find the depth of the n-ary tree. We will be using the vector to store the children of each node in the tree.
Let's see the steps to solve the problem.
Initialize the tree with dummy data.
Initialize the tree with dummy data.
Write a recursive function to find the depth of the n-ary tree.Initialize a variable to store the max depth of the tree.Iterate over the children of each node.The max depth is the max of the current max depth and the depth of the node children.If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree.The final maximum depth of the tree is maxDepth + 1.
Write a recursive function to find the depth of the n-ary tree.
Initialize a variable to store the max depth of the tree.
Initialize a variable to store the max depth of the tree.
Iterate over the children of each node.The max depth is the max of the current max depth and the depth of the node children.If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree.
Iterate over the children of each node.
The max depth is the max of the current max depth and the depth of the node children.
The max depth is the max of the current max depth and the depth of the node children.
If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree.
If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree.
The final maximum depth of the tree is maxDepth + 1.
The final maximum depth of the tree is maxDepth + 1.
Print the max depth of the tree.
Print the max depth of the tree.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   vector<Node *> child;
};
Node *newNode(int data) {
   Node *temp = new Node;
   temp->data = data;
   return temp;
}
int findDepthOfTree(struct Node *node) {
   if (node == NULL) {
      return 0;
   }
   int maxDepth = 0;
   for (vector<Node*>::iterator it = node->child.begin(); it != node->child.end(); it++) {
      maxDepth = max(maxDepth, findDepthOfTree(*it));
   }
   return maxDepth + 1;
}
int main() {
   Node *root = newNode(1);
   root->child.push_back(newNode(2));
   root->child.push_back(newNode(3));
   root->child.push_back(newNode(4));
   root->child[2]->child.push_back(newNode(1));
   root->child[2]->child.push_back(newNode(2));
   root->child[2]->child.push_back(newNode(3));
   root->child[2]->child.push_back(newNode(4));
   cout << findDepthOfTree(root) << endl;
   return 0;
}
If you run the above code, then you will get the following result.
3
If you have any queries in the tutorial, mention them in the comment section.