title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
Tailwind CSS Border Radius | 23 Mar, 2022
This class accepts more than one value in tailwind CSS. All the properties are covered as in class form. It is the alternative to the CSS border-radius property. This class is used to set the border-radius.
Border Radius Classes:
rounded-none
rounded-sm
rounded
rounded-md
rounded-lg
rounded-xl
rounded-2xl
rounded-3xl
rounded-full
rounded-t-none
rounded-r-none
rounded-b-none
rounded-l-none
rounded-t-sm
rounded-r-sm
rounded-b-sm
rounded-l-sm
rounded-t
rounded-r
rounded-b
rounded-l
rounded-t-md
rounded-r-md
rounded-b-md
rounded-l-md
rounded-t-lg
rounded-r-lg
rounded-b-lg
rounded-l-lg
rounded-t-xl
rounded-r-xl
rounded-b-xl
rounded-l-xl
rounded-t-2xl
rounded-r-2xl
rounded-b-2xl
rounded-l-2xl
rounded-t-3xl
rounded-r-3xl
rounded-b-3xl
rounded-l-3xl
rounded-t-full
rounded-r-full
rounded-b-full
rounded-l-full
rounded-tl-none
rounded-tr-none
rounded-br-none
rounded-bl-none
rounded-tl-sm
rounded-tr-sm
rounded-br-sm
rounded-bl-sm
rounded-tl
rounded-tr
rounded-br
rounded-bl
rounded-tl-md
rounded-tr-md
rounded-br-md
rounded-bl-md
rounded-tl-lg
rounded-tr-lg
rounded-br-lg
rounded-bl-lg
rounded-tl-xl
rounded-tr-xl
rounded-br-xl
rounded-bl-xl
rounded-tl-2xl
rounded-tr-2xl
rounded-br-2xl
rounded-bl-2xl
rounded-tl-3xl
rounded-tr-3xl
rounded-br-3xl
rounded-bl-3xl
rounded-tl-full
rounded-tr-full
rounded-br-full
rounded-bl-full
Rounded corners: In this section, classes are covered that have been used to create rounded corners like rounded-sm, rounded-md, rounded-lg, etc, but not the fully circular or the pill shapes.
Syntax:
<element class="rounded-{Border-Radius}">...</element>
Example:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Border Radius Class</b> <div class="mx-4 grid grid-cols-3 gap-2 bg-green-200 p-2"> <!-- First sub div is not for roundig--> <div class="rounded-none bg-green-400 w-48 h-12"> rounded-none</div> <div class="rounded bg-green-400 w-48 h-12"> rounded</div> <div class="rounded-sm bg-green-400 w-48 h-12"> rounded-sm</div> <div class="rounded-md bg-green-400 w-48 h-12"> rounded-md</div> <div class="rounded-lg bg-green-400 w-48 h-12"> rounded-lg</div> <div class="rounded-xl bg-green-400 w-48 h-12"> rounded-xl</div> </div></body> </html>
Output:
Pills and circles: In this section, classes are covered that have been used to create full-circle and pills like rounded-full class.
Syntax:
<element class="rounded-full">...</element>
Example:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Border Radius Class</b> <div class="mx-24 grid grid-cols-3 gap-2 bg-green-200 p-2"> <div class="rounded-full bg-green-400 py-3 px-6"> rounded-full for Design Pill </div> <div class="rounded-full mx-32 bg-green-400 h-24 w-24 flex items-center justify-center"> rounded-full for Circle </div> </div></body> </html>
Output:
Rounding sides separately: In this section, all the classes are covered which has been used to create one side rounded like rounded-t-lg, rounded-r-lg, rounded-b-lg, etc.
Syntax:
<element class="rounded-{t|r|b|l}{-size?}">...</element>
Example:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Border Radius Class</b> <div class="mx-4 grid grid-cols-2 gap-2 bg-green-200 p-2"> <!-- First sub div is not for roundig--> <div class="rounded-t-lg bg-green-400 w-full h-12"> rounded-t-lg</div> <div class="rounded-r-lg bg-green-400 w-full h-12"> rounded-r-lg</div> <div class="rounded-l-lg bg-green-400 w-full h-12"> rounded-l-lg</div> <div class="rounded-b-lg bg-green-400 w-full h-12"> rounded-b-lg</div> </div></body> </html>
Output:
Rounding corners separately: In this section, all the classes are covered which has been used to create one corner rounded like rounded-tl-lg, rounded-tr-lg, rounded-br-lg, etc.
Syntax:
<element class="rounded-{tl|tr|br|bl}{-size?}">...</element>
Example:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Border Radius Class</b> <div class="mx-4 grid grid-cols-2 gap-2 bg-green-200 p-2"> <!-- First sub div is not for roundig--> <div class="rounded-tl-lg bg-green-400 w-full h-12"> rounded-tl-lg</div> <div class="rounded-tr-lg bg-green-400 w-full h-12"> rounded-tr-lg</div> <div class="rounded-bl-lg bg-green-400 w-full h-12"> rounded-bl-lg</div> <div class="rounded-br-lg bg-green-400 w-full h-12"> rounded-br-lg</div> </div></body> </html>
Output:
Tailwind CSS
Tailwind-Borders
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 236,
"s": 28,
"text": "This class accepts more than one value in tailwind CSS. All the properties are covered as in class form. It is the alternative to the CSS border-radius property. This class is... |
GATE | GATE-CS-2017 (Set 1) | Question 47 | 22 Sep, 2017
The values of parameters for the Stop-and – Wait ARQ protocol are as given below.
Bit rate of the transmission channel = 1Mbps
Propagation delay from sender to receiver = 0.75 ms
Time to process a frame = 0.25ms
Number of bytes in the information frame = 1980
Number of bytes in the acknowledge frame = 20
Number of overhead bytes in the information frame = 20
Assume that there are no transmission errors. Then the transmission efficiency ( expressed in percentage) of the Stop-and – Wait ARQ protocol for the above parameters is _________( correct to 2 decimal place) .
Note: This questions appeared as Numerical Answer Type.
(A) A number between 86.5 and 87.5(B) A number between 82.4 and 82.5(C) A number between 92.4 and 95.5(D) A number between 96.4 and 97.5Answer: (A)Explanation: Given,
Number of bytes in the information frame = 1980Number of bytes in the acknowledge frame = 20Number of overhead bytes in the information frame = 20
Therefore, useful Data = Total Data – Overhead = 1980 – 20 = 1960
Tt(Data) = (1960*8) / 10^6 = 15.68 millisecond
Tt(ACK) = 20*8 / 10^6 = 0.16 millisecond
Two way round trip time = 2 * Tp = 2*0.75 = 1.5 millisecond
T(precess) = 0.25(for info) + 0.25(for ack) = 0.5 millisecond
Efficiency = Useful Time / (Tt(info) + + Tt(ACK) + 2* Tp + Tprocess )= 15.68 / (15.84 + 0.16 + 2*0.75+ 0.5 )= 0.8711111= 87%
Option (A) is correct.Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE CS 2010 | Question 54
GATE | GATE-CS-2015 (Set 1) | Question 19
GATE | GATE CS 2018 | Question 43
GATE | Gate IT 2008 | Question 59
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2006 | Question 45
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2013 | Question 25
GATE | GATE-CS-2003 | Question 77 | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Sep, 2017"
},
{
"code": null,
"e": 135,
"s": 53,
"text": "The values of parameters for the Stop-and – Wait ARQ protocol are as given below."
},
{
"code": null,
"e": 423,
"s": 135,
"text": "Bit rate of the transmi... |
Python – Convert List to delimiter separated String | 29 Aug, 2020
Given List of elements, convert it to delimiter separated String.
Input : test_list = [7, “Gfg”, “best”, 9], delim = “*”Output : 7*Gfg*best*9*Explanation : All elements are concatenated with “*” as joiner.
Input : test_list = [7, “Gfg”, “best”, 9], delim = “#”Output : 7#Gfg#best#9#Explanation : All elements are concatenated with “#” as joiner.
Method #1 : Using loop + str()
This is one of the ways in which this task can be performed. In this, we run a loop to add delimiter at end of each element, after converting each element to string.
Python3
# Python3 code to demonstrate working of # Convert List to delimiter separated String# Using loop + str() # initializing listtest_list = [7, "Gfg", 8, "is", "best", 9] # printing original listprint("The original list is : " + str(test_list)) # initializing delim delim = "*" res = '' # using loop to add string followed by delim for ele in test_list: res = res + str(ele) + delim # printing result print("The resultant string : " + str(res))
The original list is : [7, 'Gfg', 8, 'is', 'best', 9]
The resultant string : 7*Gfg*8*is*best*9*
Method #2 : Using join() + str()
This is yet another way in which this task can be performed. In this we perform the task of joining each element by delim using join() and conversion to string is done using str().
Python3
# Python3 code to demonstrate working of # Convert List to delimiter separated String# Using join() + str() # initializing listtest_list = [7, "Gfg", 8, "is", "best", 9] # printing original listprint("The original list is : " + str(test_list)) # initializing delim delim = "*" # using map to convert each element to string temp = list(map(str, test_list)) # join() used to join with delimiterres = delim.join(temp) # printing result print("The resultant string : " + str(res))
The original list is : [7, 'Gfg', 8, 'is', 'best', 9]
The resultant string : 7*Gfg*8*is*best*9
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
Defaultdict in Python
Python | Get dictionary keys as a list
Iterate over characters of a string in Python
Python | Convert set into a list
Python | Find most frequent element in a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 94,
"s": 28,
"text": "Given List of elements, convert it to delimiter separated String."
},
{
"code": null,
"e": 234,
"s": 94,
"text": "Input : test_list = [7, “Gfg”, “best”, 9],... |
How to make HTML files open in Chrome using Python? | 24 Jan, 2021
Prerequisites: Webbrowser
HTML files contain Hypertext Markup Language (HTML), which is used to design and format the structure of a webpage. It is stored in a text format and contains tags that define the layout and content of the webpage. HTML files are widely used online and displayed in web browsers.
To preview HTML files, we make the use of browsers, like Google Chrome, Mozilla Firefox, Apple Safari etc. The task of creating and previewing HTML files can be automated with the help of python scripts.
Here are a few ways how we can open HTML files on chrome:
The webbrowser module in python provides a high-level interface to allow displaying Web-based documents to users, and the os module provides a portable way of using operating system dependent functionalities (like reading or writing files, manipulating file paths etc.). So let’s see how a combination of these both can help us to open an HTML page in Chrome browser:
Function used: open_new_tab() function is used to open html file in a new tab of your default browser.
Syntax:
open_new_tab(filename)
Approach:
Import module
Open and Create file
Add html code
Write code to file
Close file
Open file in browser window
Example:
Python3
# creating nd viewing the html files in python import webbrowserimport os # to open/create a new html file in the write modef = open('GFG.html', 'w') # the html code which will go in the file GFG.htmlhtml_template = """<html><head></head><body><p>Geeks For Geeks</p> </body></html>"""# writing the code into the filef.write(html_template) # close the filef.close() # 1st method how to open html files in chrome usingfilename = 'file:///'+os.getcwd()+'/' + 'GFG.html'webbrowser.open_new_tab(filename)
Output:
If the HTML file is in the same directory as that of the python script, then there is no need of defining the file path with the os module. We can simply run the html file in new browser using the given steps:
File in Use: GFG.html
Approach
Create a html file that you want to open
In Python, Import module
Call html file using open_new_tab()
Example:
Python3
Import webbrowser webbrowser.open_new_tab('GFG.html')
Output:
Picked
python-os-module
python-utility
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 54,
"s": 28,
"text": "Prerequisites: Webbrowser"
},
{
"code": null,
"e": 334,
"s": 54,
"text": "HTML files contain Hypertext Markup Language (HTML), which is used to design and f... |
Python PostgreSQL - Delete Data | You can delete the records in an existing table using the DELETE FROM statement of PostgreSQL database. To remove specific records, you need to use WHERE clause along with it.
Following is the syntax of the DELETE query in PostgreSQL −
DELETE FROM table_name [WHERE Clause]
Assume we have created a table with name CRICKETERS using the following query −
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255),
Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
And if we have inserted 5 records in to it using INSERT statements as −
postgres=# insert into CRICKETERS values ('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values ('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
Following statement deletes the record of the cricketer whose last name is 'Sangakkara'. −
postgres=# DELETE FROM CRICKETERS WHERE LAST_NAME = 'Sangakkara';
DELETE 1
If you retrieve the contents of the table using the SELECT statement, you can see only 4 records since we have deleted one.
postgres=# SELECT * FROM CRICKETERS;
first_name | last_name | age | place_of_birth | country
------------+-----------+-----+----------------+-------------
Jonathan | Trott | 39 | CapeTown | SouthAfrica
Virat | Kohli | 31 | Delhi | India
Rohit | Sharma | 33 | Nagpur | India
Shikhar | Dhawan | 46 | Delhi | India
(4 rows)
If you execute the DELETE FROM statement without the WHERE clause all the records from the specified table will be deleted.
postgres=# DELETE FROM CRICKETERS;
DELETE 4
Since you have deleted all the records, if you try to retrieve the contents of the CRICKETERS table, using SELECT statement you will get an empty result set as shown below −
postgres=# SELECT * FROM CRICKETERS;
first_name | last_name | age | place_of_birth | country
------------+-----------+-----+----------------+---------
(0 rows)
The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it.
Therefore, to insert data into a table in PostgreSQL using python −
Import psycopg2 package.
Import psycopg2 package.
Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it.
Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it.
Turn off the auto-commit mode by setting false as value to the attribute autocommit.
Turn off the auto-commit mode by setting false as value to the attribute autocommit.
The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method.
The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method.
Then, execute the UPDATE statement by passing it as a parameter to the execute() method.
Then, execute the UPDATE statement by passing it as a parameter to the execute() method.
Following Python code deletes records of the EMPLOYEE table with age values greater than 25 −
import psycopg2
#establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving contents of the table
print("Contents of the table: ")
cursor.execute('''SELECT * from EMPLOYEE''')
print(cursor.fetchall())
#Deleting records
cursor.execute('''DELETE FROM EMPLOYEE WHERE AGE > 25''')
#Retrieving data after delete
print("Contents of the table after delete operation ")
cursor.execute("SELECT * from EMPLOYEE")
print(cursor.fetchall())
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
Contents of the table:
[('Ramya', 'Rama priya', 27, 'F', 9000.0),
('Sarmista', 'Sharma', 26, 'F', 10000.0),
('Tripthi', 'Mishra', 24, 'F', 6000.0),
('Vinay', 'Battacharya', 21, 'M', 6000.0),
('Sharukh', 'Sheik', 26, 'M', 8300.0)]
Contents of the table after delete operation:
[('Tripthi', 'Mishra', 24, 'F', 6000.0),
('Vinay', 'Battacharya', 21, 'M', 6000.0)]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3381,
"s": 3205,
"text": "You can delete the records in an existing table using the DELETE FROM statement of PostgreSQL database. To remove specific records, you need to use WHERE clause along with it."
},
{
"code": null,
"e": 3441,
"s": 3381,
"text": "Follow... |
Supermarket Data Analysis with SQL | by Soner Yıldırım | Towards Data Science | SQL is a programming language used to manage data in relational databases which store data in tabular form with labelled rows and columns. SQL is a fundamental tool to put in your skill set if you plan to work in the field of data science.
We can query a database to retrieve data without any modification or filtering. However, this is not a proactive or efficient way. We are most likely to apply some data manipulation or filtering on the raw data to make it more useful.
SQL is highly capable of doing data manipulation and filtering operations. The advantage of using SQL for such tasks is that we just need to retrieve the data we need instead of getting all at once. Furthermore, it allows for doing data analysis while retrieving the data.
In this article, we will be analyzing a supermarket sales dataset available on Kaggle. I have done some modifications on the dataset and simplified it by excluding some of the columns. I have created a table in a MySQL database with the modified version of the dataset.
The dataset contains the details of sales at different branches of a supermarket chain during a period of 3 months.
Note: I wrote another practical article on this dataset using Pandas, a highly popular data analysis and manipulation library for Python.
We may want to sort the product categories based on the total sales amounts.
mysql> select prod_line, sum(total) -> from supermarket -> group by prod_line -> order by sum(total) desc;+----------------------+------------+| prod_line | sum(total) |+----------------------+------------+| Food and beverages | 56144.86 || Sports and travel | 55122.88 || Electronic accessori | 54337.52 || Fashion accessories | 54305.88 || Home and lifestyle | 53861.87 || Health and beauty | 49193.81 |+----------------------+------------+
We first select the columns and apply the aggregation. The next step is to group the aggregated column by the product categories. Finally, we sort the results in descending order based on the total sales amounts.
Customer type and gender columns can be used to get an overview about the customer portfolio. We can count the number of purchases that belong to each cross category.
mysql> select cust_type, gender, count(*) -> from supermarket -> group by cust_type, gender;+-----------+--------+----------+| cust_type | gender | count(*) |+-----------+--------+----------+| Member | Female | 261 || Member | Male | 240 || Normal | Female | 240 || Normal | Male | 259 |+-----------+--------+----------+
The distribution is quite balanced with regards to the customer type and gender columns.
The where clause can be implemented in a select statement to apply conditions on the selected rows. For instance, we can calculate the average quantities of purchases with a total amount higher than 500.
mysql> select avg(qty) -> from supermarket -> where total > 500;+----------+| avg(qty) |+----------+| 8.3744 |+----------+mysql> select avg(qty) -> from supermarket;+----------+| avg(qty) |+----------+| 5.5100 |+----------+
The condition is applied in the first query above. The second query returns the average quantity for the entire table.
We can apply a condition based on dates. For instance, the following query returns all of the sales made between 2019–01–05 and 2019–01–07.
mysql> select * -> from supermarket -> where date between "2019-01-05" and "2019-01-07";
Consider we need to find the top 5 dates with the highest total sales amount. We first need to group the sales based on date because there are many purchases in each day. After that, the results are sorted in descending order based on total sales amount and the first 5 are selected.
mysql> select date, sum(total) -> from supermarket -> group by date -> order by sum(total) desc -> limit 5;+------------+------------+| date | sum(total) |+------------+------------+| 2019-03-09 | 7474.04 || 2019-02-07 | 7228.22 || 2019-03-14 | 7214.62 || 2019-02-15 | 6830.78 || 2019-03-02 | 6560.30 |+------------+------------+
Let’s assume we need to find the date of the sales with the maximum total amount. There are multiple ways of doing this task. One is to use nested select statements as below:
mysql> select date -> from supermarket -> where total = (select max(total) from supermarket);+------------+| date |+------------+| 2019-02-15 |+------------+
We specify the condition in the where clause using another select statement. The nested select statement returns the maximum value of the total column.
We can implement multiple nested select statements. Consider we want to find out how many sales occurred on the date in which the sales with maximum total amount occurred.
This task can be divided into three parts:
Find the maximum total sales amountFind the date of the maximum total sales amountCount the number of sales on this date
Find the maximum total sales amount
Find the date of the maximum total sales amount
Count the number of sales on this date
The following nested query will give us the desired outcome.
mysql> select count(*) from supermarket # 3 -> where date = ( # 2 -> select date from supermarket -> where total = ( # 1 -> select max(total) from supermarket ));+----------+| count(*) |+----------+| 19 |+----------+
The dataset contains 3 branches of a supermarket chain. The customers are divided into two categories. We can find the average total sales amount for each cross category of these two columns.
mysql> select branch, cust_type, avg(total) -> from supermarket -> group by branch, cust_type -> order by avg(total) desc;+--------+-----------+------------+| branch | cust_type | avg(total) |+--------+-----------+------------+| C | Normal | 337.656604 || C | Member | 336.575799 || B | Member | 325.483273 || A | Member | 321.182455 || B | Normal | 314.329341 || A | Normal | 303.831792 |+--------+-----------+------------+
The order by clause in the last line sorts the results in descending order based on the averages.
The products are classified into several product lines. We may want to sort the product lines based on the total number of items sold in each category.
mysql> select prod_line, sum(qty) -> from supermarket -> group by prod_line -> order by sum(qty) desc;+----------------------+----------+| prod_line | sum(qty) |+----------------------+----------+| Electronic accessori | 971 || Food and beverages | 952 || Sports and travel | 920 || Home and lifestyle | 911 || Fashion accessories | 902 || Health and beauty | 854 |+----------------------+----------+
It is similar to the previous examples. We select the product line and the sum of quantity columns. The results are grouped by the product line and sorted by the sum of quantities.
We can also implement a combination of aggregate functions in the select statement. For instance, the following query will return the difference between the unit prices of the most expensive and the cheapest items in the health and beauty product line.
mysql> select max(unit_price) - min(unit_price) as diff -> from supermarket -> where prod_line = "Health and beauty";+-------+| diff |+-------+| 89.88 |+-------+
We select the maximum and minimum values of the unit price column and calculate the difference. The “as” keyword is used to assign an alias to the aggregated columns.
If we want to calculate the same difference for each product line, we can omit the where clause and use the group by clause.
mysql> select prod_line, max(unit_price) - min(unit_price) as diff -> from supermarket -> group by prod_line;+----------------------+-------+| prod_line | diff |+----------------------+-------+| Electronic accessori | 89.17 || Fashion accessories | 89.71 || Food and beverages | 89.66 || Health and beauty | 89.88 || Home and lifestyle | 89.39 || Sports and travel | 89.79 |+----------------------+-------+
We have done several examples that demonstrate how SQL can be used as a data analysis tool. It allows for writing queries that can filter, manipulate, and transform the data stored in relational databases.
The main advantage of such queries is that we only retrieve the data we need which can save us a substantial amount of memory. Applying transformations and aggregations on-the-go expedites the data analysis process.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 412,
"s": 172,
"text": "SQL is a programming language used to manage data in relational databases which store data in tabular form with labelled rows and columns. SQL is a fundamental tool to put in your skill set if you plan to work in the field of data science."
},
{
"... |
Angular CLI - ng lint Command | This chapter explains the syntax, argument and options of ng lint command along with an
example.
The syntax for ng lint command is as follows −
ng lint <project> [options]
ng l <project> [options]
ng lint run the linting tool on angular app code. It checks the code quality of angular project specified. It uses TSLint as default linting tool and uses the default configuration available in tslint.json file.
The argument for ng lint command is as follows −
Options are optional parameters.
The linting configuration to use.
Aliases: -c
Default: false
Succeeds even if there was linting errors.
Default: false
Output format (prose, json, stylish, verbose, pmd, msbuild, checkstyle, vso, fileslist).
Default: prose
Shows a help message for this command in the console.
Default: false
Show output text.
Default: false
Controls the type check for linting.
Default: false
First move to an angular project updated using ng build command.which is available at
https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm.
Update goals.component.html and goals.component.ts as following −
goals.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-goals',
templateUrl: './goals.component.html',
styleUrls: ['./goals.component.css']
})
export class GoalsComponent implements OnInit {
title = 'Goal Component'
constructor() { }
ngOnInit(): void {
}
}
goals.component.html
<p>{{title}}</p>
Now run the linting command.
An example for ng lint command is given below −
\>Node\>TutorialsPoint> ng lint
Linting "TutorialsPoint"...
ERROR: D:/Node/TutorialsPoint/src/app/goals/goals.component.ts:9:27 - Missing semicolon
ERROR: D:/Node/TutorialsPoint/src/app/goals/goals.component.ts:13:2 - file should end with a newline
Lint errors found in the listed files.
Here ng lint command has checked the code quality of application and prints linting status.
Now correct the errors in goals.component.ts.
goals.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-goals',
templateUrl: './goals.component.html',
styleUrls: ['./goals.component.css']
})
export class GoalsComponent implements OnInit {
title = 'Goal Component';
constructor() { }
ngOnInit(): void {
}
}
Now run the linting command.
An example is stated below −
\>Node\>TutorialsPoint> ng lint
Linting "TutorialsPoint"...
All files pass linting.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2172,
"s": 2075,
"text": "This chapter explains the syntax, argument and options of ng lint command along with an\nexample."
},
{
"code": null,
"e": 2219,
"s": 2172,
"text": "The syntax for ng lint command is as follows −"
},
{
"code": null,
"e": ... |
Quick Tutorial: Using Bayesian optimization to tune your hyperparameters in PyTorch | by Michael Deyzel | Towards Data Science | Hyperparameters are the parameters in models that determine model architecture, learning speed and scope, and regularization.
The search for optimal hyperparameters requires some expertise and patience, and you’ll often find people using exhausting methods like grid search and random search to find the hyperparameters that work best for their problem.
I’m going to show you how to implement Bayesian optimization to automatically find the optimal hyperparameter set for your neural network in PyTorch using Ax.
We’ll be building a simple CIFAR-10 classifier using transfer learning. Most of this code is from the official PyTorch beginner tutorial for a CIFAR-10 classifier.
I won’t be going into the details of Bayesian optimization, but you can study the algorithm on the Ax website, read the original paper or the 2012 paper on its practical use.
Install Ax using:
pip install ax-platform
Import all the necessary libraries:
Download the datasets and construct the data loaders (I would advise adjusting the training batch size to 32 or 64 later):
Let’s take a look at the CIFAR-10 dataset by creating some helper functions:
Ax requires a function that returns a trained model, and another that evaluates a model and returns a performance metric like accuracy or F1 score. We’re only building the training function here and using Ax’s ownevaluate tutorial function to test our model performance, which returns accuracy. You can check out ther API to model your own evaluation function after theirs, if you’d like.
Next, we’re writing an init_net() function that initializes the model and returns the network ready-to-train. There are many opportunities for hyperparameter tuning here. You’ll notice the parameterization argument, which is a dictionary containing the hyperparameters.
Lastly, we need a train_evaluate() function that the Bayesian optimizer calls on every run. The optimizer generates a new set of hyperparameters in parameterization, passes it to this function, and then analyzes the returned evaluation results.
Now, just specify the hyperparameters you want to sweep across and pass that to Ax’s optimize() function:
That sure took a while, but it’s nothing compared to doing a naive grid search for all 3 hyperparameters. Let’s take a look at the results:
results[INFO 09-23 09:30:44] ax.modelbridge.dispatch_utils: Using Bayesian Optimization generation strategy: GenerationStrategy(name='Sobol+GPEI', steps=[Sobol for 5 arms, GPEI for subsequent arms], generated 0 arm(s) so far). Iterations after 5 will take longer to generate due to model-fitting.[INFO 09-23 09:30:44] ax.service.managed_loop: Started full optimization with 20 steps.[INFO 09-23 09:30:44] ax.service.managed_loop: Running optimization trial 1...[INFO 09-23 09:31:55] ax.service.managed_loop: Running optimization trial 2...[INFO 09-23 09:32:56] ax.service.managed_loop: Running optimization trial 3......[INFO 09-23 09:52:19] ax.service.managed_loop: Running optimization trial 18...[INFO 09-23 09:53:20] ax.service.managed_loop: Running optimization trial 19...[INFO 09-23 09:54:23] ax.service.managed_loop: Running optimization trial 20...{'lr': 0.000237872310800664, 'batchsize': 117, 'momentum': 0.99}{'accuracy': 0.4912998109307719}{'accuracy': {'accuracy': 2.2924975426156455e-09}}
It seems our optimal learning rate is 2.37e-4 when comined with a momentum of 0.99 and a batch size of 117. That’s pretty nice. The 49.1% accuracy you see here is not the final accuracy of the model, so don’t worry!
We can go even further and render some plots that show the accuracy per epoch (which improved as the parameterization improved), and the estimated accuracy by the optimizer as a function of two hyperparameters using a contour plot. The experiment variable is of type Experiment and you should definitely check out the docs to see all the methods it has to offer.
The rendered plots are easy to understand and interactive. The black squares in the contour plots show the coordinates that have actually been sampled.
Lastly, you can fetch the parameter set (something Ax calls an “arm”) that has the best mean accuracy by simply running the script below:
Arm(name=’19_0', parameters={‘lr’: 0.00023787231080066353, ‘batchsize’: 117, ‘momentum’: 0.9914986635285268})
Don’t be afraid to tune anything you wish, like hidden layer number and size, dropout, activation functions, depth of unfreezing, etc. | [
{
"code": null,
"e": 298,
"s": 172,
"text": "Hyperparameters are the parameters in models that determine model architecture, learning speed and scope, and regularization."
},
{
"code": null,
"e": 526,
"s": 298,
"text": "The search for optimal hyperparameters requires some experti... |
Angular PrimeNG InputNumber Component - GeeksforGeeks | 07 Oct, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the InputNumber component in Angular PrimeNG. We will also learn about the properties, events, methods & styling along with their syntaxes that will be used in the code.
InputNumber component: It allows a user to input content as a numerical value.
Properties:
value: It is used to give the value of the checkbox. It is of number data type, the default value is null.
format: It is used to set whether to format the value. It is of boolean data type, the default value is true.
showButtons: It is used to display spinner buttons. It is of boolean data type, the default value is false.
buttonLayout: It is used to set the layout of the buttons, valid values are “stacked” (default), “horizontal” and “vertical”. It is of string data type, the default value is stacked.
incrementButtonClass: It is used to set the style class of the increment button. It is of string data type, the default value is null.
decrementButtonClass: It is used to set the style class of the decrement button. It is of string data type, the default value is null.
incrementButtonIcon: It is used to set the style class of the increment button. It is of string data type, the default value is pi pi-chevron-up.
decrementButtonIcon: It is used to set the style class of the decrement button. It is of string data type, the default value is pi pi-chevron-down.
locale: It is used to set the locale to be used in formatting. It is of string data type, the default value is null.
localeMatcher: It is used to set the locale matching algorithm to use. It is of string data type, the default value is the best fit.
mode: It is used to define the behavior of the component, valid values are “decimal” and “currency”. It is of string data type, the default value is decimal.
prefix: It is used to set the text to display before the value. It is of string data type, the default value is null.
suffix: It is used to set the text to display after the value. It is of string data type, the default value is decimal.
currency: It is used to set the currency to use in currency formatting. It is of string data type, the default value is null.
currencyDisplay: It is used to specify how to display the currency in currency formatting. It is of string data type, the default value is a symbol.
useGrouping: It is used to set whether to use grouping separators, such as thousands of separators or thousand/lakh/crore separators. It is of boolean data type, the default value is true.
minFractionDigits: It is used to set the minimum number of fraction digits to use. It is of number data type, the default value is null.
maxFractionDigits: It is used to set the maximum number of fraction digits to use. It is of number data type, the default value is null.
min: It is used to set the minimum boundary value. It is of number data type, the default value is null.
max: It is used to set the maximum boundary value. It is of number data type, the default value is null.
step: It is used to set the step factor to increment/decrement the value. It is of number data type, the default value is 1.
style: It is used to set the inline style of the component. It is of string data type, the default value is null.
styleClass: It is used to set the style class of the component. It is of string data type, the default value is null.
inputId: It is an ID identifier of the underlying input element It is of string data type, the default value is null.
inputStyle: It is used to set the inline style of the input field. It is of string data type, the default value is null.
inputStyleClass: It is used to set the style class of the input field. It is of string data type, the default value is null.
placeholder: It is used to set the advisory information to display on input. It is of string data type, the default value is null.
size: It is used to set the size of the input field. It is of number data type, the default value is null.
maxlength: It is used to set the maximum number of characters allows in the input field. It is of number data type, the default value is null.
tabindex: It is used to set the specified tab order of the element. It is of number data type, the default value is null.
disabled: it specifies that the element should be disabled. It is of boolean data type, the default value is false.
title: It is used to set the title text of the input text. It is of string data type, the default value is null.
ariaLabel: It is used to define a string that labels the input element. It is of string data type, the default value is null.
ariaRequired: It is used to indicate that user input is required on an element before a form can be submitted. It is of boolean data type, the default value is false.
name: It is used to set the name of the input field. It is of string data type, the default value is null.
autocomplete: It is used to define a string that autocompletes attributes to the current element. It is of string data type, the default value is null.
Methods:
getFormatter: This method returns Intl.NumberFormat object.
Events:
onFocus: It is a callback that is fired when input receives focus.
onBlur: It is a callback that is fired when input loses focus.
onInput: It is a callback that is fired when the input value is entered.
event.value: It is a callback that is fired when the value is entered.
Styling:
p-inputnumber: It is the container element.
p-inputnumber-stacked: It is the container element with stacked buttons.
p-inputnumber-horizontal: It is the container element with horizontal buttons.
p-inputnumber-vertical: It is the container element with vertical buttons.
p-inputnumber-input: It is the input element.
p-inputnumber-button: It is the input element.
p-inputnumber-button-up: It is the increment button.
p-inputnumber-button-down: It is the decrement button.
p-inputnumber-button-icon: It is the button icon.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following:
Example 1: This is the basic example that illustrates how to use the InputNumber component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG inputNumber component</h5><div class="p-grid p-fluid"> <div class="p-field p-col-12 p-md-3"> <p-inputNumber placeholder="Input number here"> </p-inputNumber> </div></div>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { AppComponent } from "./app.component"; import { InputNumberModule } from "primeng/inputnumber"; @NgModule({ imports: [BrowserModule, InputNumberModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
app.component.ts
import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent {}
Output:
Example 2: In this example, we will know how to use prefix & suffix property in the InputNumber component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG inputNumber component</h5><div class="p-field p-col-12 p-md-3"> <label for="gfg">Prefix and Suffix Property</label> <p-inputNumber inputId="gfg" suffix=")" prefix="(" placeholder="()"> </p-inputNumber></div>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { AppComponent } from "./app.component"; import { InputNumberModule } from "primeng/inputnumber"; @NgModule({ imports: [BrowserModule, InputNumberModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
app.component.ts
import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/inputnumber
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 25521,
"s": 25109,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make resp... |
Pig Latin â Basics | Pig Latin is the language used to analyze data in Hadoop using Apache Pig. In this chapter, we are going to discuss the basics of Pig Latin such as Pig Latin statements, data types, general and relational operators, and Pig Latin UDF’s.
As discussed in the previous chapters, the data model of Pig is fully nested. A Relation is the outermost structure of the Pig Latin data model. And it is a bag where −
A bag is a collection of tuples.
A tuple is an ordered set of fields.
A field is a piece of data.
While processing data using Pig Latin, statements are the basic constructs.
These statements work with relations. They include expressions and schemas.
These statements work with relations. They include expressions and schemas.
Every statement ends with a semicolon (;).
Every statement ends with a semicolon (;).
We will perform various operations using operators provided by Pig Latin, through statements.
We will perform various operations using operators provided by Pig Latin, through statements.
Except LOAD and STORE, while performing all other operations, Pig Latin statements take a relation as input and produce another relation as output.
Except LOAD and STORE, while performing all other operations, Pig Latin statements take a relation as input and produce another relation as output.
As soon as you enter a Load statement in the Grunt shell, its semantic checking will be carried out. To see the contents of the schema, you need to use the Dump operator. Only after performing the dump operation, the MapReduce job for loading the data into the file system will be carried out.
As soon as you enter a Load statement in the Grunt shell, its semantic checking will be carried out. To see the contents of the schema, you need to use the Dump operator. Only after performing the dump operation, the MapReduce job for loading the data into the file system will be carried out.
Given below is a Pig Latin statement, which loads data to Apache Pig.
grunt> Student_data = LOAD 'student_data.txt' USING PigStorage(',')as
( id:int, firstname:chararray, lastname:chararray, phone:chararray, city:chararray );
Given below table describes the Pig Latin data types.
Represents a signed 32-bit integer.
Example : 8
Represents a signed 64-bit integer.
Example : 5L
Represents a signed 32-bit floating point.
Example : 5.5F
Represents a 64-bit floating point.
Example : 10.5
Represents a character array (string) in Unicode UTF-8 format.
Example : ‘tutorials point’
Represents a Byte array (blob).
Represents a Boolean value.
Example : true/ false.
Represents a date-time.
Example : 1970-01-01T00:00:00.000+00:00
Represents a Java BigInteger.
Example : 60708090709
Represents a Java BigDecimal
Example : 185.98376256272893883
A tuple is an ordered set of fields.
Example : (raja, 30)
A bag is a collection of tuples.
Example : {(raju,30),(Mohhammad,45)}
A Map is a set of key-value pairs.
Example : [ ‘name’#’Raju’, ‘age’#30]
Values for all the above data types can be NULL. Apache Pig treats null values in a similar way as SQL does.
A null can be an unknown value or a non-existent value. It is used as a placeholder for optional values. These nulls can occur naturally or can be the result of an operation.
The following table describes the arithmetic operators of Pig Latin. Suppose a = 10 and b = 20.
Addition − Adds values on either side of the operator
Subtraction − Subtracts right hand operand from left hand operand
Multiplication − Multiplies values on either side of the operator
Division − Divides left hand operand by right hand operand
Modulus − Divides left hand operand by right hand operand and returns remainder
Bincond − Evaluates the Boolean operators. It has three operands as shown below.
variable x = (expression) ? value1 if true : value2 if false.
b = (a == 1)? 20: 30;
if a = 1 the value of b is 20.
if a!=1 the value of b is 30.
CASE
WHEN
THEN
ELSE END
Case − The case operator is equivalent to nested bincond operator.
CASE f2 % 2
WHEN 0 THEN 'even'
WHEN 1 THEN 'odd'
END
The following table describes the comparison operators of Pig Latin.
Equal − Checks if the values of two operands are equal or not; if yes, then the condition becomes true.
Not Equal − Checks if the values of two operands are equal or not. If the values are not equal, then condition becomes true.
Greater than − Checks if the value of the left operand is greater than the value of the right operand. If yes, then the condition becomes true.
Less than − Checks if the value of the left operand is less than the value of the right operand. If yes, then the condition becomes true.
Greater than or equal to − Checks if the value of the left operand is greater than or equal to the value of the right operand. If yes, then the condition becomes true.
Less than or equal to − Checks if the value of the left operand is less than or equal to the value of the right operand. If yes, then the condition becomes true.
Pattern matching − Checks whether the string in the left-hand side matches with the constant in the right-hand side.
The following table describes the Type construction operators of Pig Latin.
Tuple constructor operator − This operator is used to construct a tuple.
Bag constructor operator − This operator is used to construct a bag.
Map constructor operator − This operator is used to construct a tuple.
The following table describes the relational operators of Pig Latin.
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 | [
{
"code": null,
"e": 2922,
"s": 2684,
"text": "Pig Latin is the language used to analyze data in Hadoop using Apache Pig. In this chapter, we are going to discuss the basics of Pig Latin such as Pig Latin statements, data types, general and relational operators, and Pig Latin UDF’s."
},
{
"... |
How to apply style to parent if it has child with CSS? - GeeksforGeeks | 28 Feb, 2022
We know how to apply styles to the child elements if a parent class has one. But if we want to apply a style to the parent class and that with CSS. Here’s the way we can do that. A child combinator describes a parent-child between two elements. A child combinator is made of the “greater-than (>)” character and separates two elements.Examples:
E > F, an F element child of an E element.
The following selector represents a “p” element that is child of “body”:body > p.
So the style In the parent class can be by just writing the name once like this
.parent li {
background:blue;
color:black;
}
If we want to apply the style in child class then use this
.parent > li > ul > li {
background:orange
}
Program:
html
<!DOCTYPE html><html><head> <style> .parent li { background:blue; color:black; } .parent > li > ul > li { background:orange } .parent > li > ul > li > ul >li { background:pink; } </style></head> <body> <ul class="parent"> <li>I am first</li> <li>I am second</li> <li>I am third</li> <li>I am forth</li> <li>I am fifth <ul class="child"> <li>child1</li> <li>child2 <ul> <li>child2.1</li> <li>child2.2</li> <li>child2.3</li> </ul> </li> <li>child3</li> <li>child4</li> <li>child5</li> </ul> </li> <li>I am sixth</li> <li>I am seventh</li> <li>I am eight</li> </ul></body></html>
Output:
CSS3 does not have parents selectors. If CSS4 released then there is a proposed CSS4 selector, $, which will be like selecting the li element.
However, as of now, this code can’t be used in any of the browsers.
ul $li ul.sub { ... }
In the meantime, we’ll have to use JavaScript if we need to select a parent element.
$('ul li:has(ul.child)').addClass('has_child');
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
rkbhola5
CSS-Misc
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to Create Time-Table schedule using HTML ?
Installation of Node.js on Linux
Express.js express.Router() Function
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 25128,
"s": 25100,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 25475,
"s": 25128,
"text": "We know how to apply styles to the child elements if a parent class has one. But if we want to apply a style to the parent class and that with CSS. Here’s the way ... |
How to create bins for a continuous vector in R? | To create the bins for a continuous vector, we can use cut function and store the bins in a data frame along with the original vector. The values in the cut function must be passed based on the range of the vector values, otherwise, there will be NA’s in the bin values. For example, if we have a vector that contains 0.55 and we do not use 0 in the cut function then the first bin will be NA. Check out the below examples to understand how to properly do it.
Live Demo
x1<−rnorm(20,5,2)
x1
[1] 3.066708 6.729915 7.706962 7.564306 3.924779 5.400262 2.529380 4.377311
[9] 7.270613 6.135201 5.068060 6.447229 8.603205 4.065874 4.132155 3.060366
[17] 0.953596 2.861802 7.250666 6.928397
df1<−data.frame(x1,bin=cut(x1,c(0,1,2,3,4,5,6,7,8,9),include.lowest=TRUE))
df1
x1 bin
1 3.066708 (3,4]
2 6.729915 (6,7]
3 7.706962 (7,8]
4 7.564306 (7,8]
5 3.924779 (3,4]
6 5.400262 (5,6]
7 2.529380 (2,3]
8 4.377311 (4,5]
9 7.270613 (7,8]
10 6.135201 (6,7]
11 5.068060 (5,6]
12 6.447229 (6,7]
13 8.603205 (8,9]
14 4.065874 (4,5]
15 4.132155 (4,5]
16 3.060366 (3,4]
17 0.953596 [0,1]
18 2.861802 (2,3]
19 7.250666 (7,8]
20 6.928397 (6,7]
Live Demo
x2<−runif(20,2,5)
x2
[1] 2.656399 2.436808 3.704048 3.572767 2.321280 2.982751 4.911949 2.483126
[9] 2.177203 2.797627 4.621546 3.645550 2.888457 2.919597 4.354709 4.251886
[17] 4.862071 3.367629 2.610280 3.063467
df2<−data.frame(x1,bin=cut(x2,c(2,3,4,5),include.lowest=TRUE))
df2
x1 bin
1 3.066708 [2,3]
2 6.729915 [2,3]
3 7.706962 (3,4]
4 7.564306 (3,4]
5 3.924779 [2,3]
6 5.400262 [2,3]
7 2.529380 (4,5]
8 4.377311 [2,3]
9 7.270613 [2,3]
10 6.135201 [2,3]
11 5.068060 (4,5]
12 6.447229 (3,4]
13 8.603205 [2,3]
14 4.065874 [2,3]
15 4.132155 (4,5]
16 3.060366 (4,5]
17 0.953596 (4,5]
18 2.861802 (3,4]
19 7.250666 [2,3]
20 6.928397 (3,4] | [
{
"code": null,
"e": 1522,
"s": 1062,
"text": "To create the bins for a continuous vector, we can use cut function and store the bins in a data frame along with the original vector. The values in the cut function must be passed based on the range of the vector values, otherwise, there will be NA’s i... |
SOAP - Messages | A SOAP message is an ordinary XML document containing the following elements −
Envelope − Defines the start and the end of the message. It is a mandatory element.
Envelope − Defines the start and the end of the message. It is a mandatory element.
Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element.
Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element.
Body − Contains the XML data comprising the message being sent. It is a mandatory element.
Body − Contains the XML data comprising the message being sent. It is a mandatory element.
Fault − An optional Fault element that provides information about errors that occur while processing the message.
Fault − An optional Fault element that provides information about errors that occur while processing the message.
All these elements are declared in the default namespace for the SOAP envelope −
https://www.w3.org/2001/12/soap-envelope
The default namespace for SOAP encoding and data types is −
https://www.w3.org/2001/12/soap-encoding
Note − All these specifications are subject to change. Thus, keep updating yourself with the latest specifications available on the W3 website.
The following block depicts the general structure of a SOAP message −
<?xml version = "1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding">
<SOAP-ENV:Header>
...
...
</SOAP-ENV:Header>
<SOAP-ENV:Body>
...
...
<SOAP-ENV:Fault>
...
...
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP_ENV:Envelope>
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2213,
"s": 2134,
"text": "A SOAP message is an ordinary XML document containing the following elements −"
},
{
"code": null,
"e": 2297,
"s": 2213,
"text": "Envelope − Defines the start and the end of the message. It is a mandatory element."
},
{
"code... |
C++ | Operator Overloading | Question 10 - GeeksforGeeks | 23 Nov, 2021
Which of the following operator functions cannot be global, i.e., must be a member function.(A) new(B) delete(C) Conversion Operator(D) All of the aboveAnswer: (C)Explanation: new and delete can be global, see following example.
#include
#include
#include
using namespace std;
class Myclass {
int x;
public:
friend void* operator new(size_t size);
friend void operator delete(void*);
Myclass(int i) {
x = i;
cout << "Constructor called \n";
}
~Myclass() { cout << "Destructor called \n"; }
};
void* operator new(size_t size)
{
void *storage = malloc(size);
cout << "new called \n";
return storage;
}
void operator delete(void *p )
{
cout<<"delete called \n";
free(p);
}
int main()
{
Myclass *m = new Myclass(5);
delete m;
return 0;
}
Quiz of this Question
clintra
C++-Operator Overloading
cpp-overloading
Operator Overloading
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
C++ | Inheritance | Question 7
C++ | Function Overloading and Default Arguments | Question 2
C++ | Inheritance | Question 6
C++ | Misc C++ | Question 8
C++ | Inheritance | Question 5 | [
{
"code": null,
"e": 24341,
"s": 24313,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 24570,
"s": 24341,
"text": "Which of the following operator functions cannot be global, i.e., must be a member function.(A) new(B) delete(C) Conversion Operator(D) All of the aboveAnswer: (C)... |
How to create a circle using JavaFX? | A circle is a line forming a closed loop, every point on which is a fixed distance from a center point. A circle is defined by its center and radius − distance from the center to any point on the circle.
In JavaFX a circle is represented by the javafx.scene.shape.Circle class. This class contains three properties they are −
centerX − This property represents the x coordinate of the center of a circle, you can set the value to this property using the setCenterX() method.
centerX − This property represents the x coordinate of the center of a circle, you can set the value to this property using the setCenterX() method.
centerY − This property represents y coordinate of the center of a circle, you can set the value to this property using the setCenterY() method.
centerY − This property represents y coordinate of the center of a circle, you can set the value to this property using the setCenterY() method.
radius − The radius of the circle in pixels, you can set the value to this property using the setRadius() method.
radius − The radius of the circle in pixels, you can set the value to this property using the setRadius() method.
To create a circle you need to −
Instantiate the class Circle.
Instantiate the class Circle.
Set the required properties using the setter methods or, bypassing them as arguments to the constructor.
Set the required properties using the setter methods or, bypassing them as arguments to the constructor.
Add the created node (shape) to the Group object.
Add the created node (shape) to the Group object.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
public class DrawingCircle extends Application {
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the properties of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
circle.setRadius(100.0f);
//Setting other properties
circle.setFill(Color.DARKCYAN);
circle.setStrokeWidth(8.0);
circle.setStroke(Color.DARKSLATEGREY);
//Setting the Scene
Group root = new Group(circle);
Scene scene = new Scene(root, 595, 300, Color.BEIGE);
stage.setTitle("Drawing a Circle");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1266,
"s": 1062,
"text": "A circle is a line forming a closed loop, every point on which is a fixed distance from a center point. A circle is defined by its center and radius − distance from the center to any point on the circle."
},
{
"code": null,
"e": 1388,
"s... |
BYOD: Build Your Own Dataset (for free using web scraping) | by Rishav Agarwal | Towards Data Science | Ten second takeaway: Learn how to create your own dataset with simple web scraping that mines the entire Metacritic website for game reviews using python’s beautiful soup and hosted for free on Google Cloud Platform (GCP) micro (always free tier)
Aspiring data scientists are always confused about the first step after learning the theory. There are very few places where they can apply the accrued knowledge. Sure there are plenty of datasets available but the free ones never give you a pragmatic insight into solving actual problems or sometimes they are too small to use for deep learning applications.
One way to get robust datasets is either to pay for them or enrol in expensive courses, and another is web scraping. Here I tell you how to scrape large datasets using python for free!
Data gets stale: When you scrape data you potentially get the latest data for any topic. While you can get robust datasets from Kaggle, if you want to creating something fresh for you or your company, scraping is the way to go, for example. if you want to build a price recommendation for shoes you would want the latest trends and prices from Amazon and not 2 years old data.
Customisable: You can tailor fit the code to get only the data you need from any source you want.
Why not local? With big players like Google and Amazon in the cloud computing market it’s very cheap to rent out a PC for a few hours. They also give you a free tier which is perfect for something simple like web scraping. GCP is slightly cheaper and gives you $300 credit to start with so I went with GCP. Also, I didn’t want my IP to get blocked (heh)
Fun: Well this is my idea of a Friday night!
In my case I did not find a good dataset for game reviews that was fairly new, as Metacrtic has the largest game repository and gets updated fairly regularly I decided to go with that.
All you need to do is iterate over a list of URL, identify the containers for the data, extract the data and store it in a csv.
1. Libraries used
import urllib2import csvfrom bs4 import BeautifulSoupimport pandas as pd
urllib2 : Our library for making url requests.
csv: Library to store data in a CSV
bs4: The beautiful soup library that makes extracting data from a webpage very easy.
pandas: Store the data in a nice tabular format.
2. Understanding the flow of the website
Metacritic layout is pretty simple. All the data is structured as follows
http://www.metacritic.com/browse/games/release-date/available/pc/metascore?view=detailed&page=1
lets break it down:
http://www.metacritic.com/browse/: is the domain
games: This gives the subsection and can be replaces by movies/music for other subsections
available/pc/ : This part gives the data for pc. Change this to ps4 for data on ps4 games.
metascore: this gives the rankings by meta score we can change this to “user_rating” to get data by user rating.
view=detailed : This gives the view type we choose detailed as it contains more data like genre and maturity rating.
page=x: This gives the page number x. Incase the page number doesn’t exist the site return a blank template page with no data and doesn’t throw an error
Next we decide on the html elements which have the data. For this we use the inspect tool in Chrome. We select on the elements to and highlight the subsection to get the html element and its class .
Now we know what element we need to extract let’s go ahead and extract them.
3. Making URL requests
metacritic_base = “http://www.metacritic.com/browse/games/release-date/available/pc/metascore?view=detailed&page="hdr= {‘Accept’: ‘text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8’, ‘User-Agent’ : “Magic Browser”}filepath=’/Users/rra/Downloads/’for i in range(0,54): metacritic = metacritic_base+str(i) page = urllib2.Request(metacritic, headers=hdr ) content = urllib2.urlopen(page).read()
Metacritic has a simple site layout with a static URL where page number changes for each page.
we use the urllib2.Request to request for the page and Urllib2.urlopen to read the page data
Tip: There are 53 pages so I put my counter to max out at 54 however you can simply include all this in a try except which exits on encountering an error.
4. Extracting data
We then read the data
soup = BeautifulSoup(content, ‘html.parser’)right_class=soup.find_all(‘div’, class_=’product_wrap’)for item in right_class: try: link=item.find(‘h3’, class_=”product_title”).find(“a”) g=link.get(‘href’) except: g=’' try: score = item.find(“span”, class_=”metascore_w”) s=score.text except: s =’’ try: dt = item.find("li", class_="release_date").find("span", class_="data") d=dt.text except: dt='' try: rating=item.find("li",class_="stat maturity_rating").find("span", class_="data") r= rating.text except: r="" try: pub =item.find("li",class_="stat publisher").find("span", class_="data") p= pub.text except: p='' try: genre= item.find("li",class_="stat genre").find("span", class_="data") gr = genre.text except: gr='' try: user_score=item.find("span", class_="textscore") u = user_score.text except: u=''
We use BeautifulSoup(content, ‘html.parser’) which does all the heavy lifting of parsing the vast amount of HTML.
Now we saw in the previous section that each game data is in a div with a class called product_wrap. So we extract all such divs and iterate over each div to get to the data. Here we store the following data:
g: game name
s: metascore
d: release date
p: publisher
r: mturity rating
u: user rating
gr: genre
Tip: HTML is unreliable so it’s better to use try:except witch each extraction
5. Saving data
game=[g,s,d,r,p,gr.strip(),u]df = pd.DataFrame([game])with open(filepath+'gamenames.csv', 'a') as f: df.to_csv(f, header=False, index=False, quoting=csv.QUOTE_NONNUMERIC, sep="|")
We use pandas to convert the list of list into a table and then write the data to a csv. Here we use the | as a delimiter as the genre column contains , (comma)
6. Running the code on Google cloud
I’m assuming you would know how to setup a GCP account. If now please follow this blogpost on how. You need to create an instance as follows.
Once it is running you need to install python on it and copy the code from your local machine to the instance. Here spheric-crow is the project name and instance-2 is the instance name. You need to also specify the time zone to google.
Tip: Remember to update your ubuntu once you ssh to the instance.
gcloud compute — project “spheric-crow” ssh — zone “us-east1-b” “instance-2”gcloud compute scp scrap.py instance-1:scrap
scp copies the file from the local machine to the GCP instance. Next you need to install the aforementioned libraries on your instance. Next install byobu which is a text based windows manager. This will keep the session intact even if your ssh connection breaks.
Sudo apt-get install byobubyobu
Finally run the code using the following command and you are done.
python scrap.py
Tip: You can scp or simply git pull from my github account.
7. Retrieving the mined data
You can get the mined data from the cloud using scp again and now you have a really cool dataset to play with!
gcloud compute scp instance-1:scrap/game_review.csv /Users/
you can then access the data using python as
import pandas as pddf= pd.read_csv(“/metacritic_scrap/gamenames.csv”, sep=”|”)df.columns=[“game”, “metascore”,”release_date”, “maturity_rating”,”publisher”, “genre”, “user_rating”]
and your dataset will look like
See how nicely structured this is!
Tip: You can automate this too!
Be polite: Most sites would frown upon you mining their content as it puts a lot of pressure on their servers. Try to avoid making too many request in a short time and read the robots.txt file. Here are a couple of tricks to get as little errors as possible:
Be polite: Most sites would frown upon you mining their content as it puts a lot of pressure on their servers. Try to avoid making too many request in a short time and read the robots.txt file. Here are a couple of tricks to get as little errors as possible:
Sleep: Include sleep which delays the code by a few seconds before the next request is made. I prefer to use sleep (randint(a,b)) i.e use a random integer instead of a fixed value.
from random import randintfrom time import sleep#pause for 20-100 seconds randomlysleep(randint(20,100))
User Agent: It is a string that a browser or app sends to each website you visit. We use a user_agent generator to trick the website into thinking that the request is coming form different browsers. As many institutions use the same IP we don’t usually risk getting a too many request error. Here is a list of popular user agents you can use.
from user_agent import generate_user_agent
VPN and Proxies: If you are mining a large dataset chances are that you will get a too many requests error eventually. In my case around every 2000 pages. So to counter that you can rotate a few proxies and get ~5k pages per instance run. You can get some free proxies here.
2. Caught in a Captcha: Some websites really don’t want you scraping their data and they put a captcha in place. If it’s a simple 4–5 alphanumeric captcha you can try to work it using Python Tesseract and this technique. If it the google re-captcha you have to manually solve each time just like these guys.
3. Exception Handling: HTML is very unreliable and site may not follow a strict pattern all the time so the best practice is to include each element in a try:except statement.
4. Saving periodically: Web scraping is risky business and if you don’t save data regularly you may risk losing the entire dataset mined so far. A simple solution to this is to save data regularly in a csv (like I do) or use SQLite (like the smart people do). A introduction to sqlite can be found here.
We can use the same code to mine Metacritic for loads of other content just by changing the base url:
movie reviews/ratings
tv show reviews/ratings
music reviews/rating
I extended my code to mine for data all ~100k user reviews for ~5k PC games and I had mentioned I will be using it for a game recommendation engine (blog posts to follow). If you want a slice of the action email me and I’ll send you a part of the dataset!
Metracritic’s site layout is pretty easy to follow and is replicated by a simple for loop but for mining more complicated sites like Amazon we use a browser automation tool called Puppeteer, which simulates clicks to generate the next page and so on.
Check out this great blog by Emad Eshan on how to use Puppeteer.
The entire code for this blog can be found on my git. The entire code for the user review scraping can also be found here.
In the next blog, I’ll be doing some data wrangling and deep learning on this great dataset. Stay tuned!
This is my first post so if you liked it, do comment and clap :) | [
{
"code": null,
"e": 419,
"s": 172,
"text": "Ten second takeaway: Learn how to create your own dataset with simple web scraping that mines the entire Metacritic website for game reviews using python’s beautiful soup and hosted for free on Google Cloud Platform (GCP) micro (always free tier)"
},
... |
Boost Power BI performance by improving cardinality levels | by Nikola Ilic | Towards Data Science | Performance, performance, performance...We are always striving to achieve it (or at least we SHOULD strive), but there are so many things to keep in mind when tuning Power BI reports. The first step in the optimization process is to ensure that your data model size is in optimal condition — which means, reduce the data model size whenever possible! This will enable VertiPaq’s Storage Engine to work in a more efficient way when retrieving the data for your report.
When you are working on optimizing a data model size, do you know who is your “enemy” number 1?! Column data type, right? Text columns will consume much more memory than a column of numeric type? That’s just half true!
Before we explain what is cardinality, and why it is so important for reducing the data model size, let’s first discuss the way VertiPaq stores the data, once you set the storage mode of the table to Import (DirectQuery storage mode is out of the scope of this article, so from now on, everything in this article about cardinality refers to Import storage mode exclusively).
Once you set the storage mode to Import, VertiPaq will scan the sample rows from the column, and based on the data in the specific column (don’t forget, VertiPaq is a columnar database, which means that each column has its own structure and is physically separated from the other columns), it will apply a certain compression algorithm to the data.
There are three different encoding types:
Value encoding — applies to integer data type exclusively
Hash encoding — applies to all non-integer data types, plus to integer data types in certain scenarios
RLE (Run-Length-Encoding) — occurs after Hash encoding, as an additional compression step, in those scenarios when the data in the column is sorted that way that VertiPaq “thinks” it can achieve a better compression rate, than using a Hash algorithm only
Again, before we explain where the concept of cardinality fits in the whole story, let’s illustrate how the Hash algorithm works in the background:
As you may see, VertiPaq will create a dictionary of the distinct values from the column, assign a bitmap index to each of these values, and then store this index value instead of the “real” value — simply said, it will store number 1 as a pointer to “Book” value, number 2 for “Shirt”, and so on. It’s like creating a virtual dimension table in the background!
Now, imagine that instead of two distinct values in the column, we have something like this:
Our “dimension” will now have 10 rows, so you may assume that the size of this dictionary table will be significantly larger than in the previous case with only two distinct values.
Now, you’re probably asking yourselves: ok, that’s fine, but what does all this story has in common with cardinality?
In our first example, we had a cardinality of 2, while in the second case, cardinality equals 10.
And cardinality is the top factor that affects the size of the column. Don’t forget, column size is not affected only by the size of the data in it. You should always take into account dictionary size, same as hierarchy size. For columns that have high cardinality (huge number of distinct values), and are not of integer data type, the dictionary size is significantly larger than the data size itself.
Let me show you one example. I’ll use DAX Studio to analyze different metrics behind my data model size. Once I open the Advanced tab in DAX Studio and select View Metrics, a whole range of different figures will be available, to understand how big are specific parts of my data model:
Let’s quickly reiterate the key insights from the illustration above. Within the Chats table, the datetmStartUTC column, which is of Date/Time data type and goes to the second level of precision, has almost 9 million distinct values! Its size is ca. 455 MBs — this figure includes not just data size only, which is 26 MBs, but also dictionary size and hierarchy size. You can see that VertiPaq applied the Hash algorithm to compress the data from this column, but the biggest portion of the memory footprint goes on the dictionary size (almost 358 MBs).
This is, obviously, far from the optimal condition for our data model. However, I have good news for you...
In one of the previous articles, I’ve explained how you can reduce the cardinality by applying some more advanced approaches, such as using division and modulo operations to split one numeric column with high cardinality into two columns with lower cardinality and saving a few bits per row. I’ve also shown you how to split the Date/Time column into two separate columns — one containing the date portion only, while the other keeps time data.
However, these techniques require additional effort on the report side, as all the measures need to be rewritten to reflect data model structural changes and return correct results. Therefore, those advanced approaches are not something you’ll need to apply in your regular data model optimization — they are more of an “edge” use-case, when there is no other way to reduce the size of the data model — simply said, when you’re dealing with extremely large datasets!
But, that doesn’t mean that you should not strive to improve the cardinality levels even for the smaller and simpler data models. On the opposite, that should be a regular part of your Power BI development process. In this article, I’ll show you two simple approaches that can significantly reduce the cardinality of the column, thus reducing the overall data model size.
Let’s be honest — how often do your users need to analyze the data on the second level? Like, how many sales do we have at 09:35:36, or 11:22:48? Makes no sense, I would say. In 98% of cases, the business request is to have data available on a daily level. Maybe in some circumstances, users need to understand which part of the day is the most “productive”: morning, afternoon, or evening...but still, let’s focus on the majority of cases where the data should be grained on a daily level.
I’ve changed the data type of the column, from Date/Time to Date, as the time portion is irrelevant for reporting purposes. Let’s refresh our metrics in DAX Studio:
Oh, wow! Instead of cardinality of ~ 9 million, we now have only 1356 (that’s the number of distinct days in the column). But, what’s more important, the size of the column dropped from 455 MB to 7 MB! That’s huuuuge! Look at the dictionary size: instead of having to build a dictionary for 9 million values, VertiPaq now handled just 1356 distinct values, and dictionary size dropped from 358 MBs to 85 KBs!
The other trick you can apply is when you’re dealing with decimal values. It’s not a rare situation that you import the data into Power BI “as-it-is” — and, not once, I saw people importing the decimal numbers that go to a 5 digit precision after the decimal point! I mean, is it really necessary to know that your total sales amount is 27.586.398,56891, or is it ok to display 27.586.398,57?
Just to be clear, formatting values to display 2 decimal places in the Power BI won’t affect the data model size — it’s just a formatting option for your visuals — in the background, data is being stored with 5 digits after the decimal place.
Now, let’s check the metrics of this table in DAX Studio. This is a trivial data model size, with only 151 distinct values in it, but you can only imagine the difference on multi-million rows table:
I’ll now go to Power Query Editor and change the type of this column to Fixed Decimal number:
We’ve now rounded values to 2 decimal places after the decimal point, so let’s switch back to DAX Studio and check the numbers again:
The difference is obvious, even on this extremely small dataset!
The other technique I wanted to show you is how to leverage concepts of summarization and grouping to improve the cardinality levels and make your data model more performant.
When you are creating reports, chances are that the users need to understand different metrics on a higher level of granularity than the individual transaction — for example, how many products were sold on a specific date, how many customers signed up on a specific date, and so on. This means that most of your analytical queries don’t need to target a single transaction, as the summarized data would be completely fine.
Let’s examine the difference in the memory footprint if we summarize the data for our Chats table. The original table, as you may recall from the previous part of the article, takes 555 MBs:
Now, if I summarize the data in advance, and group it per date and/or product, by writing the following T-SQL:
SELECT CONVERT(DATE,datetmStartUTC) AS datetm,productID,COUNT(chatID) AS totalChatsFROM ChatsGROUP BY CONVERT(DATE,datetmStartUTC),productID
If the most frequent business requests are to analyze the number of chats per date and/or product, this query will successfully satisfy these requests.
Let’s check the size of this summarized table, compared to the original one:
While the original table, even with an improved cardinality level for the datetmStartUTC column, takes 105 MBs, the aggregated table takes only 217 KB! And this table can answer most of the business analysis questions. Even if you need to include additional attributes, for example, customer data, this will still be a more optimal method to retrieve the data.
There is more to this!
Even if you’re not able to create summarized data on the data source side, you can still get a significant performance boost by leveraging the aggregation feature in Power BI. This is one of the most powerful features in Power BI and deserves a separate article, or even a series of articles, like this from Phil Seamark, which I always refer to when I need a deeper understanding of the aggregations and the way it works in Tabular model.
Building an optimal data model is not an easy task! There are many potential caveats and it’s sometimes hard to avoid all the traps along the road to a “perfect” model. However, understanding the importance of reducing the overall data model size is one of the key requirements when tuning your Power BI solutions.
With that in mind, to be able to achieve optimal data model size, you need to absorb the concept of cardinality, as the main factor that determines the column size. By understanding cardinality in a proper way, and the way VertiPaq stores and compresses the data, you should be able to apply some of the techniques we’ve just covered, to improve the cardinality levels of the column, and consequentially, boost the overall performance of your reports!
Thanks for reading!
Become a member and read every story on Medium! | [
{
"code": null,
"e": 639,
"s": 171,
"text": "Performance, performance, performance...We are always striving to achieve it (or at least we SHOULD strive), but there are so many things to keep in mind when tuning Power BI reports. The first step in the optimization process is to ensure that your data ... |
8086 program to sort an integer array in descending order - GeeksforGeeks | 29 Jun, 2018
Problem – Write a program in 8086 microprocessor to sort numbers in descending order in an array of n numbers, where size “n” is stored at memory address 2000 : 500 and the numbers are stored from memory address 2000 : 501.
Example –
Example explanation:
Pass-1:
32 05 14 50
32 05 14 50
32 14 05 50
32 14 50 05 (1 number got fix)
Pass-2:
32 14 50 05
32 14 50 05
32 50 14 05 (2 number got fix)
Pass-3:
32 50 14 05
50 32 14 05 (sorted)
Pass-1:
32 05 14 50
32 05 14 50
32 14 05 50
32 14 50 05 (1 number got fix)
Pass-2:
32 14 50 05
32 14 50 05
32 50 14 05 (2 number got fix)
Pass-3:
32 50 14 05
50 32 14 05 (sorted)
Algorithm –
Load data from offset 500 to register CL (for count).Travel from starting memory location to last and compare two numbers if first number is smaller than second number then swap them.First pass fix the position for last number.Decrease the count by 1.Again travel from starting memory location to (last-1, by help of count) and compare two numbers if first number is smaller than second number then swap them.Second pass fix the position for last two numbers.Repeate.
Load data from offset 500 to register CL (for count).
Travel from starting memory location to last and compare two numbers if first number is smaller than second number then swap them.
First pass fix the position for last number.
Decrease the count by 1.
Again travel from starting memory location to (last-1, by help of count) and compare two numbers if first number is smaller than second number then swap them.
Second pass fix the position for last two numbers.
Repeate.
Program –
Explanation –
MOV SI, 500: set the value of SI to 500.MOV CL, [SI]: load data from offset SI to register CL.DEC CL: decrease value of register CL BY 1.MOV SI, 500: set the value of SI to 500.MOV CH, [SI]: load data from offset SI to register CH.DEC CH: decrease value of register CH BY 1.INC SI: increase value of SI BY 1.MOV AL, [SI]: load value from offset SI to register AL.INC SI: increase value of SI BY 1.CMP AL, [SI]: compares value of register AL and [SI] (AL-[SI]).JNC 41C: jump to address 41C if carry not generated.XCHG AL, [SI]: exchange the contents of register AL and SI.DEC SI: decrease value of SI by 1.XCHG AL, [SI]: exchange the contents of register AL and SI.INC SI: increase value of SI by 1.DEC CH: decrease value of register CH by 1.JNZ 40F: jump to address 40F if zero flat reset.DEC CL: decrease value of register CL by 1.JNZ 407: jump to address 407 if zero flat reset.HLT: stop.
MOV SI, 500: set the value of SI to 500.
MOV CL, [SI]: load data from offset SI to register CL.
DEC CL: decrease value of register CL BY 1.
MOV SI, 500: set the value of SI to 500.
MOV CH, [SI]: load data from offset SI to register CH.
DEC CH: decrease value of register CH BY 1.
INC SI: increase value of SI BY 1.
MOV AL, [SI]: load value from offset SI to register AL.
INC SI: increase value of SI BY 1.
CMP AL, [SI]: compares value of register AL and [SI] (AL-[SI]).
JNC 41C: jump to address 41C if carry not generated.
XCHG AL, [SI]: exchange the contents of register AL and SI.
DEC SI: decrease value of SI by 1.
XCHG AL, [SI]: exchange the contents of register AL and SI.
INC SI: increase value of SI by 1.
DEC CH: decrease value of register CH by 1.
JNZ 40F: jump to address 40F if zero flat reset.
DEC CL: decrease value of register CL by 1.
JNZ 407: jump to address 407 if zero flat reset.
HLT: stop.
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Memory Hierarchy Design and its Characteristics
8085 program to add two 8 bit numbers
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Architecture of 8086
Computer Organization | RISC and CISC
Memory mapped I/O and Isolated I/O
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Programmable peripheral interface 8255 | [
{
"code": null,
"e": 24904,
"s": 24876,
"text": "\n29 Jun, 2018"
},
{
"code": null,
"e": 25128,
"s": 24904,
"text": "Problem – Write a program in 8086 microprocessor to sort numbers in descending order in an array of n numbers, where size “n” is stored at memory address 2000 : 50... |
Reverse Linked List in Python | Suppose we have a linked list, we have to reverse it. So if the list is like 1 → 3 → 5 → 7, then the new reversed list will be 7 → 5 → 3 → 1
To solve this, we will follow this approach −
Define one procedure to perform list reversal in a recursive way as to solve(head, back)
if the head is not present, then return head
temp := head.next
head.next := back
back = head
if temp is empty, then return head
head = temp
return solve(head, back)
Let us see the following implementation to get a better understanding −
Live Demo
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = "ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
return self.solve(head,None)
def solve(self, head, back):
if not head:
return head
temp= head.next
#print(head.val)
head.next = back
back = head
if not temp:
return head
head = temp
return self.solve(head,back)
list1 = make_list([1,3,5,7])
ob1 = Solution()
list2 = ob1.reverseList(list1)
print_list(list2)
list1 = [1,3,5,7]
[7, 5, 3, 1, ] | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "Suppose we have a linked list, we have to reverse it. So if the list is like 1 → 3 → 5 → 7, then the new reversed list will be 7 → 5 → 3 → 1"
},
{
"code": null,
"e": 1249,
"s": 1203,
"text": "To solve this, we will follow this approa... |
ES6 - Dialog Boxes | JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss each dialog box one by one.
An alert dialog box is mostly used to send a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to send a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box provides only one button "OK" to select and proceed.
<html>
<head>
<script type = "text/javascript">
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>
The following output is displayed on successful execution of the above code.
A confirmation dialog box is mostly used to take the user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box as follows.
<html>
<head>
<script type = "text/javascript">
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
} else {
Document.write ("User does not want to continue!");
return false;
}
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>
The following output is displayed on successful execution of the above code.
The prompt dialog box is very useful when you want to pop-up a text box to get a user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null.
<html>
<head>
<script type = "text/javascript">
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>
The following output is displayed on successful execution of the above code.
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2515,
"s": 2277,
"text": "JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users. Here we will discuss each dialog box one by one."
},
{
"... |
Find the equation of the straight line passing through the given points - GeeksforGeeks | 26 Nov, 2021
Given an array arr containing N coordinate points in a plane, the task is to check whether the coordinate points lie on a straight line or not. If they lie on a straight line then print Yes and also the equation of that line otherwise print No.
Example:
Input: arr[] = {{1, 1}, {2, 2}, {3, 3}} Output: Yes1x- 1y=0
Input: arr[] = {{0, 1}, {2, 0}}Output:Yes2y+x-2 = 0
Input: arr[] = {{1, 5}, {2, 2}, {4, 6}, {3, 5}}Output: No
Approach: The idea is to find the equation of the line that can be formed using any one pair of points given in the array and if all other points satisfy the equation of the line formed using the pair of the points, then all these points together form a straight line. So, if all points satisfy the equation of the line, then print Yes followed by the equation of the line, otherwise print No.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if a straight line// can be formed using N pointsvoid isStraightLinePossibleEq( vector<pair<int, int> > arr, int n){ // First pair of point (x0, y0) int x0 = arr[0].first; int y0 = arr[0].second; // Second pair of point (x1, y1) int x1 = arr[1].first; int y1 = arr[1].second; int dx = x1 - x0, dy = y1 - y0, c = dy * x0 - dx * y0; // Loop to iterate over the points // and check whether they satisfy // the equation or not. for (int i = 2; i < n; i++) { int x = arr[i].first, y = arr[i].second; if ((dx * y) - (dy * x) != c) { cout << "No"; return; } } cout << "Yes" << endl; cout << dy << "x-" << dx << "y=" << c << "\n";} // Driver Codeint main(){ // Array of points vector<pair<int, int> > arr = { { 0, 0 }, { 1, 1 }, { 3, 3 }, { 2, 2 } }; int N = 2; // Function Call isStraightLinePossibleEq(arr, N); return 0;}
// Java program for the above approachimport java.util.*; public class GFG{ // Function to check if a straight line// can be formed using N pointsstatic void isStraightLinePossibleEq(int arr[][], int n){ // First pair of point (x0, y0) int x0 = arr[0][0]; int y0 = arr[0][1]; // Second pair of point (x1, y1) int x1 = arr[1][0]; int y1 = arr[1][1]; int dx = x1 - x0, dy = y1 - y0, c = dy * x0 - dx * y0; // Loop to iterate over the points // and check whether they satisfy // the equation or not. for (int i = 2; i < n; i++) { int x = arr[i][0], y = arr[i][1]; if ((dx * y) - (dy * x) != c) { System.out.print("No"); return; } } System.out.print("Yes" + "\n"); System.out.print(dy + "x-" + dx + "y=" + c + "\n");} // Driver Codepublic static void main(String args[]){ // Array of points int arr[][] = {{ 0, 0 }, { 1, 1 }, { 3, 3 }, { 2, 2 }}; int N = 2; // Function Call isStraightLinePossibleEq(arr, N); }}// This code is contributed by Samim Hossain Mondal.
# Python code for the above approach # Function to check if a straight line# can be formed using N pointsdef isStraightLinePossibleEq(arr, n): # First pair of point (x0, y0) x0 = arr[0][0] y0 = arr[0][1] # Second pair of point (x1, y1) x1 = arr[1][0] y1 = arr[1][1] dx = x1 - x0 dy = y1 - y0 c = dy * x0 - dx * y0 # Loop to iterate over the points # and check whether they satisfy # the equation or not. for i in range(2, n): x = arr[i][0], y = arr[i][1] if (dx * y) - (dy * x) != c: print("No") return print("Yes") print(str(dy)+ "x" +"-" + str(dx)+ "y"+ "="+ str(c)) # Driver Code # Array of pointsarr = [[0, 0], [1, 1], [3, 3], [2, 2]]N = 2 # Function CallisStraightLinePossibleEq(arr, N) # This code is contributed by Potta Lokesh
// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to check if a straight line// can be formed using N pointsstatic void isStraightLinePossibleEq(int [,]arr, int n){ // First pair of point (x0, y0) int x0 = arr[0, 0]; int y0 = arr[0, 1]; // Second pair of point (x1, y1) int x1 = arr[1, 0]; int y1 = arr[1, 1]; int dx = x1 - x0, dy = y1 - y0, c = dy * x0 - dx * y0; // Loop to iterate over the points // and check whether they satisfy // the equation or not. for (int i = 2; i < n; i++) { int x = arr[i, 0], y = arr[i, 1]; if ((dx * y) - (dy * x) != c) { Console.Write("No"); return; } } Console.Write("Yes" + "\n"); Console.Write(dy + "x-" + dx + "y=" + c + "\n");} // Driver Codepublic static void Main(){ // Array of points int[,] arr = new int[4, 2] {{ 0, 0 }, { 1, 1 }, { 3, 3 }, { 2, 2 }}; int N = 2; // Function Call isStraightLinePossibleEq(arr, N); }} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript program for the above approach // Function to check if a straight line // can be formed using N points const isStraightLinePossibleEq = (arr, n) => { // First pair of point (x0, y0) let x0 = arr[0][0]; let y0 = arr[0][1]; // Second pair of point (x1, y1) let x1 = arr[1][0]; let y1 = arr[1][1]; let dx = x1 - x0, dy = y1 - y0, c = dy * x0 - dx * y0; // Loop to iterate over the points // and check whether they satisfy // the equation or not. for (let i = 2; i < n; i++) { let x = arr[i][0], y = arr[i][1]; if ((dx * y) - (dy * x) != c) { cout << "No"; return; } } document.write("Yes<br/>"); document.write(`${dy}x-${dx}y=${c}<br/>`); } // Driver Code // Array of points let arr = [[0, 0], [1, 1], [3, 3], [2, 2]]; let N = 2; // Function Call isStraightLinePossibleEq(arr, N); // This code is contributed by rakeshsahni </script>
Yes
1x-1y=0
Time Complexity: O(N)Auxiliary Space: O(1)
rakeshsahni
samim2000
lokeshpotta20
Accenture
Coordinate Geometry
Geometric
Mathematical
Accenture
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Circle and Lattice Points
Queries on count of points lie inside a circle
Convex Hull using Divide and Conquer Algorithm
Maximum number of region in which N non-parallel lines can divide a plane
Equation of circle when three points on the circle are given
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 24987,
"s": 24959,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 25232,
"s": 24987,
"text": "Given an array arr containing N coordinate points in a plane, the task is to check whether the coordinate points lie on a straight line or not. If they lie on a st... |
How to Analyze 100-Dimensional Data with UMAP in Breathtakingly Beautiful Ways | Towards Data Science | No matter how powerful machine learning models are, they can't quite beat the feeling you get during those "Aha!" moments of exploring data through rich visuals. But, there are so many histograms, scatterplots, heatmaps you can create before you say, "this is really getting old."
In those moments, you need something that reminds you of how amazing and mesmerizing data can be. You need to get inspiration from masterpiece visuals like at FlowingData or relevant subreddits, but you don't have to go that far. Recently, I have been fortunate to come across UMAP — a Python package to visualize and cluster high-dimensional data in breathtakingly beautiful ways. It was just what I needed to remember why I got into learning data science two years ago.
Today, we will learn how to analyze multi-dimensional datasets by projecting them to 2D using Uniform Manifold Approximation & Projection (UMAP) package through visuals like below:
UMAP is a dimensionality reduction algorithm and a powerful data analysis tool.
It is similar to PCA (Principal Component Analysis) in terms of speed and resembles tSNE to reduce dimensionality while preserving as much information of the dataset as possible. Before the UMAP algorithm was introduced in 2018, PCA and tSNE had two most significant flaws:
PCA was very fast at the cost of losing finer details of the data after the reductiontSNE was extremely slow even though it preserves the underlying structure of the data.
PCA was very fast at the cost of losing finer details of the data after the reduction
tSNE was extremely slow even though it preserves the underlying structure of the data.
We will talk more about these differences later. Now, it is time to get the first taste of UMAP, and we will immediately start with a challenging dataset:
>>> tps.shape(957919, 119)
The Kaggle TPS September dataset contains ~1M rows and ~120 features with a binary target. They are all numerical, and we are pretty helpless in performing proper EDA on this dataset. Our options are limited to only printing summary statistics and plotting histograms of each feature.
Let's see what UMAP can do for us. Before using it, we will sample the dataset to avoid overplotting and fill in the missing values:
Here, the target represents whether or not a client claims their insurance.
After installing and importing UMAP, we initialize the manifold algorithm and fit it to X, y in the familiar Sklearn fit/transform pattern:
>>> X_reduced.shape(100000, 2)
By default, UMAP projects the data into two components (2D). Let's create a scatterplot colored by the target class:
>>> plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, s=0.5);
Even though it is fun to look at, the plot does not show any clear patterns. It is because we didn't scale the features before fitting UMAP. The algorithm uses distance metrics to group similar data points, and features with higher scales bias such calculations.
So, we will choose Quantile Transformer to scale the features based on their quantiles and median. This scaling method suits the dataset better since it contains many skewed and bimodal features:
# Plot the resultsplt.scatter(X_reduced_2[:, 0], X_reduced_2[:, 1], c=y, s=0.5);
Now, we are talking! UMAP managed to capture the hidden distinction between the target classes perfectly. We can also see some outliers (the dot around the yellow blob). The dataset was not so challenging after all.
But, this plot is in no way close to what I have shown you. It is still overplotted to see structural patterns within each cluster. To take this to the next level, we will use the default UMAP visualization package with many more features. And we will need a better dataset.
This section will analyze the Kaggle TPS May competition data that categorizes ~200k eCommerce listings based on ~75 numeric qualities. Let's import it and take a quick look:
The target contains nine classes.
As before, we will scale all features, but this time with a straightforward log transform. Then, we fit the UMAP manifold:
After the fit is done, we will import the umap.plot package (installed separately) and plot a point cloud:
Doesn't it resemble a nebula from space? We can distinctly see that Class 8 dominates the space and is clustered around the center. Class 6 is also clearly distinguished from the rest. We see half a circle of mixed data points around class 8. Regarding the singleton data points, they may be classified as outliers.
A note on visualization above — we are simply passing the fitted manifold (not transformed data!) to the points function and specifying the labels for color encoding. I have also chosen the fire as a dark theme.
You can also create connectivity plots with umap.plot.connectivity for diagnostics purposes and to better understand the manifold structure. Do note that creating these plots is time-consuming and computation/memory-heavy.
You can learn more about UMAP visualizations from this section of the documentation.
The underlying reduction algorithm has many parameters that can significantly impact the manifold and hence, the visuals. The four most important ones are:
n_components
n_neighbors
min_dist
metric
As you might have guessed, n_components controls the number of dimensions after the projection. The default is 2 for its ease of visualization. However, for datasets with more than 100 features, 2D may not be enough to preserve the underlying topological structure of the data fully. I recommend trying values between 2-20 at steps of 5 and evaluate different baseline models to see the change in accuracy.
Next, we have n_neighbors. It controls the area of the local neighborhood UMAP looks at for each sample when building the manifold. Smaller values narrow the focus to local structure, taking into account peculiarities and small patterns, potentially losing the big picture.
Higher values to n_neighbors give more flexibility and allows UMAP to focus on a broader "view" of the data in the corresponding dimension. This, of course, comes at the cost of losing the finer details of the structure. The default value for this parameter is 15.
Another critical parameter is min_dist which controls the literal distance between data points. You can tweak the default value of 0.1 to control the tightness of distinct point clouds. Lower values will result in clumpier embeddings, allowing you to see individual clusters more easily. This may be useful during clustering. In contrast, values close to 1 give points more breathing room and enable you to see the broader topological structure.
metric represents the formula to calculate the distance between points. The default is euclidean but you can choose among many others, including manhattan, minkowski and chebyshev.
First consideration while using UMAP is the RAM consumption. Under the hood, UMAP consumes a lot of memory, especially during fitting and creating diagrams like connectivity plots. I suggest running UMAP on a machine with at least 16GB of RAM.
For example, even the 200k-row dataset in the plotting section consumed ~18GB of RAM when creating the connectivity plot. The documentation suggests setting low_memory to True as a possible fix. Additionally, I recommend reducing the memory usage of the dataset by casting each column to the smallest subtype possible using NumPy. I have discussed dealing with out-of-memory issues at length in a previous article:
towardsdatascience.com
Also, don't forget to transform/scale numerical features as they tend to have different scales by default. I suggest QuantileTransformer for crazy distributions like bimodals, trimodals, etc. PowerTransformer works best for skewed features. Whichever transformer you choose, the goal is always to make features as normally distributed as possible.
Today, we have covered the basics of UMAP and learned only a thin slice of what it can do. For further reading, I suggest checking out the documentation of the package. There, you will see different use cases of UMAP and how it is used by tech giants like Google in various projects.
There are also dedicated sections for comparing UMAP to other dimensionality reduction algorithms. For a math enthusiast, you can also read how UMAP works and proofs of its formulas. Thank you for reading! | [
{
"code": null,
"e": 453,
"s": 172,
"text": "No matter how powerful machine learning models are, they can't quite beat the feeling you get during those \"Aha!\" moments of exploring data through rich visuals. But, there are so many histograms, scatterplots, heatmaps you can create before you say, \"... |
How to store usernames and passwords safely in MySQL database? | To store username and passwords safely in MySQL database, we can use MD5().
Let us see an example. First, we will create a table. The CREATE command is used to create a table.
mysql> create table UserNameAndPasswordDemo
- > (
- > U_Id int(10) unsigned NOT NULL AUTO_INCREMENT,
- > UserId varchar(255) DEFAULT NULL,
- > UserPassword varchar(255) DEFAULT NULL,
- > primary key(U_Id),
- > UNIQUE KEY `UserId` (`UserId`)
- > );
Query OK, 0 rows affected (0.61 sec)
Inserting records and safely storing passwords with the help of MD5().
mysql> INSERT INTO UserNameAndPasswordDemo(UserId, UserPassword) VALUES ('John@gg.com', MD5('john123'));
Query OK, 1 row affected (0.17 sec)
mysql> INSERT INTO UserNameAndPasswordDemo(UserId, UserPassword) VALUES (MD5('Carol@gg.com'), MD5('123Carol'));
Query OK, 1 row affected (0.14 sec)
Now, we will implement the SELECT statement to display the records, including password in MD5. Here, we are only displaying records for UserId 'John@gg.com'.
mysql> SELECT *from UserNameAndPasswordDemo where UserId='John@gg.com';
The following is the output.
+------+-------------+----------------------------------+
| U_Id | UserId | UserPassword |
+------+-------------+----------------------------------+
| 1 | John@gg.com | 6e0b7076126a29d5dfcbd54835387b7b |
+------+-------------+----------------------------------+
1 row in set (0.00 sec)
To display all records.
mysql> SELECT *from UserNameAndPasswordDemo;
The following is the output wherein we have saved username and password using MD5 −
+------+----------------------------------+----------------------------------+
| U_Id | UserId | UserPassword |
+------+----------------------------------+----------------------------------+
| 1 | John@gg.com | 6e0b7076126a29d5dfcbd54835387b7b |
| 2 | 5f565a3d794f85e5db4f3bb7b5811a25 | f1d2fb85f7d6ce7428b9b3fd569be42b |
+------+----------------------------------+----------------------------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "To store username and passwords safely in MySQL database, we can use MD5()."
},
{
"code": null,
"e": 1238,
"s": 1138,
"text": "Let us see an example. First, we will create a table. The CREATE command is used to create a table."
},
... |
Python | Pandas DatetimeIndex.dayofyear - GeeksforGeeks | 24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.dayofyear attribute outputs the ordinal value of the day of the year for each entries of the DatetimeIndex object.
Syntax: DatetimeIndex.dayofyear
Return: Index object
Example #1: Use DatetimeIndex.dayofyear attribute to find the ordinal value of the day of the year for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'W' represents Weekly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='W', periods = 3, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)
Output :
Now we want to find ordinal value of day for each entries in the DatetimeIndex object.
# find the ordinal value of the day # for each entries present in the objectdidx.dayofyear
Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the days present in each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.dayofyear attribute to find the ordinal value of the day of the year for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents Monthly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='M', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)
Output :Now we want to find ordinal value of day for each entries in the DatetimeIndex object.
# find the ordinal value of the day # for each entries present in the objectdidx.dayofyear
Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the days present in each entry of the DatetimeIndex object.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 24115,
"s": 23901,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages a... |
Plot data from CSV file with Matplotlib | To extract CSV file for specific columns to list in python, we can use Pandas read_csv() method.
Make a list of columns that have to be extracted.
Use read_csv() method to extract the CSV file data into a data frame.
Print the exracted data.
Plot the data frame using plot() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ["Name", "Marks"]
df = pd.read_csv("input.csv", usecols=columns)
print("Contents in csv file:\n", df)
plt.plot(df.Name, df.Marks)
plt.show() | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To extract CSV file for specific columns to list in python, we can use Pandas read_csv() method."
},
{
"code": null,
"e": 1209,
"s": 1159,
"text": "Make a list of columns that have to be extracted."
},
{
"code": null,
"e"... |
How to generate random samples rounded to 4 decimal places in R? | Random samples can be generated in many ways such as using discrete and continuous distributions, using integer vectors, using numerical vectors, using character vectors and/or factor vectors, also with columns of a data set. If we have the sample that is continuous in nature then the values are likely to contain many values after decimal point and we can limit those values to 4 or use any other limit using round function.
Live Demo
x1<-round(rnorm(10),4)
x1
[1] 0.1667 -0.5536 -0.2748 -0.1064 -0.7740 0.0009 0.3966 -0.2256 -0.4090
[10] 0.4069
Live Demo
x2<-round(rnorm(50,545,18.5),4)
x2
[1] 534.2164 562.2330 508.1712 544.9145 568.2658 566.7066 520.1372 555.8063
[9] 490.2302 530.0890 550.1564 552.7664 512.8081 539.7952 536.8150 527.6695
[17] 543.5097 556.8944 528.4357 519.7085 554.9833 541.6425 580.0051 559.1235
[25] 558.1846 549.6800 581.8289 555.0069 560.3540 528.3715 523.2465 526.7506
[33] 513.3090 569.5984 504.2076 565.5712 594.9353 551.5697 550.7176 560.9044
[41] 553.6006 548.2351 571.0769 513.0627 560.5451 529.1586 552.1659 541.0974
[49] 557.9535 535.8345
Live Demo
x3<-round(runif(100,2,10),4)
x3
[1] 3.3254 4.2719 2.5700 6.6529 2.3641 5.7524 3.5321 4.0652 8.7108 9.5321
[11] 4.8742 2.6012 5.9765 4.1423 6.1051 2.3037 3.0290 2.2835 4.3078 6.9569
[21] 3.0007 9.8222 7.3561 7.8823 6.9002 9.8261 3.9888 9.4723 7.6115 3.5430
[31] 3.5425 2.5960 6.5738 6.5245 4.6534 5.0535 2.4721 9.9349 3.3694 2.1342
[41] 9.8047 3.2214 4.1357 5.9450 7.5481 9.9704 9.1236 6.6892 4.2183 4.2098
[51] 9.1609 3.3085 3.8390 5.6355 3.2058 3.1597 9.0767 4.7739 3.4916 6.7490
[61] 8.5052 3.1381 4.4015 2.5416 9.0075 8.8939 4.2335 7.5611 4.3264 6.2221
[71] 2.6467 3.4608 3.3156 6.6610 9.0668 7.0933 9.2373 6.7479 6.3007 9.3724
[81] 5.5539 9.2073 3.7334 2.8943 4.1278 6.9277 4.0263 7.8080 3.2616 5.0656
[91] 4.7286 9.8659 4.3485 5.7590 4.8930 5.5345 3.5390 9.2349 2.0937 6.1323
Live Demo
x4<-round(rexp(100,3.5),4)
x4
[1] 0.0671 0.1094 0.0880 0.0271 0.0188 0.0594 0.9127 0.4143 0.2443 0.1643
[11] 0.2951 0.0381 0.1241 0.3050 0.1466 0.3556 0.1066 1.0008 0.0905 0.0861
[21] 0.2225 0.0188 0.8789 0.1757 0.4530 0.0884 0.2754 0.2594 0.2853 0.2232
[31] 0.1717 0.3329 0.5694 0.1007 1.5399 0.3020 0.1537 0.0227 0.3811 0.1305
[41] 0.2021 0.0148 0.1565 0.3016 0.2054 0.0474 0.4245 0.2189 0.0746 0.0540
[51] 0.1479 0.1197 0.0670 0.5775 0.4953 0.9968 0.1305 0.2396 0.1523 0.0392
[61] 0.2877 0.0349 0.1656 0.2726 0.4670 0.2336 0.0932 0.2731 0.3326 0.0030
[71] 0.3336 0.5345 0.1917 0.3915 0.6645 0.0015 0.3518 0.7542 0.0054 0.2730
[81] 0.5271 0.0723 0.0439 0.2569 0.4438 1.0872 0.1163 0.5161 0.0244 0.0762
[91] 0.1537 0.0876 0.2585 0.0544 0.1379 0.3796 0.1431 0.2645 0.5104 0.3769
Live Demo
x5<-round(rexp(100,10),4)
x5
[1] 0.0389 0.0984 0.0092 0.0384 0.1462 0.2182 0.2277 0.0102 0.0589 0.0148
[11] 0.0952 0.1037 0.6899 0.0279 0.0562 0.0555 0.3258 0.0199 0.0649 0.0214
[21] 0.1385 0.0805 0.0707 0.0129 0.0227 0.0688 0.0681 0.4176 0.2576 0.4757
[31] 0.0199 0.1240 0.0096 0.0349 0.0394 0.0025 0.0233 0.0495 0.0408 0.1025
[41] 0.0480 0.2670 0.0988 0.1490 0.0547 0.0152 0.0390 0.0286 0.0113 0.0384
[51] 0.1952 0.0361 0.0834 0.0852 0.0246 0.0099 0.1016 0.0028 0.0340 0.3052
[61] 0.1962 0.1240 0.0688 0.0276 0.0665 0.1007 0.1076 0.0231 0.0344 0.0634
[71] 0.1471 0.0151 0.0515 0.2178 0.1477 0.0004 0.0597 0.1680 0.1433 0.0205
[81] 0.0958 0.1006 0.0436 0.0225 0.2576 0.0816 0.2283 0.0376 0.0981 0.0226
[91] 0.0263 0.0126 0.0322 0.0307 0.1616 0.0353 0.0021 0.0073 0.1099 0.0533
Live Demo
x6<-round(rnorm(100,5,1),4)
x6
[1] 5.6763 6.0442 3.8460 6.9212 5.8802 4.5369 5.7293 5.4419 4.8554 4.8552
[11] 6.3626 3.0416 5.5835 3.3639 3.5631 4.4367 6.1987 6.5645 4.4211 4.5338
[21] 5.1488 2.3234 6.7397 4.6025 4.6126 4.3689 5.3708 6.2197 4.7341 5.7758
[31] 3.7592 6.2968 5.8481 4.9489 4.8234 4.9166 3.5623 4.4833 3.4248 5.2370
[41] 5.0679 6.2172 4.6400 5.7530 6.9294 5.3914 5.2008 3.8987 5.8946 3.6129
[51] 3.6497 5.5797 3.7814 4.9368 4.0392 5.5592 3.1513 5.3439 5.1348 4.6515
[61] 5.3077 4.8295 3.8849 4.8448 3.3433 3.2978 4.0765 7.9617 5.1990 4.1103
[71] 4.5910 4.3942 6.5974 6.1603 4.2415 4.2938 7.0490 4.5537 4.9323 5.6792
[81] 6.3582 4.3443 4.0635 4.3988 7.5974 5.1550 6.2474 4.1624 4.0028 4.1772
[91] 3.7348 5.1781 5.4563 4.9231 6.7859 3.9984 4.8556 4.1362 5.0205 6.1024
Live Demo
x7<-round(rt(100,35),4)
x7
[1] 0.3204 -1.3065 -1.0071 -2.0756 -0.0839 0.7791 -0.0810 -1.5429 0.6007
[10] -0.3293 1.4005 -2.2854 -2.9662 -0.1180 1.0510 -0.0574 -0.5469 -1.1538
[19] -0.0302 0.3048 1.3370 1.3374 2.1286 -1.0568 0.1238 -0.2602 -1.4643
[28] 0.9552 -0.0340 -0.3254 -2.4275 -0.4864 2.8389 -1.0984 -1.0615 -2.2571
[37] -1.7641 -1.0414 -0.8122 -0.9599 1.0389 -2.0130 1.4173 0.6212 -0.2002
[46] 1.0792 0.8220 -0.4070 -0.4462 0.7189 1.7046 0.5914 -0.2832 0.2117
[55] 0.0152 0.9239 0.1632 -0.0780 -1.4047 1.0794 -0.8982 0.9582 -0.2948
[64] 0.3619 1.8029 -1.7045 -0.0908 1.6610 1.1330 -0.9057 1.6303 1.0317
[73] 0.9091 0.7074 0.5091 -0.0232 0.2435 1.4325 0.4925 0.6357 -1.3657
[82] 1.4857 0.5618 0.1661 -0.1686 -0.3427 -1.1928 -1.4164 -0.4323 0.2180
[91] 1.2018 -2.5645 1.5959 0.1095 -0.2138 -0.3220 -0.2515 1.5408 -1.7223
[100] 0.9292
Live Demo
x8<-round(rf(100,2,36),4)
x8
[1] 0.8147 0.0376 0.1377 0.6935 2.3744 1.8458 0.2076 0.7661 2.1681 2.1221
[11] 0.2457 0.2045 2.8954 0.5044 0.3615 0.8056 1.0633 0.6306 1.1108 0.2749
[21] 0.2724 0.0587 1.8507 1.2245 0.7484 0.1565 0.3563 0.9754 1.1266 0.2427
[31] 0.1566 0.5620 1.0601 0.2009 6.3452 0.1189 1.5286 1.0583 1.1904 0.8433
[41] 0.4249 0.0324 0.0383 1.2045 1.7232 2.3048 3.0217 0.2014 0.3035 0.3601
[51] 0.4877 0.1151 0.2056 0.6065 0.9192 0.6845 3.7313 0.0209 1.3406 0.1404
[61] 0.7136 1.3781 0.0560 2.8054 1.3838 3.4458 0.3417 0.1298 1.3320 0.0430
[71] 2.5704 3.4338 0.8516 1.3397 1.5941 3.6932 0.1111 1.1202 1.7724 0.8752
[81] 3.8412 0.2798 0.4708 2.1400 0.8470 0.5233 0.7540 0.2193 0.1412 1.8143
[91] 0.9365 0.3903 2.3025 1.6087 0.2255 0.5314 1.8405 0.2321 0.8266 1.3261
Live Demo
x9<-round(rlnorm(100,5,2),4)
x9
[1] 3663.4697 1177.2276 11.4535 815.7052 3066.3002 63.3265
[7] 6.8847 35.7552 236.8196 79.1767 689.2404 5.5008
[13] 344.2535 1138.8724 287.1132 49.1381 489.8662 158.1743
[19] 109.4748 355.1509 855.8181 191.1866 9.0679 314.2612
[25] 1008.5422 17.5288 20.0675 37.5216 2466.2132 1104.7948
[31] 570.9207 11.2588 3.1528 481.2571 354.3538 4.6479
[37] 928.3763 743.7015 1054.3399 253.3067 20.7045 352.9785
[43] 1849.3159 167.5804 0.9107 2489.4271 12994.5896 1119.0242
[49] 24.1053 1861.5244 754.3061 28.5280 24.2137 57.0343
[55] 203.8550 245.9501 582.4504 7571.2720 305.8121 3.3545
[61] 10962.3609 35055.4310 345.9599 50.3923 815.9937 0.1470
[67] 142.1961 310.8576 632.7251 929.2929 61.2483 166.1665
[73] 238.8496 5.8300 252.5437 93.1759 4494.1969 40.7933
[79] 2271.2802 743.6349 387.8769 2.0409 65.9566 64.4320
[85] 66.8955 1093.2168 24.1452 65.7903 31.2941 9.4564
[91] 5453.9356 27.8865 72.1684 216.2117 46.6497 72.9932
[97] 12.9700 217.6623 2230.6189 329.4752 | [
{
"code": null,
"e": 1489,
"s": 1062,
"text": "Random samples can be generated in many ways such as using discrete and continuous distributions, using integer vectors, using numerical vectors, using character vectors and/or factor vectors, also with columns of a data set. If we have the sample that ... |
Coreference Resolution in Python. Neural-network-based approach | Towards Data Science | In human language, endophoric awareness plays a key part in comprehension (decoding) skills, writing (encoding) skills, and general linguistic awareness. Endophora consists of anaphoric, cataphoric, and self-references within a text.
Anaphoric references occur when a word refers back to other ideas in the text for its meaning.
David went to the concert. He said it was an amazing experience.He refers to David.It refers to the concert.
Cataphoric references occur when a word refers to ideas later in the text.
Every time I visit her, my grandma bakes me cookies.Her refers to my grandma.
Coreference resolution is the NLP (Natural Language Processing) equivalent of endophoric awareness used in information retrieval systems, conversational agents, and virtual assistants like Amazon’s Alexa. It is the task of clustering mentions in text that refer to the same underlying entities.
For example:
“I”, “my”, and “she” belong to the same cluster and “Joe” and “he” belong to the same cluster.
Algorithms which resolve coreferences commonly look for the nearest preceding mention that is compatible with the referring expression. Instead of using rule-based dependency parse trees, neural networks can also be trained which take into account word embeddings and distance between mentions as features.
NeuralCoref is an open source python packgage integrated in SpaCy’s NLP pipeline. You can install NeuralCoref with pip:
pip install neuralcoref
or from sources with dependencies in a virtual environment:
SpaCy and NeuralCoref can be used to create production-ready NLP applications with little fine-tuning. For example, let's parse through the historical United States v. Nixon case to retrieve facts referencing the former U.S. President Richard Nixon:
Output:Fact count: 108
Following indictment alleging violation of federal statutes by certain staff members of the White House and political supporters of the President, the Special Prosecutor filed a motion under Fed.Proc. 17(c) for a subpoena for the production before trial of certain tapes and documents relating to precisely identified conversations and meetings between the President and others.the President, claiming executive privilege, filed a motion to quash the subpoena.
Following indictment alleging violation of federal statutes by certain staff members of the White House and political supporters of the President, the Special Prosecutor filed a motion under Fed.
Proc. 17(c) for a subpoena for the production before trial of certain tapes and documents relating to precisely identified conversations and meetings between the President and others.
the President, claiming executive privilege, filed a motion to quash the subpoena.
The script scrapes the webpage with Urllib and parses HTML using Beautiful Soup. We load the text into a SpaCy model of our choice; you can download pre-trained SpaCy models from the terminal as shown below:
python -m spacy download en_core_web_lg
The SpaCy pipeline assigns word vectors, context-specific token vectors, part-of-speech tags, dependency parsing, and named entities. by extending the SpaCy’s pipeline of annotations you can resolve coreferences.
You can retrieve a list of all the clusters of corefering mentions using the doc._.coref_clustersattribute and replace corefering mentions with the main mentions in each cluster by using thedoc._.coref_resolvedattribute.
SpaCy has a built-in unsupervised sentence tokenizer to split the text into a list of sentences. Use lowercased lemmatized sentences for approximate string searching to the topic of your interest (e.g. President). | [
{
"code": null,
"e": 406,
"s": 172,
"text": "In human language, endophoric awareness plays a key part in comprehension (decoding) skills, writing (encoding) skills, and general linguistic awareness. Endophora consists of anaphoric, cataphoric, and self-references within a text."
},
{
"code":... |
How can we simulate the MySQL MINUS query? | Since we cannot use the MINUS query in MySQL, we will use JOIN to simulate the MINUS query. It can be understood with the help of the following example −
In this example, we are two tables namely Student_detail and Student_info having the following data −
mysql> Select * from Student_detail;
+-----------+---------+------------+------------+
| studentid | Name | Address | Subject |
+-----------+---------+------------+------------+
| 101 | YashPal | Amritsar | History |
| 105 | Gaurav | Chandigarh | Literature |
| 130 | Ram | Jhansi | Computers |
| 132 | Shyam | Chandigarh | Economics |
| 133 | Mohan | Delhi | Computers |
| 150 | Rajesh | Jaipur | Yoga |
| 160 | Pradeep | Kochi | Hindi |
+-----------+---------+------------+------------+
7 rows in set (0.00 sec)
mysql> Select * from Student_info;
+-----------+-----------+------------+-------------+
| studentid | Name | Address | Subject |
+-----------+-----------+------------+-------------+
| 101 | YashPal | Amritsar | History |
| 105 | Gaurav | Chandigarh | Literature |
| 130 | Ram | Jhansi | Computers |
| 132 | Shyam | Chandigarh | Economics |
| 133 | Mohan | Delhi | Computers |
| 165 | Abhimanyu | Calcutta | Electronics |
+-----------+-----------+------------+-------------+
6 rows in set (0.00 sec)
Now, the following query using JOINS will simulate MINUS to return the ‘studentid’ values in student_info but not in the Student_detail table.
mysql> SELECT studentid from student_info LEFT JOIN Student_detail USING(studentid) WHERE student_detail.studentid IS NULL;
+-----------+
| studentid |
+-----------+
| 165 |
+-----------+
1 row in set (0.07 sec)
Now, the following query will give us the opposite result of the above query i.e. it will return the ‘studentid’ values in student_detail but not in Student_info table.
mysql> SELECT studentid from student_detail LEFT JOIN Student_info USING(studentid) WHERE student_info.studentid IS NULL;
+-----------+
| studentid |
+-----------+
| 150 |
| 160 |
+-----------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "Since we cannot use the MINUS query in MySQL, we will use JOIN to simulate the MINUS query. It can be understood with the help of the following example −"
},
{
"code": null,
"e": 1318,
"s": 1216,
"text": "In this example, we are two ... |
Define integer literals as octal values in Java | Literals with a leading zero are octal literals. Any number prefixed with a 0 is considered octal. Octal numbers can only use digits 0-7, just like decimal can use 0-9, and binary can use 0-1.
To define integer literals as octal value in Java is effortless. Here is the declaration and initialization.
int myOct = 023;
Live Demo
public class Demo {
public static void main(String []args) {
int myOct = 023;
System.out.println(myOct);
}
}
19
Let us see another example.
Live Demo
public class Demo {
public static void main(String []args) {
int myOct = 010;
System.out.println(myOct);
}
}
8 | [
{
"code": null,
"e": 1255,
"s": 1062,
"text": "Literals with a leading zero are octal literals. Any number prefixed with a 0 is considered octal. Octal numbers can only use digits 0-7, just like decimal can use 0-9, and binary can use 0-1."
},
{
"code": null,
"e": 1364,
"s": 1255,
... |
D3.js dsv() Function - GeeksforGeeks | 17 Aug, 2020
The d3.dsv() function in D3.js is a part of the request API that returns a request for the file of type DSV. The mime type is text/DSV. An optional row conversion function can be specified to map and filter row objects.
Syntax:
d3.dsv(delimiter, inputfile, function);
Parameters: This function accepts three parameters as mentioned above and described below:
delimiter: It is the delimited such as “,” or “-” and so on that separates the columns.
inputfile: It is the location of the input file.
function: It is the function that is user-defined which performs certain actions to deal with the data.
Below given are a few examples of the function given above.
Note: Please create and save a file name sample.dsv before going with the code.
Example1:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <title>D3.js dsv() Function</title> </head> <style></style> <body> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-dsv.v1.min.js"> </script> <script src="https://d3js.org/d3-fetch.v1.min.js"> </script> <script> d3.dsv(",", "sample.dsv", (data) => { console.log(data); }); </script> </body></html>
Output:
Example 2: When the delimiter is ” ” (space)
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <title>D3.js dsv() Function</title> </head> <style></style> <body> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-dsv.v1.min.js"> </script> <script src="https://d3js.org/d3-fetch.v1.min.js"> </script> <script> d3.dsv(" ", "sample.dsv", (data) => { console.log(data.year, " ", data.population); }); </script> </body></html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24272,
"s": 24244,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 24492,
"s": 24272,
"text": "The d3.dsv() function in D3.js is a part of the request API that returns a request for the file of type DSV. The mime type is text/DSV. An optional row conversion ... |
Tryit Editor v3.7 | HTML Input types
Tryit: dates with max and min values | [
{
"code": null,
"e": 27,
"s": 10,
"text": "HTML Input types"
}
] |
Get month and Year from Date in Pandas - Python - GeeksforGeeks | 26 Nov, 2021
Pandas is one of the most powerful library in Python which is used for high performance and speed of calculation. It is basically an open-source BSD-licensed Python library. Commonly it is used for exploratory data analysis, machine learning, data visualization in data science, and many more. It has very dynamic and easy to understand syntax which makes users jobs easier and is a boost for developers’ innovations (as pandas is a open-source library).
Let us now start with installing pandas. Following are the commands for installing pandas on Linux, windows or mac directly use:
pip install pandas
For installing pandas on anaconda environment use:
conda install pandas
Lets now load pandas library in our programming environment.
import pandas as pd
Coming to accessing month and date in pandas, this is the part of exploratory data analysis. Suppose we want to access only the month, day, or year from date, we generally use pandas.
Method 1: Use DatetimeIndex.month attribute to find the month and use DatetimeIndex.year attribute to find the year present in the Date.
df['year'] = pd.DatetimeIndex(df['Date Attribute']).year
df['month'] = pd.DatetimeIndex(df['Date Attribute']).month
Here ‘df’ is the object of the dataframe of pandas, pandas is callable as ‘pd’ (as imported), ‘DatatimeIndex()’ is a function in pandas which is used to refer to the date attribute of your dataset, ‘Date Attribute’ is the date column in your data-set (It can be anything ans varies from one data-set to other), ‘year’ and ‘month’ are the attributes for referring to the year and month respectively.Let’s now look at an example:
Code :
Python3
# import pandas libraryimport pandas as pd # dictionary of string key and list valueraw_data = {'name': ['Rutuja', 'Neeraj', 'Renna', 'Pratik'], 'age': [20, 19, 22, 21], 'favorite_color': ['blue', 'red', 'yellow', "green"], 'grade': [88, 92, 95, 70], 'birth_date': ['01-02-2000', '08-05-1997', '04-28-1996', '12-16-1995']} # create a dataframe objectdf = pd.DataFrame(raw_data, index = ['Rutuja', 'Neeraj', 'Renna', 'Pratik']) # get year from the corresponding# birth_date column valuedf['year'] = pd.DatetimeIndex(df['birth_date']).year # get month from the corresponding# birth_date column valuedf['month'] = pd.DatetimeIndex(df['birth_date']).month # Show the dataframe# by default 5 rows from topdf.head()
Output:
So in the output it is clearly seen that the last two columns of the data-set are appended and we have separately stored the month and date using pandas.
Method 2: Use datetime.month attribute to find the month and use datetime.year attribute to find the year present in the Date .
df['year'] = df['Date Attribute'].dt.year
df['month'] = df['Date Attribute'].dt.month
Here ‘df’ is the object of the dataframe of pandas, pandas is callable as ‘pd’ (as imported), datetime is callable as ‘dt’ (as imported). ‘Date Attribute’ is the date column in your data-set (It can be anything ans varies from one data-set to other), ‘year’ and ‘month’ are the attributes for referring to the year and month respectively.Let’s now look at example:
Code:
Python3
# import required libraryimport pandas as pdimport datetime as dt # dictionary of string as key# and list as a valueraw_data = {'Leaders': ['Mahatma Gandhi', 'Jawaharlal Nehru', 'Atal Bihari Vajpayee', 'Rabindranath Tagore'], 'birth_date': ['10-02-1869', '11-14-1889', '12-25-1924', '05-07-1861']} # create a dataframe objectdf = pd.DataFrame(raw_data, index = ['Mahatma Gandhi', 'Jawaharlal Nehru', 'Atal Bihari Vajpayee', 'Rabindranath Tagore']) # get a year from corresponding# birth_date column valuedf['year'] = df['birth_date'].dt.year # get a month from corresponding# birth_date column valuedf['month'] = df['birth_date'].dt.month # show the dataframe# by default first 5 rows# from topdf.head()
Output:
So in the output, it is clearly seen that the last two columns of the data-set are appended and we have separately stored the month and date using pandas.
sumitgumber28
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 24925,
"s": 24897,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 25381,
"s": 24925,
"text": "Pandas is one of the most powerful library in Python which is used for high performance and speed of calculation. It is basically an open-source BSD-licensed Pytho... |
Pie & Donut Charts with Plotly. Why & How | by Darío Weitz | Towards Data Science | WHY: Pie Charts (PCs) are used to display parts of a whole of mutually exclusive and not overlapping categories. The conceptual idea is not to make a comparison between the categories but to show the percentage or proportion of each category with respect to the total. This type of chart should not be used for Correlation, Deviation or Distribution analysis.
HOW: PCs are circular charts divided into slices-like sectors. The full circle represents the whole (100%) while the slices represent the parts. Each of the parts must be correctly labeled and preferably include the numerical value corresponding to the percentage of the sector. Slices (segments, sectors, wedges) cannot overlap (mutually exclusive). They must consistently add up to 100%.
PCs encode the corresponding numerical values with two visual attributes: 1.-length of each slice along the perimeter; 2.-area of each slice.
Storytelling: PCs are widely used in finance, business, journalism, and education to show percentages or proportions among a large variety of categories including budgets, sales, rate of unemployment, segments of a population, academic performances, or answers to a survey. They express a message of whole-part relationships through the area of each slice and/or the length of each slice along the pie’s perimeter.
Their use as a Data Visualization technique is the subject of deep controversy: on the one hand, those visual attributes are not easy to decode; on the other hand, audiences are very familiar with the simple aesthetics of the pie charts. What is beyond dispute is that they are hard to read when there are too many slices.
Some Warnings
· Always check that the whole is 100%, that the whole makes clear sense to the audience, and that the categories are mutually exclusive. For example, these requirements are not always verified in survey results.
· Always include annotations and percentages to describe the content.
· PCs should not be used for accurate comparisons, when differences between categories are minor, or for trends or patterns.
· Try to not use more than six or seven slices. They are not only hard to read but also there are too many legends.
· If you have numerous small sectors that are difficult to read, try to combine them into a single sector with a legend appropriate to the new situation and with a neutral color.
· Avoid all 3D effects. Although they are aesthetically pleasing, they introduce distortion and hinders seriously the interpretation of the message.
Alternative 1: Donut Charts (Doughnut Charts)
They are absolutely equivalents to pie charts (they display parts of a whole of mutually exclusive and not overlapping categories), with the only difference being a blank space (a hole) in the center of the chart where some kind of additional information is indicated to enhance the storytelling.
Now it is not possible to make a comparison of areas, but the numerical values of the sectors are encoded only by means of arc lengths along the perimeter of the circle.
Its use is justified when the information in the center allows gaining space and thus reducing the total space generated by the chart. For example, the legends corresponding to each sector can be indicated in the hole of the donut. Of course, this gain in space must outweigh the new difficulty generated by having fewer visual attributes.
Alternative 2: Segment Separation
The message can be reinforced by separating one or a few segments from the original pie. You can put the entire pie apart, or just highlight an individual slice depending on the narrative. Be aware that this visual separation produces a distortion in the chart that may make the message difficult to interpret.
Pie Charts & Alternatives with Plotly
Plotly, a technical computing company located in Montreal, Canada, launched in 2019 Plotly Express (PE), a new high-level Python visualization library. PE includes functions to plot standard charts with a single function call.
Plotly also provides a module named plotly.graph_objects which contains a hierarchy of Python classes. Figure, a primary class, has a data attribute that allows to create and display graphical figures in a relatively quick and easy way.
Our data refer to Population Economically Active in the Argentine Republic in 2017. We are going to show with a pie chart the percentages corresponding to four groups of the economically active population according to the type of pressure on the labor market. These four groups are named: 1.-’employed’; 2.-’unemployed’; 3.-’underemployed job seekers’; 4.-’underemployed non-job seekers’.
For the pie charts in this article, the Plotly Express function is px.pie, and the corresponding parameters are: data_frame, the first parameter, corresponds to the sectors of the pie; values sets numerical values associated to sectors; names sets the labels for the sectors; color assign hues to sectors.
This is the code for the pie chart in Figure 1 (above):
import plotly.express as pxlabels = ['employed', 'unemployed', 'underemployed job seekers', 'underemployed non-job seekers']values = [72.8, 7.2, 14.7, 5.3]fig1 = px.pie(labels, values = values, names = labels)fig1.show()
We considered it convenient to change the default colors for others that would improve the message. For such purpose, we used the parameter color_discrete_map and we obtained Figure number 2.
fig2 = px.pie(labels, values = values, names = labels, color = labels, color_discrete_map = {'employed':'blue', 'unemployed': 'red', 'underemployed job seekers':'lightblue', 'underemployed non-job seekers':'orange' })fig2.show()
Next, we add a title and a hoover tooltip (Fig.3):
fig3 = px.pie(labels, values = values, names = labels, color = labels, color_discrete_map = {'employed':'blue', 'unemployed': 'red', 'underemployed job seekers':'lightblue', 'underemployed non-job seekers':'orange' })fig3.update_traces(title = 'Population Economically Active', title_font = dict(size=25,family='Verdana', color='darkred'), hoverinfo='label+percent', textinfo='percent', textfont_size=20)fig3.show()
Let’s see how the message is conveyed by a donut chart. We included the hole parameter to set the fraction of the radius to cut out of the pie.
fig4 = px.pie(labels, values = values, hole = 0.4, names = labels, color = labels, title = 'Population Economically Active', color_discrete_map = {'employed':'blue', 'unemployed': 'red', 'underemployed job seekers':'lightblue', 'underemployed non-job seekers':'orange' })fig4.update_traces( title_font = dict(size=25,family='Verdana', color='darkred'), hoverinfo='label+percent', textinfo='percent', textfont_size=20)fig4.show()
We are interested in what the chart looks like with a separate segment, but there is a drawback: Plotly Express does not provide a parameter for that task. Therefore, we have to resort to plotly.graph_objects.
For the following donut charts in this article, the plotly.graph_objects function is data = go.Pie() and the corresponding parameters are: values; labels; hole; marker_colors.
import plotly.graph_objects as gocolors = ['blue','red','lightblue','orange']fig5 = go.Figure(data = go.Pie(values = values, labels = labels, hole = 0.4, title = 'Population Economically Active', marker_colors = colors ))fig5.update_traces( title_font=dict(size=25,family='Verdana', color='darkred'), hoverinfo='label+percent', textinfo='percent', textfont_size=20, )fig5.show()
As can be seen, we have a problem: the title has appeared in the hole. To solve it, we added an annotation in the hole.
fig6 = go.Figure(data = go.Pie(values = values, labels = labels, hole = 0.4, marker_colors = colors ))fig6.update_traces(hoverinfo='label+percent', textinfo='percent', textfont_size=20)fig6.update_layout( title_text = 'Population Economically Active', title_font = dict(size=25,family='Verdana', color='darkred'))fig6.add_annotation(x= 0.5, y = 0.5, text = 'Year 2017', font = dict(size=20,family='Verdana', color='black'), showarrow = False)fig6.show()
Let’s see if the message is reinforced by separating one segment from the original chart. We set values for pull, a list to define which slices are pull out from the center and to what extent.
fig7 = go.Figure(data = go.Pie(values = values, labels = labels, hole = 0.4, pull = [0,0.25,0,0], marker_colors = colors ))fig7.update_traces(hoverinfo='label+percent', textinfo='percent', textfont_size=20)fig7.update_layout( title_text = 'Population Economically Active', title_font = dict(size=25,family='Verdana', color='darkred'))fig7.add_annotation(x= 0.5, y = 0.5, text = 'Year 2017', font = dict(size=20,family='Verdana', color='black'), showarrow = False)fig7.show()
We leave it up to you to decide which chart (Fig.4, Fig.6, or Fig.7) provides the best storytelling.
If you find this article of interest, please read my previous (https://medium.com/@dar.wtz):
Lollipop & Dumbbell Charts with Plotly, Mean or Median?
towardsdatascience.com
Slope Charts, Why & How, Storytelling with Slopes | [
{
"code": null,
"e": 532,
"s": 172,
"text": "WHY: Pie Charts (PCs) are used to display parts of a whole of mutually exclusive and not overlapping categories. The conceptual idea is not to make a comparison between the categories but to show the percentage or proportion of each category with respect ... |
Flutter - Accessing REST API | Flutter provides http package to consume HTTP resources. http is a Future-based library and uses await and async features. It provides many high level methods and simplifies the development of REST based mobile applications.
http package provides a high level class and http to do web requests.
http class provides functionality to perform all types of HTTP requests.
http class provides functionality to perform all types of HTTP requests.
http methods accept a url, and additional information through Dart Map (post data, additional headers, etc.,). It requests the server and collects the response back in async/await pattern. For example, the below code reads the data from the specified url and print it in the console.
http methods accept a url, and additional information through Dart Map (post data, additional headers, etc.,). It requests the server and collects the response back in async/await pattern. For example, the below code reads the data from the specified url and print it in the console.
print(await http.read('https://flutter.dev/'));
Some of the core methods are as follows −
read − Request the specified url through GET method and return back the response as Future<String>
read − Request the specified url through GET method and return back the response as Future<String>
get − Request the specified url through GET method and return back the response as Future<Response>. Response is a class holding the response information.
get − Request the specified url through GET method and return back the response as Future<Response>. Response is a class holding the response information.
post − Request the specified url through POST method by posting the supplied data and return back the response as Future<Response>
post − Request the specified url through POST method by posting the supplied data and return back the response as Future<Response>
put − Request the specified url through PUT method and return back the response as Future <Response>
put − Request the specified url through PUT method and return back the response as Future <Response>
head − Request the specified url through HEAD method and return back the response as Future<Response>
head − Request the specified url through HEAD method and return back the response as Future<Response>
delete − Request the specified url through DELETE method and return back the response as Future<Response>
delete − Request the specified url through DELETE method and return back the response as Future<Response>
http also provides a more standard HTTP client class, client. client supports persistent connection. It will be useful when a lot of request to be made to a particular server. It needs to be closed properly using close method. Otherwise, it is similar to http class. The sample code is as follows −
var client = new http.Client();
try {
print(await client.get('https://flutter.dev/'));
}
finally {
client.close();
}
Let us create a simple application to get product data from a web server and then show the products using ListView.
Create a new Flutter application in Android studio, product_rest_app.
Create a new Flutter application in Android studio, product_rest_app.
Replace the default startup code (main.dart) with our product_nav_app code.
Replace the default startup code (main.dart) with our product_nav_app code.
Copy the assets folder from product_nav_app to product_rest_app and add assets inside the pubspec.yaml file.
Copy the assets folder from product_nav_app to product_rest_app and add assets inside the pubspec.yaml file.
flutter:
assets:
- assets/appimages/floppy.png
- assets/appimages/iphone.png
- assets/appimages/laptop.png
- assets/appimages/pendrive.png
- assets/appimages/pixel.png
- assets/appimages/tablet.png
Configure http package in the pubspec.yaml file as shown below −
Configure http package in the pubspec.yaml file as shown below −
dependencies:
http: ^0.12.0+2
Here, we will use the latest version of the http package. Android studio will send a package alert that the pubspec.yaml is updated.
Here, we will use the latest version of the http package. Android studio will send a package alert that the pubspec.yaml is updated.
Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application.
Click Get dependencies option. Android studio will get the package from Internet and properly configure it for the application.
Import http package in the main.dart file −
Import http package in the main.dart file −
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
Create a new JSON file, products.json with product information as shown below −
Create a new JSON file, products.json with product information as shown below −
[
{
"name": "iPhone",
"description": "iPhone is the stylist phone ever",
"price": 1000,
"image": "iphone.png"
},
{
"name": "Pixel",
"description": "Pixel is the most feature phone ever",
"price": 800,
"image": "pixel.png"
},
{
"name": "Laptop",
"description": "Laptop is most productive development tool",
"price": 2000,
"image": "laptop.png"
},
{
"name": "Tablet",
"description": "Tablet is the most useful device ever for meeting",
"price": 1500,
"image": "tablet.png"
},
{
"name": "Pendrive",
"description": "Pendrive is useful storage medium",
"price": 100,
"image": "pendrive.png"
},
{
"name": "Floppy Drive",
"description": "Floppy drive is useful rescue storage medium",
"price": 20,
"image": "floppy.png"
}
]
Create a new folder, JSONWebServer and place the JSON file, products.json.
Create a new folder, JSONWebServer and place the JSON file, products.json.
Run any web server with JSONWebServer as its root directory and get its web path. For example, http://192.168.184.1:8000/products.json. We can use any web server like apache, nginx etc.,
Run any web server with JSONWebServer as its root directory and get its web path. For example, http://192.168.184.1:8000/products.json. We can use any web server like apache, nginx etc.,
The easiest way is to install node based http-server application. Follow the steps given below to install and run http- server application
The easiest way is to install node based http-server application. Follow the steps given below to install and run http- server application
Install Nodejs application (nodejs.org)
Install Nodejs application (nodejs.org)
Go to JSONWebServer folder.
Go to JSONWebServer folder.
cd /path/to/JSONWebServer
Install http-server package using npm.
Install http-server package using npm.
npm install -g http-server
Now, run the server.
Now, run the server.
http-server . -p 8000
Starting up http-server, serving .
Available on:
http://192.168.99.1:8000
http://127.0.0.1:8000
Hit CTRL-C to stop the server
Create a new file, Product.dart in the lib folder and move the Product class into it.
Create a new file, Product.dart in the lib folder and move the Product class into it.
Write a factory constructor in the Product class, Product.fromMap to convert mapped data Map into the Product object. Normally, JSON file will be converted into Dart Map object and then, converted into relevant object (Product).
Write a factory constructor in the Product class, Product.fromMap to convert mapped data Map into the Product object. Normally, JSON file will be converted into Dart Map object and then, converted into relevant object (Product).
factory Product.fromJson(Map<String, dynamic> data) {
return Product(
data['name'],
data['description'],
data['price'],
data['image'],
);
}
The complete code of the Product.dart is as follows −
The complete code of the Product.dart is as follows −
class Product {
final String name;
final String description;
final int price;
final String image;
Product(this.name, this.description, this.price, this.image);
factory Product.fromMap(Map<String, dynamic> json) {
return Product(
json['name'],
json['description'],
json['price'],
json['image'],
);
}
}
Write two methods − parseProducts and fetchProducts - in the main class to fetch and load the product information from web server into the List<Product> object.
Write two methods − parseProducts and fetchProducts - in the main class to fetch and load the product information from web server into the List<Product> object.
List<Product> parseProducts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) =>Product.fromJson(json)).toList();
}
Future<List<Product>> fetchProducts() async {
final response = await http.get('http://192.168.1.2:8000/products.json');
if (response.statusCode == 200) {
return parseProducts(response.body);
} else {
throw Exception('Unable to fetch products from the REST API');
}
}
Note the following points here −
Note the following points here −
Future is used to lazy load the product information. Lazy loading is a concept to defer the execution of the code until it is necessary.
Future is used to lazy load the product information. Lazy loading is a concept to defer the execution of the code until it is necessary.
http.get is used to fetch the data from the Internet.
http.get is used to fetch the data from the Internet.
json.decode is used to decode the JSON data into the Dart Map object. Once JSON data is decoded, it will be converted into List<Product> using fromMap of the Product class.
json.decode is used to decode the JSON data into the Dart Map object. Once JSON data is decoded, it will be converted into List<Product> using fromMap of the Product class.
In MyApp class, add new member variable, products of type Future<Product> and include it in constructor.
In MyApp class, add new member variable, products of type Future<Product> and include it in constructor.
class MyApp extends StatelessWidget {
final Future<List<Product>> products;
MyApp({Key key, this.products}) : super(key: key);
...
In MyHomePage class, add new member variable products of type Future<Product> and include it in constructor. Also, remove items variable and its relevant method, getProducts method call. Placing the products variable in constructor. It will allow to fetch the products from Internet only once when the application is first started.
In MyHomePage class, add new member variable products of type Future<Product> and include it in constructor. Also, remove items variable and its relevant method, getProducts method call. Placing the products variable in constructor. It will allow to fetch the products from Internet only once when the application is first started.
class MyHomePage extends StatelessWidget {
final String title;
final Future<ListList<Product>> products;
MyHomePage({Key key, this.title, this.products}) : super(key: key);
...
Change the home option (MyHomePage) in the build method of MyApp widget to accommodate above changes −
Change the home option (MyHomePage) in the build method of MyApp widget to accommodate above changes −
home: MyHomePage(title: 'Product Navigation demo home page', products: products),
Change the main function to include Future<Product> arguments −
Change the main function to include Future<Product> arguments −
void main() => runApp(MyApp(fetchProduct()));
Create a new widget, ProductBoxList to build the product list in the home page.
Create a new widget, ProductBoxList to build the product list in the home page.
class ProductBoxList extends StatelessWidget {
final List<Product> items;
ProductBoxList({Key key, this.items});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: ProductBox(item: items[index]),
onTap: () {
Navigator.push(
context, MaterialPageRoute(
builder: (context) =gt; ProductPage(item: items[index]),
),
);
},
);
},
);
}
}
Note that we used the same concept used in Navigation application to list the product except it is designed as a separate widget by passing products (object) of type List<Product>.
Finally, modify the MyHomePage widget’s build method to get the product information using Future option instead of normal method call.
Finally, modify the MyHomePage widget’s build method to get the product information using Future option instead of normal method call.
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: FutureBuilder<List<Product>>(
future: products, builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData ? ProductBoxList(items: snapshot.data)
// return the ListView widget :
Center(child: CircularProgressIndicator());
},
),
)
);
}
Here note that we used FutureBuilder widget to render the widget. FutureBuilder will try to fetch the data from it’s future property (of type Future<List<Product>>). If future property returns data, it will render the widget using ProductBoxList, otherwise throws an error.
Here note that we used FutureBuilder widget to render the widget. FutureBuilder will try to fetch the data from it’s future property (of type Future<List<Product>>). If future property returns data, it will render the widget using ProductBoxList, otherwise throws an error.
The complete code of the main.dart is as follows −
The complete code of the main.dart is as follows −
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'Product.dart';
void main() => runApp(MyApp(products: fetchProducts()));
List<Product> parseProducts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromMap(json)).toList();
}
Future<List<Product>> fetchProducts() async {
final response = await http.get('http://192.168.1.2:8000/products.json');
if (response.statusCode == 200) {
return parseProducts(response.body);
} else {
throw Exception('Unable to fetch products from the REST API');
}
}
class MyApp extends StatelessWidget {
final Future<List<Product>> products;
MyApp({Key key, this.products}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Product Navigation demo home page', products: products),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
final Future<List<Product>> products;
MyHomePage({Key key, this.title, this.products}) : super(key: key);
// final items = Product.getProducts();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: Center(
child: FutureBuilder<List<Product>>(
future: products, builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData ? ProductBoxList(items: snapshot.data)
// return the ListView widget :
Center(child: CircularProgressIndicator());
},
),
)
);
}
}
class ProductBoxList extends StatelessWidget {
final List<Product> items;
ProductBoxList({Key key, this.items});
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: ProductBox(item: items[index]),
onTap: () {
Navigator.push(
context, MaterialPageRoute(
builder: (context) => ProductPage(item: items[index]),
),
);
},
);
},
);
}
}
class ProductPage extends StatelessWidget {
ProductPage({Key key, this.item}) : super(key: key);
final Product item;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(this.item.name),),
body: Center(
child: Container(
padding: EdgeInsets.all(0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Image.asset("assets/appimages/" + this.item.image),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.name, style:
TextStyle(fontWeight: FontWeight.bold)),
Text(this.item.description),
Text("Price: " + this.item.price.toString()),
RatingBox(),
],
)
)
)
]
),
),
),
);
}
}
class RatingBox extends StatefulWidget {
@override
_RatingBoxState createState() =>_RatingBoxState();
}
class _RatingBoxState extends State<RatingBox> {
int _rating = 0;
void _setRatingAsOne() {
setState(() {
_rating = 1;
});
}
void _setRatingAsTwo() {
setState(() {
_rating = 2;
});
}
void _setRatingAsThree() {
setState(() {
_rating = 3;
});
}
Widget build(BuildContext context) {
double _size = 20;
print(_rating);
return Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 1
? Icon(Icons.star, ize: _size,)
: Icon(Icons.star_border, size: _size,)
),
color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size,
),
),
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 2
? Icon(Icons.star, size: _size,)
: Icon(Icons.star_border, size: _size, )
),
color: Colors.red[500],
onPressed: _setRatingAsTwo,
iconSize: _size,
),
),
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 3 ?
Icon(Icons.star, size: _size,)
: Icon(Icons.star_border, size: _size,)
),
color: Colors.red[500],
onPressed: _setRatingAsThree,
iconSize: _size,
),
),
],
);
}
}
class ProductBox extends StatelessWidget {
ProductBox({Key key, this.item}) : super(key: key);
final Product item;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2), height: 140,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Image.asset("assets/appimages/" + this.item.image),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.name, style:TextStyle(fontWeight: FontWeight.bold)),
Text(this.item.description),
Text("Price: " + this.item.price.toString()),
RatingBox(),
],
)
)
)
]
),
)
);
}
}
Finally run the application to see the result. It will be same as our Navigation example except the data is from Internet instead of local, static data entered while coding the application.
34 Lectures
4 hours
Sriyank Siddhartha
117 Lectures
10 hours
Frahaan Hussain
27 Lectures
1 hours
Skillbakerystudios
17 Lectures
51 mins
Harsh Kumar Khatri
17 Lectures
1.5 hours
Pramila Rawat
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2443,
"s": 2218,
"text": "Flutter provides http package to consume HTTP resources. http is a Future-based library and uses await and async features. It provides many high level methods and simplifies the development of REST based mobile applications."
},
{
"code": null,
... |
Orchestrate a Data Science Project in Python With Prefect | by Khuyen Tran | Towards Data Science | As a data scientist, why should you care about optimizing your data science workflow? Let’s start with an example of a basic data science project.
Imagine you were working with an Iris dataset. You started with building functions to process your data.
After defining the functions, you execute them.
Your code ran fine, and you saw nothing wrong with the output, so you think the workflow is good enough. However, there can be many disadvantages with a linear workflow like above.
The disadvantages are:
If there is an error in the function get_classes , the output produced by the function encode_categorical_columns will be lost, and the workflow will need to start from the beginning. This can be frustrating if it takes a long time to execute the function encode_categorical_columns .
Since the functions encode_categorical_columns and get_classes are not dependent on each other, they can be executed at the same time to save time:
Running the functions this way can also prevent wasting unnecessary time on functions that don’t work. If there is an error in the function get_classes , the workflow will restart right away without waiting for the function encode_categorical_columns to finish.
Now, you might agree with me that it is important to optimize the workflow of different functions. However, it can be a lot of works to manually manage the workflow.
Is there a way that you can automatically optimize the workflow by adding only several lines of code? That is when Prefect comes in handy.
Prefect is an open-sourced framework to build workflows in Python. Prefect makes it easy to build, run, and monitor data pipelines at scale.
To install Prefect, type:
pip install prefect
To learn how Prefect works, let’s encapsulate the workflow at the beginning of the article with Prefect.
A Task is a discrete action in a Prefect flow. Start with turning the functions defined above into tasks using the decorator prefect.task :
A Flow represents the entire workflow by managing the dependencies between tasks. To create a flow, simply insert the code to run your functions inside the with Flow(...) context manager.
Note that none of these tasks are executed when running the code above. Prefect allows you to either run the flow right away or schedule for later.
Let’s try to execute the flow right away using flow.run() :
Running the code above will give you the output similar to this:
To understand the workflow created by Prefect, let’s visualize the entire workflow.
Start with installing prefect[viz] :
pip install "prefect[viz]"
Then add the method visualize to the code:
And you should see the visualization of the data-engineer workflow like below!
Note that Prefect automatically manages the orders of execution among tasks so that the workflow is optimized. This is pretty cool for a few additional pieces of code!
If you find yourself frequently experimenting with different values of one variable, it’s ideal to turn that variable into a Parameter.
You can consider a Parameter as a Task , except that it can receive user inputs whenever a flow is run. To turn a variable into a parameter, simply use task.Parameter .
The first argument of Parameter specifies the name of the parameter. default is an optional argument that specifies the default value of the parameter.
Running flow.visualize again will give us an output like below:
You can overwrite the default parameter for each run by:
adding the argument parameters to flow.run() :
or using Prefect CLI:
or using a JSON file:
Your JSON file should look similar to this:
You can also change parameters for each run using Prefect Cloud, which will be introduced in the next section.
Prefect also allows you to monitor your workflow in Prefect Cloud. Follow this instruction to install relevant dependencies for Prefect Cloud.
After all of the dependencies are installed and set up, start with creating a project on Prefect by running:
$ prefect create project "Iris Project"
Next, start a local agent to deploy our flows locally on a single machine:
$ prefect agent local start
Then add:
... at the end of your file.
After running the file, you should see something similar to the below:
Click the URL in the output, and you will be redirected to an Overview page. The Overview page shows the version of your flow, when it is created, the flow’s run history, and its runs summary.
You can also view the summary of other runs, when they are executed, and their configurations.
It is pretty cool how these important pieces of information are automatically tracked by Perfect!
Note that the workflow is registered to Prefect Cloud, but it is not executed yet. To execute the workflow with the default parameters, click Quick Run in the top right corner.
Click the run that is created. Now you will be able to see the activity for your new flow run in real-time!
To run the workflow with custom parameters, click the Run tab, then change the parameters under Inputs.
When you are satisfied with the parameters, simply click the Run button to start the run.
Clicking Schematic will give you the graph of the entire workflow.
Besides some basic features mentioned above, Prefect also provides some other cool features that will significantly increase the efficiency of your workflow.
Remember the problem we mentioned at the beginning of the article? Normally, if the function get_classes fails, the data created by the function encode_categorical_columns will be discarded and the entire workflow needs to start from the beginning.
However, with Prefect, the output of encode_categorical_columns is stored. Next time when the workflow is rerun, the output of encode_categorical_columns will be used by the next task without rerunning the task encode_categorical_columns .
This can result in a huge decrease in the time it takes to run the workflow.
Sometimes, you might want to export your task’s data to an external location. This can be done by inserting to the task function the code to save the data.
However, doing that will make it difficult to test the function.
Prefect makes it easy to save the output of a task for each run by:
setting the checkpoint to True
$ export PREFECT__FLOWS__CHECKPOINTING=true
and adding result = LocalResult(dir=...)) to the decorator @task .
Now the output of the task split_data will be saved to the directory data/processed ! The name will look something similar to this:
prefect-result-2021-11-06t15-37-29-605869-00-00
If you want to customize the name of your file, you can add the argument target to @task :
Prefect also provides other Result classes such as GCSResult and S3Result . You can check out API docs for results here.
If you are working with multiple flows, for example, data-engineer flow and data-science flow, you might want to use the output of the data-engineer flow for the data-science flow.
After saving the output of your data-engineer flow as a file, you can read that file using the read method:
Imagine this scenario: You created two flows that depend on each other. The flow data-engineer needs to be executed before the flow data-science
Somebody who looked at your workflow didn’t understand the relationship between these two flows. As a result, they executed the flow data-science and the flow data-engineer at the same time and encountered an error!
To prevent this from happening, we should specify the relationship between flows. Luckily, Prefect makes it easier for us to do so.
Start with grabbing two different flows using StartFlowRun . Add wait=True to the argument so that the downstream flow is executed only after the upstream flow finishes executing.
Next, calling data_science_flow under the with Flow(...) context manager. Use upstream_tasks to specify the tasks/flows that will be executed before the data-science flow is executed.
Now the two flows are connected like below:
Pretty cool!
Prefect also makes it seamless to execute a flow at a certain time or at a certain interval.
For example, to run a flow every 1 minute, you can initiate the class IntervalSchedule and add schedule to the with Flow(...) context manager:
Now your flow will be rerun every 1 minute!
Learn more about different ways to schedule your flow here.
You can log the print statements within a task by simply adding log_stdout=True to @task :
And you should see an output like below when executing the task:
[2021-11-06 11:41:16-0500] INFO - prefect.TaskRunner | Model accuracy on test set: 93.33
Congratulations! You have just learned how Prefect can optimize your data science workflow in a few lines of Python code. Small optimization in your code can result in a huge increase in efficiency in the long run.
Feel free to play and fork the source code of this article here:
github.com
I like to write about basic data science concepts and play with different data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: | [
{
"code": null,
"e": 318,
"s": 171,
"text": "As a data scientist, why should you care about optimizing your data science workflow? Let’s start with an example of a basic data science project."
},
{
"code": null,
"e": 423,
"s": 318,
"text": "Imagine you were working with an Iris d... |
Python - Flatten Nested Tuples - GeeksforGeeks | 04 Jan, 2022
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can have application across many domains such as Data Science and web development. Let’s discuss certain way in which this task can be performed.
Input : test_tuple = ((4, 7), ((4, 5), ((6, 7), (7, 6))))
Output : ((4, 7), (4, 5), (6, 7), (7, 6))
Input : test_tuple = ((4, 7), (5, 7), (1, 3))
Output : ((4, 7), (5, 7), (1, 3))
Method : Using recursion + isinstance()The combination of above functionalities can help us achieve solution to this problem. In this we use recursion to perform the task of digging into each tuple for inner tuples, and for decision of flattening, isinstance() is used depending upon tuple container or primitive data.
Python3
# Python3 code to demonstrate working of # Flatten Nested Tuples# Using recursion + isinstance() # helper functiondef flatten(test_tuple): if isinstance(test_tuple, tuple) and len(test_tuple) == 2 and not isinstance(test_tuple[0], tuple): res = [test_tuple] return tuple(res) res = [] for sub in test_tuple: res += flatten(sub) return tuple(res) # initializing tupletest_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4)))) # printing original tupleprint("The original tuple : " + str(test_tuple)) # Flatten Nested Tuples# Using recursion + isinstance()res = flatten(test_tuple) # printing result print("The flattened tuple : " + str(res))
The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : ((4, 5), (4, 7), (8, 9), (10, 11), (9, 10), (3, 4))
surinderdawra388
Python Nested-Tuples
Python tuple-programs
Python
Python Programs
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24874,
"s": 24846,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 25177,
"s": 24874,
"text": "Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can ha... |
Bootstrap hide.bs.tab event | The hide.bs.tab fires when the tab is about to be hidden in Bootstrap.
Fire the hide.bs.tab and generate the alert before the modal is hidden −
$('.nav-tabs a').on('hide.bs.tab', function(e){
alert('Previous tab will hide now!');
});
The first tab is the active tab and fade in property is also set −
<div id="home" class="tab-pane fade in active">
<h3>Home</h3>
<p>This is demo text!</p>
</div>
You can try to run the following code to implement the hide.bs.tab event −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Web Dev</h2>
<ul class="nav nav-tabs">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#two">PHP</a></li>
<li><a href="#three">C#.NET</a></li>
<li><a href="#four">Ruby</a></li>
<li><a href="#five">HTML5</a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade in active">
<h3>Home</h3>
<p>This is demo text!</p>
</div>
<div id="two" class="tab-pane fade">
<h3>PHP</h3>
<p>This is demo text!</p>
</div>
<div id="three" class="tab-pane fade">
<h3>C#.NET</h3>
<p>This is demo text!</p>
</div>
<div id="four" class="tab-pane fade">
<h3>Ruby</h3>
<p>This is demo text!</p>
</div>
<div id="five" class="tab-pane fade">
<h3>HTML5</h3>
<p>This is demo text!</p>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
$('.nav-tabs a').on('show.bs.tab', function(){
alert('New tab will be visible now!');
});
$('.nav-tabs a').on('shown.bs.tab', function(){
alert('New tab is now visible!');
});
$('.nav-tabs a').on('hide.bs.tab', function(e){
alert('Previous tab will hide now!');
});
$('.nav-tabs a').on('hidden.bs.tab', function(){
alert('Previous Tab is hidden now!');
});
});
</script>
</body>
</html> | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "The hide.bs.tab fires when the tab is about to be hidden in Bootstrap."
},
{
"code": null,
"e": 1206,
"s": 1133,
"text": "Fire the hide.bs.tab and generate the alert before the modal is hidden −"
},
{
"code": null,
"e": 1... |
Creating A Twitter Sentiment Analysis Program in Python with Naive Bayes Classification | by Anas Al-Masri | Towards Data Science | Sentiment Analysis is a term that you must have heard if you have been in the Tech field long enough. It is the process of predicting whether a piece of information (i.e. text, most commonly) indicates a positive, negative or neutral sentiment on the topic. In this article, we will go through making a Python program that analyzes the sentiment of tweets on a particular topic. The user will be able to input a keyword and get the sentiment on it based on the latest 100 tweets that contain the input keyword.
Also known as “Opinion Mining”, Sentiment Analysis refers to the use of Natural Language Processing to determine the attitude, opinions and emotions of a speaker, writer, or other subject within an online mention.
Essentially, it is the process of determining whether a piece of writing is positive or negative. This is also called the Polarity of the content.
As humans, we are able to classify text into positive/negative subconsciously. For example, the sentence “The kid had a gorgeous smile on his face”, will most likely give us a positive sentiment. In layman’s terms, we kind of arrive to such conclusion by examining the words and averaging out the positives and the negatives. For instance, the words “gorgeous” and “smile” are more likely to be positive, while words like “the”, “kid” and “face” are really neutral. Therefore, the overall sentiment of the sentence is likely to be positive.
A common use for this technology comes from its deployment in the social media space to discover how people feel about certain topics, particularly through users’ word-of-mouth in textual posts, or in the context of Twitter, their tweets.
Basic programming knowledge:
Although Python is highly involved in this mini-project, it is not required to have a deep knowledge in the language, as long as you have basic programming knowledge.
Installed tools:
For this program, we will need Python to be installed on the computer. We will be using the libraries twitter, nltk, re, csv, time, and json. You are likely to have to install the first two libraries. The rest already come with the Python interpreter. It doesn’t hurt to check that they’re up-to-date though.
Data set splitting concept:
This is critical to fully understand the process pipeline. You only need to know the difference between Training and Test data sets, and in what context each one is used.
Basic RESTful API knowledge:
This is not crucial, but it could help. We will be using the Twitter API here and there in the code, making normal calls to the API and dealing with the JSON objects it returns. In case you need it, you can find the official Twitter API documentation here.
Section A: Preparing The Test Set
Step A.1: Getting the authentication credentials
Step A.2: Authenticating our Python script
Step A.3: Creating the function to build the Test set
Section B: Preparing The Training Set
Section C: Pre-processing Tweets in The Data Sets
Section D: Naive Bayes Classifier
Step D.1: Building the vocabulary
Step D.2: Matching tweets against our vocabulary
Step D.3: Building our feature vector
Step D.4: Training the classifier
Section E: Testing The Model
Twitter can sometimes take a few days to approve your application to use the Twitter API. However, it usually takes less that 24 hours.
It can take 10+ hours to download the Training set (this will be explained later on).
The tutorial was adopted from the Udemy course: From 0 to 1: Machine Learning, NLP, and Python-cut to The Chase.
As our task of Sentiment Analysis is one that focuses heavily on textual data, one would expect there to be a lot of text processing. This is definitely correct. In fact, both our Test and Training data will merely comprise of text.
I chose to start with the Test set in order to get you all warmed up for the Training set extraction part, as it will rely more on the API. Here is a bit of an overview of what we are about to do:
1- Register Twitter application to get our own credentials.
2- Authenticate our Python script with the API using the credentials.
3- Create function to download tweets based on a search keyword.
Registering an application with Twitter is critical, as it is the only way to get authentication credentials. As soon as we get our credentials, we will start writing code. Step 3 is where the Test set lies. We will be downloading tweets based on the term that we are trying to analyze the sentiment on.
Step A.1: Getting the authentication credentials
First off, we need to visit the Twitter Developer website and log into our account through the following link:
developer.twitter.com
On the top-right corner, click on the Apps button, Create an App, Apply and then Continue, as shown below:
Next, we will choose the “I am requesting access for my own personal use” option:
On the same web page, scroll-down a bit and input your Account name and Country of operation then click Continue, and you will be redirected to the next web page. Here, you can choose any Use Cases you’re interested in. For our case, I chose the following:
After you make your choice, scroll-down and fill out the use case interest paragraph required. Twitter takes this very seriously now (guess they learned from Facebook’s mistakes xD), so make sure you emphasize on the application being a self-learning/academic-related project. Choose “No” for the government involvement question, and press “Continue”.
On the next web page, read the Terms and Conditions list, Agree to them then Submit Application.
Next, open your email and verify your Twitter Developer account through the link included in the email sent to you. Finally, you will get a message similar to the following:
All you can do now is wait for a few hours for the application to be approved (which almost certainly will, if your explanation did not violate Twitter’s terms and conditions).
When you get the approval email, click on the login link it contains. You will be redirected to the following web page, where you should choose “Create an app”:
On the next web page, click “Create an app” from the top-right corner. After you are redirected, fill out the required app details, including — if you’d like — that it is for self-learning purposes. Click “Create”.
The next web page will include the app details that you just input, access tokens and permissions. Proceed to the “Keys and tokens” tab. Copy the API key as well as the API secret key into a safe place (a text file, if you’d like), as we will be using them in a bit.
Once you’re all set, click “Create” to generate the Access token credentials. Copy the Access token and the Access token secret into a safe place as well. We’re done with the credential acquisition part!
Step A.2: Authenticating our Python script
Since we now have our Twitter Developers login credentials (i.e. API keys and Access token), we can proceed to authenticating our program. First, we need to import the Twitter library, then create an Twitter.API object with the credentials from the “safe” place we talked about, as follows:
The last line in the previous code snippet is only there to verify that our API instance works. This will be determined based on the output we get. Run the above code and you should get something like the following JSON response:
{"created_at": "Tue Feb 12 17:48:27 +0800 2019" 'default_profile": true ............}
That is nothing crazy but some data about the access made to the API through your Twitter account. If you reach this, you’re good to go.
Step A.3: Creating the function to build the Test set
Now we can start on making a function that downloads the Test set that we talked about. Basically, this is going to be a function that takes a search keyword (i.e. string) as an input, searches for tweets that include this keyword and returns them as twitter.Status objects that we can iterate through.
The caveat here, though, is that Twitter limits the number of requests you can make through the API for security purposes. This limit is 180 requests per 15-minute window.
This means, we can only get up to 180 tweets using our search function every 15 minutes, which should not be a problem, as our Training set is not going to be that large anyway. For the sake of simplicity, we will limit the search to 100 tweets for now, not exceeding the allowed number of requests. Our function for searching for the tweets (i.e. Test set) will be:
As you might have expected, this function will return a list of tweets that contain our search keyword.
Note that we coupled — into a JSON object — every tweet’s text with a label that is NULL for now. This is merely because we are going to classify each tweet as Positive or Negative later on, in order to determine whether the sentiment on the search term is positive or negative, based on the majority count. This is how Sentiment Analysis pragmatically works.
Before we move on, let’s test out our function by adding the following code after the function body:
This should print out five tweets that contain our search keyword on the Terminal of your IDE (if you’re using one). Now everything is set. We have our Test set and we can move on to building our Training set.
Note that so far, we haven’t written a lot of code. This is attributed to the beauty of Python’s succinctness in syntax as well as the use of external program-ready libraries, such as RESTful APIs (Twitter API in our case).
In this section, we will also be using our Twitter API instance from the last section. However, we need to get some things out the way first. We will be using a downloadable Training set. The tweets of which were all labeled as positive or negative, depending on the content. This exactly what a Training set is for.
A Training set is critical to the success of the model. Data is which needs to be labeled properly with no inconsistencies or incompleteness, as training will rely heavily on the accuracy of such data and the manner of acquisition.
For this task, we will be using the amazing Niek Sanders’ Corpus of over 5000 hand-classified tweets, which makes it quite reliable. There’s also a catch here. Twitter does not allow storing tweets on a personal device, even though all such data is publicly available. Therefore, the corpus includes a keyword (topic of the tweet), a label (pos/neg) and a tweet ID number for every tweet (i.e. row in our CSV corpus). You can get the file containing the corpus from the original site, or through this link of a personal repository.
Let’s backtrack for a bit. Remember the Twitter API limit we talked about? This will also apply here, as we will be using the API to get the actual tweet text through each tweet’s ID number included in the Corpus we have. This means, to download 5000 tweets, we will need to follow:
max_number_of_requests = 180time_window = 15 minutes = 900 secondsTherefore, the process should follow:Repeat until end-of-file: { 180 requests -> (900/180) sec wait}
Let’s now write the code that does exactly that. Let’s not forget to save the tweets we retrieve through the API into a new CSV file so that we don’t have to download them every time we run the code. Our function will be as follows:
This was a handful, but it’s fairly simple if we break it down into parts. Firstly, we define the function to take two inputs, both of which are file paths:
corpusFile is the string path to the Niek Sanders’ CSV corpus file we downloaded. This file, as mentioned earlier, includes the tweet’s topic, label and id.
tweetDataFile is the string path to the file we would like to save the full tweets in. In contrast to corpusFile, this file will include every tweet’s text as well as topic, label and id.
Next, we started with an empty list corpus. We then opened the file corpusFile and appended every tweet from the file to the list corpus.
The next segment of the code deals with getting the text of tweets based on the IDs. We loop through the tweets in corpus, calling the API on every tweet to get the Tweet.Status object of the particular tweet. Afterwards, we use that same object (status) to get the text associated with it and push it into the trainingDataSet then sleep (i.e. pause execution) for five minutes (900/180 seconds) in order to abide by the request limit we talked about.
Now let’s take the time to leave our script download the tweets (which will take hours) following our last function. We can do this using the following snippet:
As soon as the code finishes executing, you will have your tweetDataFile CSV file full of tweets (~5000, as a matter of fact). If you got this far, CONGRATULATIONS !— it took me, the first time, a substantial amount of time to reach here without problems. Now we’re done with the relatively boring part. Let’s get ourselves hyped up for the upcoming section.
Before we move on to the actual classification section, there is some cleaning up to do. As a matter of fact, this step is critical and usually takes a long time when building Machine Learning models. However, this will not be a problem in our task, as the data we have is relatively consistent. In other words, we know exactly what we need from it. I will express on this matter later on.
Let’s talk about what matters and what doesn’t matter in Sentiment Analysis. Words are the most important part (to an extent that we will talk about in the upcoming section). However, when it comes to things like punctuation, you cannot get the sentiment from punctuation. Therefore, punctuation does not matter to Sentiment Analysis. Moreover, tweet components like images, videos, URLs, usernames, emojis, etc. do not contribute to the polarity (whether it is positive or negative) of the tweet. However, this is only true for this application. For instance, in another application, you could have a Deep Learning image classifier that learns and predicts whether this image that the tweet contains stands for something positive (e.g. a rainbow) or negative (e.g. a tank). When it comes to the technicality, both Sentiment Analysis and Deep Learning fall under Machine Learning. In fact, you can perform Sentiment Analysis through Deep Learning, but that’s a story for another day.
So we know what we need to keep in the tweets we have and what we need to take out. This applies to both Training and Test sets. So let’s make a our pre-processor class:
That was a handful, so let’s break it down into parts. We start off by our imported libraries. re is Python’s Regular Expressions (RegEx) library, which takes care of parsing strings and modifying them in an efficient way without having to explicitly iterate through the characters comprising the particular string. We also imported ntlk, is the Natural Processing Toolkit, which is one of the most commonly used Python libraries out there. It takes care of any processing that we need to perform on text to change its form or extract certain components from it. The class constructor removes stop words. This is a relatively big topic that you can read up on later, as it is more into Natural Language Processing and less related to our topic.
The processTweets function just loops through all the tweets input into it, calling its neighboring function processTweet on every tweet in the list. The latter does the actual pre-processing by first making all the text in lower-case letters. This is merely because, in almost all programming languages, “cAr” is not interpreted the same way as “car”. Therefore, it is better to normalize all characters to be lower-case across all our data. Secondly, URLs and usernames are removed from the tweet. This is for the reasons we disclosed earlier in the article. Afterwards, the number sign (i.e. #) is removed from every hashtag, in order to avoid hashtags being processed differently. Last but not least, duplicate characters are rid off of, in order to ensure that no important word goes unprocessed even if it is spelled out in an unusual way (e.g. “caaaaar” becomes “car”). Finally, the tweet’s text is broken into words (tokenized) in order to ease its processing in the upcoming stages.
Let’s take an example. The following tweet could be present in the data set:
"@person1 retweeted @person2: Corn has got to be the most delllllicious crop in the world!!!! #corn #thoughts..."
Our pre-processor will result in the tweet looking like:
“AT_USER rt AT_USER corn has got to be the most delicious crop in the world corn thoughts”
And finally, the tokenization will result in:
{“corn”, “most”, “delicious”, “crop”, “world”, “corn”, “thoughts”}
Note that our code removed duplicate characters in words as we metioned earlier (i.e. “delllllicious” became “delicious”). However, it did not remove duplicate words (i.e. “corn”) from the text, but rather kept them. This is because duplicate word play a role in determining the polarity of the text (as we will see in the upcoming section).
We are all set to use our Pre-processor class. First, we will create a variable that refers to it (an object), and then call it on both the Training and Test sets as we discussed earlier:
Now we can move on to the most exciting part — classification. But first, let’s brush up (or touch) on our algorithm for this task: Naive Bayes Classifier.
Without a doubt, one of the most important concepts in Computer Science and Machine Learning. It can be frustrating to get into the math of it head-first. Therefore, I will not be explaining it from the mathematical perspective.
You don’t need to know the math to be a Computer Scientist. However, you do need to know the math to become a really good one.
I want to emphasize on the fact that I will only briefly explain Naive Bayes Classification here, as the in-depth explanation deserves its own lengthy post.
Naive Bayes Classifier is a classification algorithm that relies on Bayes’ Theorem. This theorem provides a way of calculating a type or probability called posterior probability, in which the probability of an event A occurring is reliant on probabilistic known background (e.g. event B evidence). For example, if Person_X only plays tennis when it is not raining outside, then, according to Bayesian statistics, the probability of Person_X playing tennis when it is not raining can be given as:
P(X plays | no rain) = P(no rain | X plays)*P(x plays)/P(no rain)
following Bayes’ theorem:
P(A|B) = P(B|A)*P(A)/P(B)
All you need to know for our task is that a Naive Bayes Classifier depends on the ever-famous Bayes’ theorem. Before we move on, let’s give a quick overview of the steps we will be taking next:
1- Build a vocabulary (list of words) of all the words resident in our training data set.
2- Match tweet content against our vocabulary — word-by-word.
3- Build our word feature vector.
4- Plug our feature vector into the Naive Bayes Classifier.
This might seem like a lot, but don’t worry. It is actually fairly simple and as short as it can be. Let’s take it down step-by-step.
Step D.1: Building the vocabulary
A vocabulary in Natural Language Processing is a list of all speech segments available for the model. In our case, this includes all the words resident in the Training set we have, as the model can make use of all of them relatively equally — at this point, to say the least. The code will look something like this:
This is just creating a list of all_words we have in the Training set, breaking it into word features. Those word_features are basically a list of distinct words, each of which has its frequency (number of occurrences in the set) as a key.
Step D.2: Matching tweets against our vocabulary
This step is crucial, as we will go through all the words in our Training set (i.e. our word_features list), comparing every word against the tweet at hand, associating a number with the word following:
label 1 (true): if word in vocabulary is resident in tweetlabel 0 (false): if word in vocabulary is not resident in tweet
This is fairly simple to code:
Given the last snippet, for every word in the word_features, we will have the JSON key ‘contains word X’, where X is the word. Every key of those will have the value True/False, according to what we said earlier about the labels — True for ‘present’ and False for ‘absent’.
Step D.3: Building our feature vector
Let’s now call the last two functions we have written. This will build our final feature vector, with which we can proceed on to training.
The NTLK built-in function apply_features does the actual feature extraction from our lists. Our final feature vector is trainingFeatures.
Step D.4: Training the classifier
We have finally come to the most important — and ironically the shortest — part of our task. Thanks to NLTK, it will only take us a function call to train the model as a Naive Bayes Classifier, since the latter is built into the library:
We’re almost done! All we have left is running the classifier training code (i.e. nltk.NaiveBayesClassifier.train()) and testing it. Note that this code could take a few minutes to execute.
Moment of truth! Let’s finish up our work by running the classifier (i.e. NBayesClassifier) on the 100 tweets that we downloaded from Twitter, according to our search term, and getting the majority vote of the labels returned by the classifier, then outputting the total positive or negative percentage (i.e. score) of the tweets. This is also going to be very simple:
That’s it! Congratulations. You have created a Twitter Sentiment Analysis Python program. Note that we did not touch on the accuracy (i.e. evaluate the model) because it is not our topic for the day. There will be a post where I explain the whole model/hypothesis evaluation process in Machine Learning later on. Let’s take a final look at the full code we wrote for this task:
Sentiment Analysis is an interesting way to think about the applicability of Natural Language Processing in making automated conclusions about text. It is being utilized in social media trend analysis and, sometimes, for marketing purposes. Making a Sentiment Analysis program in Python is not a difficult task, thanks to modern-day, ready-for-use libraries. This program is a simple explanation to how this kind of application works. This is only for academic purposes, as the program described here is by no means production-level. | [
{
"code": null,
"e": 683,
"s": 172,
"text": "Sentiment Analysis is a term that you must have heard if you have been in the Tech field long enough. It is the process of predicting whether a piece of information (i.e. text, most commonly) indicates a positive, negative or neutral sentiment on the topi... |
10 Important Android Studio Shortcuts You Need the Most - GeeksforGeeks | 10 Sep, 2021
Android Studio is the official integrated development environment (IDE) for Android application development. In this article, some of the most imp shortcuts are explained in Android, with the help of examples.
Some of the most important Shortcut keys used in Android Studio are:
1. CTRL + E -> Recently opened files pop-up: The Android Studio has an option where you can browse the most recently opened files on the go. It was performed with the help of Ctrl + E.
Syntax:
Windows: CTRL + E
Mac: Command + E
Example:
2. CTRL + D -> Duplicate current line or selection: The Android Studio has an option where you can create a duplicate of the current line or the selection. It performed with the help of Ctrl + D.
Syntax:
Windows: CTRL + D
Mac: Command + D
3. CTRL + Y -> Delete line at caret: The Android Studio has an option where you can delete the current line where the cursor is at. It performed with the help of Ctrl + Y.
Syntax:
Windows: CTRL + Y
Mac: Command + Delete
Example:
4. CTRL + Q -> Quick documentation lookup: The Android Studio has an option where you can browse the documentation quickly. It performed with the help of Ctrl + Q.
Syntax:
Windows: CTRL + Q
Mac: CTRL + J
5. CTRL + ALT + L -> Reformat code: The Android Studio has an option where you can format the code with just one press. It performed with the help of Ctrl + Alt + L.
Syntax:
Windows: CTRL + ALT + L
Mac: Command + Option + L
Example:
6. CTRL + O -> Override methods: The Android Studio has an option where you can override methods. It performed with the help of Ctrl + O.
Syntax:
Windows: CTRL + O
Mac: CTRL + O
7. CTRL + ‘+’/’-‘ (Plus/Minus) -> Collapse/expand current code block: The Android Studio has an option where you can collapse or open the current code block in which the cursor is. The expansion of the block is performed with the help of Ctrl + ‘+’ and the contraction with the help of Ctrl + ‘-‘.
Syntax:
Windows: CTRL + '+'/'-'
Mac: Command + '+'/'-'
Example:
8. CTRL + Shift + ‘+’/’-‘ (Plus/Minus) -> Collapse/expand all code block: The Android Studio has an option where you can collapse or open all the code blocks. The expansion of the block is performed with the help of Ctrl + ‘+’ and the contraction with the help of Ctrl + ‘-‘.
Syntax:
Windows: CTRL + Shift + '+'/'-'
Mac: Command + Shift + '+'/'-'
9. CTRL + ALT + I -> Auto-indent code: The Android Studio has an option where you can auto indent the code with just one press. It performed with the help of Ctrl + Alt + I.
Syntax:
Windows: CTRL + ALT + I
Mac: Command + Option + I
10. CTRL + B or CTRL + click -> Go to declaration (directly): The Android Studio has an option where you can go to the declaration of the entity directly from its use. It performed with the help of Ctrl + B or Ctrl + Click.
Syntax:
Windows: CTRL + B or CTRL + Click
Mac: Command + B or Command + Click
Reference: https://developer.android.com/studio/intro/keyboard-shortcuts
kk9826225
nnr223442
android
Android-Studio
Android
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
How to Change the Background Color After Clicking the Button in Android?
Android Listview in Java with Example
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
MVP (Model View Presenter) Architecture Pattern in Android with Example
Fragment Lifecycle in Android
How to Add Image to Drawable Folder in Android Studio? | [
{
"code": null,
"e": 25140,
"s": 25112,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 25351,
"s": 25140,
"text": "Android Studio is the official integrated development environment (IDE) for Android application development. In this article, some of the most imp shortcuts are ex... |
JqueryUI - Datepicker | Datepickers in jQueryUI allow users to enter dates easily and visually. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.
jQueryUI provides datepicker() method that creates a datepicker and changes the appearance of HTML elements on a page by adding new CSS classes. Transforms the <input>, <div>, and <span> elements in the wrapped set into a datepicker control.
The datepicker() method can be used in two forms −
$(selector, context).datepicker (options) Method
$(selector, context).datepicker (options) Method
$(selector, context).datepicker ("action", [params]) Method
$(selector, context).datepicker ("action", [params]) Method
$(selector, context).datepicker(options);
You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows −
$(selector, context).datepicker({option1: value1, option2: value2..... });
The following table lists the different options that can be used with this method −
This option specifies a jQuery selector for a field that is also updated with any date selections. The altFormat option can be used to set the format for this value. This is quite useful for setting date values into a hidden input element to be submitted to the server, while displaying a more user-friendly format to the user. By default its value is "".
Option - altField
This option specifies a jQuery selector for a field that is also updated with any date selections. The altFormat option can be used to set the format for this value. This is quite useful for setting date values into a hidden input element to be submitted to the server, while displaying a more user-friendly format to the user. By default its value is "".
Syntax
$(".selector").datepicker(
{ altField: "#actualDate" }
);
This option is used when an altField option is specified. It provides the format for the value to be written to the alternate element. By default its value is "".
Option - altFormat
This option is used when an altField option is specified. It provides the format for the value to be written to the alternate element. By default its value is "".
Syntax
$(".selector").datepicker(
{ altFormat: "yy-mm-dd" }
);
This option is a String value to be placed after the <input> element, intended to show instructions to the user. By default its value is "".
Option - appendText
This option is a String value to be placed after the <input> element, intended to show instructions to the user. By default its value is "".
Syntax
$(".selector").datepicker(
{ appendText: "(yyyy-mm-dd)" }
);
This option when set to true resizes the <input> element to accommodate the datepicker’s date format as set with the dateFormat option. By default its value is false.
Option - autoSize
This option when set to true resizes the <input> element to accommodate the datepicker’s date format as set with the dateFormat option. By default its value is false.
Syntax
$(".selector").datepicker(
{ autoSize: true }
);
This option is a callback function that’s invoked just before a datepicker is displayed, with the <input> element and datepicker instance passed as parameters. This function can return an options hash used to modify the datepicker. By default its value is "".
Option - beforeShow
This option is a callback function that’s invoked just before a datepicker is displayed, with the <input> element and datepicker instance passed as parameters. This function can return an options hash used to modify the datepicker. By default its value is "".
This option is a callback function which takes a date as parameter, that’s invoked for each day in the datepicker just before it’s displayed, with the date passed as the only parameter. This can be used to override some of the default behavior of the day elements. This function must return a three-element array.By default its value is null.
Option - beforeShowDay
This option is a callback function which takes a date as parameter, that’s invoked for each day in the datepicker just before it’s displayed, with the date passed as the only parameter. This can be used to override some of the default behavior of the day elements. This function must return a three-element array, as follows −
[0]—true to make the date selectable, false otherwise.
[0]—true to make the date selectable, false otherwise.
[1]—A space-delimited string of CSS class names to be applied or an empty string to apply none
[1]—A space-delimited string of CSS class names to be applied or an empty string to apply none
[2]—An optional string to apply a tooltip to the day element
[2]—An optional string to apply a tooltip to the day element
By default its value is null.
This option specifies the path to an image to be displayed on the button enabled by setting the showOn option to one of buttons or both. If buttonText is also provided, the button text becomes the alt attribute of the button. By default its value is "".
Option - buttonImage
This option specifies the path to an image to be displayed on the button enabled by setting the showOn option to one of buttons or both. If buttonText is also provided, the button text becomes the alt attribute of the button. By default its value is "".
Syntax
$(".selector").datepicker(
{ buttonImage: "/images/datepicker.gif" }
);
This option if set to true, specifies that the image specified by buttonImage is to appear standalone (not on a button). The showOn option must still be set to one of button or both for the image to appear. By default its value is false.
Option - buttonImageOnly
This option if set to true, specifies that the image specified by buttonImage is to appear standalone (not on a button). The showOn option must still be set to one of button or both for the image to appear. By default its value is false.
Syntax
$(".selector").datepicker(
{ buttonImageOnly: true }
);
This option specifies the caption for the button enabled by setting the showOn option to one of button or both. By default its value is "...".
Option - buttonText
This option specifies the caption for the button enabled by setting the showOn option to one of button or both. By default its value is "...".
Syntax
$(".selector").datepicker(
{ buttonText: "Choose" }
);
This option is a custom function to calculate and return the week number for a date passed as the lone parameter. The default implementation is that provided by the $.datepicker.iso8601Week() utility function.
Option - calculateWeek
This option is a custom function to calculate and return the week number for a date passed as the lone parameter. The default implementation is that provided by the $.datepicker.iso8601Week() utility function.
Syntax
$(".selector").datepicker(
{ calculateWeek: myWeekCalc }
);
This option if set to true, a month dropdown is displayed, allowing the user to directly change the month without using the arrow buttons to step through them. By default its value is false.
Option - changeMonth
This option if set to true, a month dropdown is displayed, allowing the user to directly change the month without using the arrow buttons to step through them. By default its value is false.
Syntax
$(".selector").datepicker(
{ changeMonth: true }
);
This option if set to true, a year dropdown is displayed, allowing the user to directly change the year without using the arrow buttons to step through them. Option yearRange can be used to control which years are made available for selection. By default its value is false.
Option - changeYear
This option if set to true, a year dropdown is displayed, allowing the user to directly change the year without using the arrow buttons to step through them. Option yearRange can be used to control which years are made available for selection. By default its value is false.
Syntax
$(".selector").datepicker(
{ changeYear: true }
);
This option specifies the text to replace the default caption of Done for the close button. It is used when the button panel is displayed via the showButtonPanel option. By default its value is "Done".
Option - closeText
This option specifies the text to replace the default caption of Done for the close button. It is used when the button panel is displayed via the showButtonPanel option. By default its value is "Done".
Syntax
$(".selector").datepicker(
{ closeText: "Close" }
);
This option if set true (the default), text entry into the <input> element is constrained to characters allowed by the current dateformat option. By default its value is true.
Option - constrainInput
This option if set true (the default), text entry into the <input> element is constrained to characters allowed by the current dateformat option. By default its value is true.
Syntax
$(".selector").datepicker(
{ constrainInput: false }
);
This option specifies the text to replace the default caption of Today for the current button. This is used if the button panel is displayed via the showButtonPanel option. By default its value is Today.
Option - currentText
This option specifies the text to replace the default caption of Today for the current button. This is used if the button panel is displayed via the showButtonPanel option. By default its value is Today.
Syntax
$(".selector").datepicker(
{ currentText: "Now" }
);
This option specifies the date format to be used. By default its value is mm/dd/yy.
Option - dateFormat
This option specifies the date format to be used. By default its value is mm/dd/yy.
Syntax
$(".selector").datepicker(
{ dateFormat: "yy-mm-dd" }
);
This option is a 7-element array providing the full day names with the 0th element representing Sunday. Can be used to localize the control. By default its value is [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ].
Option - dayNames
This option is a 7-element array providing the full day names with the 0th element representing Sunday. Can be used to localize the control. By default its value is [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ].
Syntax
$(".selector").datepicker(
{ dayNames: [ "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag" ] }
);
This option is a 7-element array providing the minimal day names with the 0th element representing Sunday, used as column headers. Can be used to localize the control. By default its value is [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ].
Option - dayNamesMin
This option is a 7-element array providing the minimal day names with the 0th element representing Sunday, used as column headers. Can be used to localize the control. By default its value is [ "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" ].
Syntax
$(".selector").datepicker(
{ dayNamesMin: [ "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa" ] }
);
This option specifies a 7-element array providing the short day names with the 0th element representing Sunday. Can be used to localize the control. By default its value is [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ].
Option - dayNamesShort
This option specifies a 7-element array providing the short day names with the 0th element representing Sunday. Can be used to localize the control. By default its value is [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ].
Syntax
$(".selector").datepicker(
{ dayNamesShort: [ "Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam" ] }
);
This option sets the initial date for the control, overriding the default value of today, if the <input> element has no value. This can be a Date instance, the number of days from today, or a string specifying an absolute or relative date. By default its value is null.
Option - defaultDate
This option sets the initial date for the control, overriding the default value of today, if the <input> element has no value. This can be a Date instance, the number of days from today, or a string specifying an absolute or relative date. By default its value is null.
Syntax
$(".selector").datepicker(
{ defaultDate: +7 }
);
This option specifies the speed of the animation that makes the datepicker appear. Can be one of slow, normal, or fast, or the number of milliseconds for the animation to span. By default its value is normal.
Option - duration
This option specifies the speed of the animation that makes the datepicker appear. Can be one of slow, normal, or fast, or the number of milliseconds for the animation to span. By default its value is normal.
Syntax
$(".selector").datepicker(
{ duration: "slow" }
);
This option specifies which day is considered the first day of the week, and will be displayed as the left-most column. By default its value is 0.
Option - firstDay
This option specifies which day is considered the first day of the week, and will be displayed as the left-most column. By default its value is 0.
Syntax
$(".selector").datepicker(
{ firstDay: 1 }
);
This option when set to true, the current day link is set to the selected date, overriding the default of today. By default its value is false.
Option - gotoCurrent
This option when set to true, the current day link is set to the selected date, overriding the default of today. By default its value is false.
Syntax
$(".selector").datepicker(
{ gotoCurrent: true }
);
This option if set to true, hides the next and previous links (as opposed to merely disabling them) when they aren’t applicable, as determined by the settings of the minDate and maxDate options. By default its value is false.
Option - hideIfNoPrevNext
This option if set to true, hides the next and previous links (as opposed to merely disabling them) when they aren’t applicable, as determined by the settings of the minDate and maxDate options. By default its value is false.
Syntax
$(".selector").datepicker(
{ hideIfNoPrevNext: true }
);
This option when set to true, specifies the localizations as a right-to-left language. By default its value is false.
Option - isRTL
This option when set to true, specifies the localizations as a right-to-left language. By default its value is false.
Syntax
$(".selector").datepicker(
{ isRTL: true }
);
This option sets the maximum selectable date for the control. This can be a Date instance, the number of days from today, or a string specifying an absolute or relative date. By default its value is null.
Option - maxDate
This option sets the maximum selectable date for the control. This can be a Date instance, the number of days from today, or a string specifying an absolute or relative date. By default its value is null.
Syntax
$(".selector").datepicker(
{ maxDate: "+1m +1w" }
);
This option sets the minimum selectable date for the control. This can be a Date instance, the number of days from today, or a string specifying an absolute or relative date. By default its value is null.
Option - minDate
This option sets the minimum selectable date for the control. This can be a Date instance, the number of days from today, or a string specifying an absolute or relative date. By default its value is null.
Syntax
$(".selector").datepicker(
{ minDate: new Date(2007, 1 - 1, 1) }
);
This option is a 12-element array providing the full month names with the 0th element representing January. Can be used to localize the control. By default its value is [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ].
Option - monthNames
This option is a 12-element array providing the full month names with the 0th element representing January. Can be used to localize the control. By default its value is [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ].
Syntax
$(".selector").datepicker(
{ monthNames: [ "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre" ] }
);
This option specifies a 12-element array providing the short month names with the 0th element representing January. Can be used to localize the control. By default its value is [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ].
Option - monthNamesShort
This option specifies a 12-element array providing the short month names with the 0th element representing January. Can be used to localize the control. By default its value is [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ].
Syntax
$(".selector").datepicker(
{ monthNamesShort: [ "jan", "fév", "mar", "avr", "mai", "Jui", "Jul", "aoû", "sep", "Oot", "nov", "déc" ] }
);
This option if set to true, the navigation links for nextText, prevText, and currentText are passed through the
$.datepicker.formatDate() function prior to display. This allows date formats to be supplied for those options that get replaced with the relevant values. By default its value is false.
Option - navigationAsDateFormat
This option if set to true, the navigation links for nextText, prevText, and currentText are passed through the
$.datepicker.formatDate() function prior to display. This allows date formats to be supplied for those options that get replaced with the relevant values. By default its value is false.
Syntax
$(".selector").datepicker(
{ navigationAsDateFormat: true }
);
This option specifies the text to replace the default caption of Next for the next month navigation link. ThemeRoller replaces this text with an icon. By default its value is Next.
Option - nextText
This option specifies the text to replace the default caption of Next for the next month navigation link. ThemeRoller replaces this text with an icon. By default its value is Next.
Syntax
$(".selector").datepicker(
{ nextText: "Later" }
);
This option specifies the number of months to show in the datepicker. By default its value is 1.
Option - numberOfMonths
This option specifies the number of months to show in the datepicker. By default its value is 1. Multiple types supported −
Number − The number of months to display in a single row.
Number − The number of months to display in a single row.
Array − An array defining the number of rows and columns to display.
Array − An array defining the number of rows and columns to display.
Syntax
$(".selector").datepicker(
{ numberOfMonths: [ 2, 3 ] }
);
This option is a callback that’s invoked when the datepicker moves to a new month or year, with the selected year, month (1-based), and datepicker instance passed as parameters, and the function context is set to the input field element. By default its value is null.
Option - onChangeMonthYear
This option is a callback that’s invoked when the datepicker moves to a new month or year, with the selected year, month (1-based), and datepicker instance passed as parameters, and the function context is set to the input field element. By default its value is null.
This option is a callback invoked whenever a datepicker is closed, passed the selected date as text (the empty string if there is no selection), and the datepicker instance, and the function context is set to the input field element. By default its value is null.
Option - onClose
This option is a callback invoked whenever a datepicker is closed, passed the selected date as text (the empty string if there is no selection), and the datepicker instance, and the function context is set to the input field element. By default its value is null.
This option is a callback invoked whenever a date is selected, passed the selected date as text (the empty string if there is no selection), and the datepicker instance, and the function context is set to the input field element. By default its value is null.
Option - onSelect
This option is a callback invoked whenever a date is selected, passed the selected date as text (the empty string if there is no selection), and the datepicker instance, and the function context is set to the input field element. By default its value is null.
This option specifies the text to replace the default caption of Prev for the previous month navigation link. (Note that the ThemeRoller replaces this text with an icon). By default its value is PrevdefaultDatedayNamesMin.
Option - prevText
This option specifies the text to replace the default caption of Prev for the previous month navigation link. (Note that the ThemeRoller replaces this text with an icon). By default its value is Prev.
Syntax
$(".selector").datepicker(
{ prevText: "Earlier" }
);
This option if set to true, days shown before or after the displayed month(s) are selectable. Such days aren’t displayed unless the showOtherMonths option is true. By default its value is false.
Option - selectOtherMonths
This option if set to true, days shown before or after the displayed month(s) are selectable. Such days aren’t displayed unless the showOtherMonths option is true. By default its value is false.
Syntax
$(".selector").datepicker(
{ selectOtherMonths: true }
);
This option if its a number, specifies a value between 0 and 99 years before which any 2-digit year values will be considered to belong to the previous century. If this option is a string, the value undergoes a numeric conversion and is added to the current year.
The default is +10 which represents 10 years from the current year.
Option - shortYearCutoff
This option if its a number, specifies a value between 0 and 99 years before which any 2-digit year values will be considered to belong to the previous century. If this option is a string, the value undergoes a numeric conversion and is added to the current year.
The default is +10 which represents 10 years from the current year.
Syntax
$(".selector").datepicker(
{ shortYearCutoff: 50 }
);
This option specifies sets the name of the animation to be used to show and hide the datepicker. If specified, must be one of show (the default), fadeIn, slideDown, or any of the jQuery UI show/hide animations. By default its value is show.
Option - showAnim
This option specifies sets the name of the animation to be used to show and hide the datepicker. If specified, must be one of show (the default), fadeIn, slideDown, or any of the jQuery UI show/hide animations. By default its value is show.
Syntax
$(".selector").datepicker(
{ showAnim: "fold" }
);
This option if set to true, a button panel at the bottom of the datepicker is displayed, containing current and close buttons. The caption of these buttons can be provided via the currentText and closeText options. By default its value is false.
Option - showButtonPanel
This option if set to true, a button panel at the bottom of the datepicker is displayed, containing current and close buttons. The caption of these buttons can be provided via the currentText and closeText options. By default its value is false.
Syntax
$(".selector").datepicker(
{ showButtonPanel: true }
);
This option specifies the 0-based index, starting at the upper left, of where the month containing the current date should be placed within a multi-month display. By default its value is 0.
Option - showCurrentAtPos
This option specifies the 0-based index, starting at the upper left, of where the month containing the current date should be placed within a multi-month display. By default its value is 0.
Syntax
$(".selector").datepicker(
{ showCurrentAtPos: 3 }
);
This option specifies if set to true, the positions of the month and year are reversed in the header of the datepicker. By default its value is false.
Option - showMonthAfterYear
This option specifies if set to true, the positions of the month and year are reversed in the header of the datepicker. By default its value is false.
Syntax
$(".selector").datepicker(
{ showMonthAfterYear: true }
);
This option specifies when the datepicker should appear. The possible values are focus, button or both. By default its value is focus.
Option - showOn
This option specifies when the datepicker should appear. The possible values are focus, button or both. By default its value is focus.
focus (default) causes the datepicker to display when the <input> element gains focus.
button causes a button to be created after the <input> element (but before any appended text) that triggers the datepicker when clicked.
both causes the trigger button to be created, and for focus events to also trigger the datepicker.
Syntax
$(".selector").datepicker(
{ showOn: "both" }
);
This option provides a hash to be passed to the animation when a jQuery UI animation is specified for the showAnim option. By default its value is {}.
Option - showOptions
This option provides a hash to be passed to the animation when a jQuery UI animation is specified for the showAnim option. By default its value is {}.
Syntax
$(".selector").datepicker(
{ showOptions: { direction: "up" } }
);
This option if set to true, dates before or after the first and last days of the current month are displayed. These dates aren't selectable unless the selectOtherMonths option is also set to true. By default its value is false.
Option - showOtherMonths
This option if set to true, dates before or after the first and last days of the current month are displayed. These dates aren't selectable unless the selectOtherMonths option is also set to true. By default its value is false.
Syntax
$(".selector").datepicker(
{ showOtherMonths: true }
);
This option if set to true, the week number is displayed in a column to the left of the month display. The calculateWeek option can be used to alter the manner in which this value is determined. By default its value is false.
Option - showWeek
This option if set to true, the week number is displayed in a column to the left of the month display. The calculateWeek option can be used to alter the manner in which this value is determined. By default its value is false.
Syntax
$(".selector").datepicker(
{ showWeek: true }
);
This option specifies specifies how many months to move when one of the month navigation controls is clicked. By default its value is 1.
Option - stepMonths
This option specifies specifies how many months to move when one of the month navigation controls is clicked. By default its value is 1.
Syntax
$(".selector").datepicker(
{ stepMonths: 3 }
);
This option specifies the text to display for the week number column, overriding the default value of Wk, when showWeek is true. By default its value is Wk.
Option - weekHeader
This option specifies the text to display for the week number column, overriding the default value of Wk, when showWeek is true. By default its value is Wk.
Syntax
$(".selector").datepicker(
{ weekHeader: "W" }
);
This option specifies limits on which years are displayed in the dropdown in the form from:to when changeYear is true. The values can be absolute or relative (for example: 2005:+2, for 2005 through 2 years from now). The prefix c can be used to make relative values offset from the selected year rather than the current year (example: c-2:c+3). By default its value is c-10:c+10.
Option - yearRange
This option specifies limits on which years are displayed in the dropdown in the form from:to when changeYear is true. The values can be absolute or relative (for example: 2005:+2, for 2005 through 2 years from now). The prefix c can be used to make relative values offset from the selected year rather than the current year (example: c-2:c+3). By default its value is c-10:c+10.
Syntax
$(".selector").datepicker(
{ yearRange: "2002:2012" }
);
This option displays additional text after the year in the datepicker header. By default its value is "".
Option - yearSuffix
This option displays additional text after the year in the datepicker header. By default its value is "".
Syntax
$(".selector").datepicker(
{ yearSuffix: "CE" }
);
The following section will show you a few working examples of datepicker functionality.
The following example demonstrates a simple example of datepicker functionality passing no parameters to the datepicker() method.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-1" ).datepicker();
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-1"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Enter Date:
The following example demonstrates a simple example of inline datepicker functionality.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-2" ).datepicker();
});
</script>
</head>
<body>
<!-- HTML -->
Enter Date: <div id = "datepicker-2"></div>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
In the above example we use <div> element to get the inline date picker.
The following example shows the usage of three important options (a) appendText (b) dateFormat (c) altField and (d) altFormat in the datepicker function of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-3" ).datepicker({
appendText:"(yy-mm-dd)",
dateFormat:"yy-mm-dd",
altField: "#datepicker-4",
altFormat: "DD, d MM, yy"
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-3"></p>
<p>Alternate Date: <input type = "text" id = "datepicker-4"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Enter Date: (yy-mm-dd)
Alternate Date:
In the above example, you can see that the date formate for first input is set as yy-mm-dd. If you select some date from datepicker the same date is reflected in the second input field whose date format is set as "DD, d MM, yy".
The following example shows the usage of option beforeShowDay in the datepicker function of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-5" ).datepicker({
beforeShowDay : function (date) {
var dayOfWeek = date.getDay ();
// 0 : Sunday, 1 : Monday, ...
if (dayOfWeek == 0 || dayOfWeek == 6) return [false];
else return [true];
}
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-5"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Enter Date:
In the above example sunday and saturday are disabled.
The following example shows the usage of three important options (a) showOn (b) buttonImage and (c) buttonImageOnly in the datepicker function of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-6" ).datepicker({
showOn:"button",
buttonImage: "/jqueryui/images/calendar-icon.png",
buttonImageOnly: true
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-6"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Enter Date:
In the above example an icon is displayed which needs to b clicked to open the datepicker.
The following example shows the usage of three important options (a) dayNamesMin (b) dayNamesMin and (c) duration in the datepicker function of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-7" ).datepicker({
defaultDate:+9,
dayNamesMin: [ "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa" ],
duration: "slow"
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-7"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Enter Date:
In the above example the names of the days are changed using dayNamesMin. You can also see a default date is set.
The following example shows the usage of three important options (a) prevText (b) nextText (c) showOtherMonths and (d) selectOtherMonths in the datepicker function of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-8" ).datepicker({
prevText:"click for previous months",
nextText:"click for next months",
showOtherMonths:true,
selectOtherMonths: false
});
$( "#datepicker-9" ).datepicker({
prevText:"click for previous months",
nextText:"click for next months",
showOtherMonths:true,
selectOtherMonths: true
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Start Date: <input type = "text" id = "datepicker-8"></p>
<p>Enter End Date: <input type = "text" id = "datepicker-9"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Enter Start Date:
Enter End Date:
In the above example the prev and nect links have captions. If you click on the element, the datepicker opens. Now in the first datepicker, the other months dates are disable as selectOtherMonths is setfalse. In the second date picker for second input type, the selectOtherMonths is set totrue.
The following example shows the usage of three important options (a) changeMonth (b) changeYear and (c) numberOfMonths in the datepicker function of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-10" ).datepicker({
changeMonth:true,
changeYear:true,
numberOfMonths:[2,2]
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-10"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Enter Date:
In the above example, you can see dropdown menus for Month and Year fields. And we are dispalying 4 months in an array structure of [2,2].
The following example shows the usage of three important options (a) showWeek (b) yearSuffix and (c) showAnim in the datepicker function of JqueryUI.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-11" ).datepicker({
showWeek:true,
yearSuffix:"-CE",
showAnim: "slide"
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-11"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −
Enter Date:
In the above example, you can see that week numbers are displayed on the left side of datepicker as showWeek is set to true. The year is have a suffix of "-CE".
The datepicker (action, params) method can perform an action on the calendar, such as such as selecting a new date. The action is specified as a string in the first argument and optionally, one or more params can be provided based on the given action.
$(selector, context).datepicker ("action", [params]);
The following table lists the actions for this method −
This action removes the datepicker functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments.
Action - destroy()
This action removes the datepicker functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments.
Syntax
$(".selector").datepicker("destroy");
This action displays datepicker in a jQuery UI dialog box.
Action - dialog( date [, onSelect ] [, settings ] [, pos ] )
This action displays datepicker in a jQuery UI dialog box . Where −
date is the initial date.
date is the initial date.
onSelect is a callback function when a date is selected. The function receives the date text and date picker instance as parameters.
onSelect is a callback function when a date is selected. The function receives the date text and date picker instance as parameters.
settings is the new settings for the date picker.
settings is the new settings for the date picker.
pos is the position of the top/left of the dialog as [x, y] or a MouseEvent that contains the coordinates. If not specified the dialog is centered on the screen.
pos is the position of the top/left of the dialog as [x, y] or a MouseEvent that contains the coordinates. If not specified the dialog is centered on the screen.
Syntax
$(".selector").datepicker( "dialog", "10/12/2012" );
This action returns the Date corresponding to the selected date. This method does not accept any arguments.
Action - getDate()
This action returns the Date corresponding to the selected date. This method does not accept any arguments.
Syntax
$(".selector").datepicker("getDate");
This action closes the previously opened date picker. This method does not accept any arguments.
Action - hide()
This action closes the previously opened date picker. This method does not accept any arguments.
Syntax
$(".selector").datepicker("hide");
This action checks if the date picker funcitonality is disabled. This method does not accept any arguments.
Action - isDisabled()
This action checks if the date picker funcitonality is disabled. This method does not accept any arguments.
Syntax
$(".selector").datepicker("isDisabled");
This action retrieves the value currently associated with the specified optionName.
Action - option( optionName )
This action retrieves the value currently associated with the specified optionName.
Syntax
$(".selector").datepicker( "option", "disabled");
This action gets an object containing key/value pairs representing the current datepicker options hash. This method does not accept any arguments.
Action - option()
This action gets an object containing key/value pairs representing the current datepicker options hash. This method does not accept any arguments.
Syntax
var options = $( ".selector" ).datepicker( "option" );
This action sets the value of the datepicker option associated with the specified optionName.
Action - option( optionName, value )
This action sets the value of the datepicker option associated with the specified optionName.
Syntax
$(".selector").datepicker( "option", "disabled", true );
This action sets one or more options for the datepicker.
Action - option( options )
This action sets one or more options for the datepicker.
Syntax
$(".selector").datepicker("option", { disabled: true });
This action redraws the date picker, after having made some external modifications. This method does not accept any arguments.
Action - refresh()
This action redraws the date picker, after having made some external modifications. This method does not accept any arguments.
Syntax
$(".selector").datepicker("refresh");
This action sets the specified date as the current date of the datepicker.
Action - setDate()
This action sets the specified date as the current date of the datepicker.
Syntax
$(".selector").datepicker("setDate", "10/12/2012");
This action opens the date picker. If the datepicker is attached to an input, the input must be visible for the datepicker to be shown. This method does not accept any arguments.
Action - show()
This action opens the date picker. If the datepicker is attached to an input, the input must be visible for the datepicker to be shown. This method does not accept any arguments.
Syntax
$(".selector").datepicker("show");
This action returns a jQuery object containing the datepicker.
Action - widget()
This action returns a jQuery object containing the datepicker.
Syntax
$(".selector").datepicker("widget");
The following examples show the use of some of the actions listed in the above table.
Now let us see an example using the actions from the above table. The following example demonstrates the use of actions setDate.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-12" ).datepicker();
$( "#datepicker-12" ).datepicker("setDate", "10w+1");
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-12"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output −
Enter Date:
The following example demonstrates the use of action show.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker-13" ).datepicker();
$( "#datepicker-13" ).datepicker("show");
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type = "text" id = "datepicker-13"></p>
</body>
</html>
Let us save the above code in an HTML file datepickerexample.htm and open it in a standard browser which supports javascript, you must also see the following output −
Enter Date:
There are no datepicker event methods as of now!
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2476,
"s": 2264,
"text": "Datepickers in jQueryUI allow users to enter dates easily and visually. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily."
},
{
"code": null,
"e": 2720... |
Difference between <figure> & <img> tags in HTML - GeeksforGeeks | 02 Sep, 2021
In this article, we will learn about the <figure> & <img> tag along with its implementation. We will also learn the differences between them. Let’s begin the discussion with the figure tag in HTML.
HTML <figure> Tag: The <figure> tag in HTML5 is used to add self-contained content like illustrations, diagrams, photos, or codes listing in a document. It is related to the main flow, but it can be used in any position of a document and the figure goes with the flow of the document and if remove it then it should not affect the flow of the document. In simple words, the figure tag is used to semantically organize the content of images, videos, audios or even charts or tables, block of codes in the HTML document.
Syntax:
<figure>
<img src="url">
<figcaption>content</figcaption>
</figure>
Attributes: It contains mostly two tags which are given below:
img src: This tag is used to add an image source in the document.
figcaption: This tag is used to set the caption to the image. It is optional to use.
Example: This example illustrates the use of the <figure> tag along with src, width, height & alt attributes.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> figure { border: 2px solid black; padding: 5px; } </style> </head> <body> <figure> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210827151326/gfg-200x200.png" alt="image" width="200px" height="200px"/> <figcaption>Geeks For Geeks</figcaption> </figure> </body></html>
Output: In this case the <figure> tag, it has made all the changes, as the image with caption is properly aligned with some space away from the margin. The image and caption are part of each other. The border is added to both <figure> tag and <figcaption> tag, both have occupied the border. <figure> tag is inline element.
<figure> tag
HTML <img> Tag: HTML <img> tag is used to add image or to set the background in the webpage/website. Nowadays website does not directly add images to a web page, as the images are linked to web pages by using the <img> tag which holds space for the image.
Syntax :
<img src="url" alt="some_text">
Attribute: It contains the following attribute values:
src: It is used to specifies the URL path of the source image.
alt: It is used to specifies an alternate text for the image if the image for some reason cannot be displayed.
Example: In this example, we are using the <img> tag along with src, width, height, and alt attributes.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> img { border: 2px solid black; padding: 5px; } </style> </head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210827151326/gfg-200x200.png" alt="image" width="200px" height="200px"/> <p>Geeks For Geeks</p> </body></html>
Output: In the case of the <img> tag, it is not properly aligned and is very close to the margin, and the caption is away from the image. The image and caption are not part of each other. The border is not the part of both image and caption. <img> tag is an inline element but when we specify width and height it becomes a block element.
<img> tag
Difference between <figure> & <img> tags:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
nitupandel001
HTML-Questions
HTML-Tags
Picked
Difference Between
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Mealy machine and Moore machine
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 24884,
"s": 24856,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 25082,
"s": 24884,
"text": "In this article, we will learn about the <figure> & <img> tag along with its implementation. We will also learn the differences between them. Let’s begin the discu... |
Find all the numbers in a string using regular expression in Python | Extracting only the numbers from a text is a very common requirement in python data analytics. It is done easily using the python regular expression library. This library helps us define the patterns for digits which can be extracted as substrings.
In the below example we use the function findall() from the re module. The parameters to these function are the pattern which we want to extract and the string from which we want to extract. Please note with below example we get only the digits and not the decimal points or the negative signs.
import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list = re.findall(r'\d+', str)
print(num_list)
Running the above code gives us the following result −
Enter a String with numbers:
Go to 13.8 miles and then -4.112 miles.
['13', '8', '4', '112']
We can expand the search pattern to include the decimal points and the negative or positive signs also in the search result.
import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list=re.findall(r'[-+]?[.]?[\d]+',str)
print(num_list)
Running the above code gives us the following result −
Enter a String with numbers:
Go to 13.8 miles and then -4.112 miles.
['13', '.8', '-4', '.112'] | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "Extracting only the numbers from a text is a very common requirement in python data analytics. It is done easily using the python regular expression library. This library helps us define the patterns for digits which can be extracted as substrings."
}... |
Tryit Editor v3.7 | Tryit: SVG rectangle with rounded corners | [] |
BufferedReader Class lines() method in Java with Examples - GeeksforGeeks | 28 Jan, 2021
BufferedReader.lines() is the method of the Java Buffered Reader Class in the Java Library which returns lines in terms of Stream and from this Buffered Reader class. With the help of the stream, there are a lot of methods that mimic the output according to our needs.
Syntax:
BufferedReader.lines() : Stream<String>
Parameters: This method does not take any kind of parameter.
Return: This method returns the stream of lines in terms of Stream and the Generic Type Change the stream into String.
Exception: IOException will be thrown when accessing the underlying BufferedReader which is wrapped in an UncheckedIOException.
Example: Find the line containing Hello as a word it will only work in a continuous scanning
The directory contains one txt files named as GFG.txt
The text File contains two lines:
Java
// Java program to demonstrate the continuous scanning// by BufferedReader.lines() method and return the stream// of lines that contains the specific word import java.io.*;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.*;import java.util.Arrays;import java.util.List;import java.util.stream.Stream; class GFG { public static void main(String[] args) { FileReader f= new FileReader("location of the file"); BufferedReader b = new BufferedReader(f); // taking the stream as a string Stream<String> i = b.lines(); i.filter(line -> line.contains("Hello")).findAny().ifPresent(System.out::println); // filter the stream that line contains Hello is // preset output b.close(); f.close(); }}
Output:
Hello this is the first line. Hello this is the second line.
Java-BufferReader
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 24218,
"s": 23948,
"text": "BufferedReader.lines() is the method of the Java Buffered Reader Class in the Java Library which returns lines in terms of Stream and from this Buffered Reader cl... |
Apply an IF condition to every element in an HTML table with JavaScript? | For this, you can use document.querySelectorAll.forEach().
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<table>
<tr>
<td class="demo"> Java </td>
</tr>
<tr>
<td class="demo"> MySQL </td>
</tr>
<tr>
</tr>
</table>
</body>
<script>
document.querySelectorAll(".demo").forEach(function (obj) {
if (obj.innerText.trim() === "MySQL") {
obj.innerText = "Javascript";
}
if (obj.innerText.trim() === "MongoDB") {
obj.innerText = "Python";
}
});
</script>
</html>
To run the above program, save the file name anyName.html(index.html). Right click on the file
and select the option “Open with live server” in VS Code editor.
This will produce the following output − | [
{
"code": null,
"e": 1121,
"s": 1062,
"text": "For this, you can use document.querySelectorAll.forEach()."
},
{
"code": null,
"e": 1145,
"s": 1121,
"text": "Following is the code −"
},
{
"code": null,
"e": 2006,
"s": 1145,
"text": "<!DOCTYPE html>\n<html lang=... |
Set width and precision to format output in Java | Set width in output as shown below. Here, %10 sets a 10 character field
System.out.printf("d1 = %10.2f \nd2 = %8g", d1, d2);
Above, the value after the decimal is for decimal places i.e. 5.3 is for 3 decimal places −
System.out.printf("\nd1 = %5.3f \nd2 = %2.5f", d1, d2);
The following is an example −
Live Demo
public class Demo {
public static void main(String[] args) throws Exception {
double d1 = 399.8877;
double d2 = 298.87690;
System.out.printf("d1 = %10.2f \nd2 = %8g", d1, d2);
System.out.printf("\nd1 = %5.3f \nd2 = %2.5f", d1, d2);
}
}
d1 = 399.89
d2 = 298.877
d1 = 399.888
d2 = 298.87690 | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "Set width in output as shown below. Here, %10 sets a 10 character field"
},
{
"code": null,
"e": 1187,
"s": 1134,
"text": "System.out.printf(\"d1 = %10.2f \\nd2 = %8g\", d1, d2);"
},
{
"code": null,
"e": 1279,
"s": 11... |
Swing Examples - Using Date Format in JFormattedTextField | Following example showcase how to create and use JFormattedTextField to specify a Date format on Text Fields in Swing based application.
We are using the following APIs.
JFormattedTextField − To create a formatted text field.
JFormattedTextField − To create a formatted text field.
DateFormat − To provide Date format to JFormattedTextField.
DateFormat − To provide Date format to JFormattedTextField.
SimpleDateFormat(patten) − to get a desired date format of date pattern.
SimpleDateFormat(patten) − to get a desired date format of date pattern.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingTester implements PropertyChangeListener {
private static JFormattedTextField principleTextField;
private static JFormattedTextField rateTextField;
private static JFormattedTextField yearsTextField;
private static JFormattedTextField amountTextField;
public static void main(String[] args) {
SwingTester tester = new SwingTester();
createWindow(tester);
}
private static void createWindow(SwingTester tester) {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame, tester);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame, SwingTester tester) {
JPanel panel = new JPanel();
LayoutManager layout = new GridLayout(6,2);
panel.setLayout(layout);
panel.setSize(300, 200);
panel.setBorder(BorderFactory.createTitledBorder("Formats"));
NumberFormat principleFormat = NumberFormat.getNumberInstance();
principleTextField = new JFormattedTextField(principleFormat);
principleTextField.setName("Principle");
principleTextField.setColumns(10);
JLabel principleLabel = new JLabel("Principle:");
principleLabel.setLabelFor(principleTextField);
principleTextField.setValue(new Double(100000));
principleTextField.addPropertyChangeListener("value", tester);
NumberFormat rateFormat = NumberFormat.getPercentInstance();
rateFormat.setMinimumFractionDigits(2);
rateTextField = new JFormattedTextField(rateFormat);
rateTextField.setName("Rate");
rateTextField.setColumns(10);
JLabel rateLabel = new JLabel("Interest Rate:");
rateLabel.setLabelFor(rateTextField);
rateTextField.setValue(new Double(0.1));
rateTextField.addPropertyChangeListener("value", tester);
yearsTextField = new JFormattedTextField();
yearsTextField.setName("Years");
yearsTextField.setColumns(10);
JLabel yearLabel = new JLabel("Year(s):");
yearLabel.setLabelFor(yearsTextField);
yearsTextField.setValue(new Double(1));
yearsTextField.addPropertyChangeListener("value", tester);
NumberFormat amountFormat = NumberFormat.getCurrencyInstance();
amountTextField = new JFormattedTextField(amountFormat);
amountTextField.setName("Amount");
amountTextField.setColumns(10);
amountTextField.setEditable(false);
JLabel amountLabel = new JLabel("Amount:");
amountLabel.setLabelFor(amountTextField);
amountTextField.setValue(new Double(110000));
DateFormat dateFormat = new SimpleDateFormat("dd MMM YYYY");
JFormattedTextField today = new JFormattedTextField(dateFormat);
today.setName("Today");
today.setColumns(10);
today.setEditable(false);
JLabel todayLabel = new JLabel("Date:");
todayLabel.setLabelFor(today);
today.setValue(new Date());
panel.add(principleLabel);
panel.add(principleTextField);
panel.add(rateLabel);
panel.add(rateTextField);
panel.add(yearLabel);
panel.add(yearsTextField);
panel.add(amountLabel);
panel.add(amountTextField);
panel.add(todayLabel);
panel.add(today);
JPanel mainPanel = new JPanel();
mainPanel.add(panel);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
double amount, rate, years, principle;
principle = ((Number)principleTextField.getValue()).doubleValue();
rate = ((Number)rateTextField.getValue()).doubleValue() * 100;
years = ((Number)yearsTextField.getValue()).doubleValue();
amount = principle + principle * rate * years / 100;
amountTextField.setValue(new Double(amount));
}
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2176,
"s": 2039,
"text": "Following example showcase how to create and use JFormattedTextField to specify a Date format on Text Fields in Swing based application."
},
{
"code": null,
"e": 2209,
"s": 2176,
"text": "We are using the following APIs."
},
{
... |
Solution of system of linear equation in MATLAB - GeeksforGeeks | 28 Jul, 2020
Let us see how to solve a system of linear equations in MATLAB. Here are the various operators that we will be deploying to execute our task :
\ operator : A \ B is the matrix division of A into B, which is roughly the same as INV(A) * B. If A is an NXN matrix and B is a column vector with N components or a matrix with several such columns, then X = A \ B is the solution to the equation A * X = B. A warning message is printed if A is badly scaled or nearly singular. A\EYE(SIZE(A)) produces the inverse of A.
linsolve operator : X = LINSOLVE(A, B) solves the linear system A * X = B using LU factorization with partial pivoting when A is square, and QR factorization with column pivoting. A warning is given if A is ill conditioned for square matrices and rank deficient for rectangular matrices.
Example 1 : Non-homogeneous System Ax = b, where A is a square and is invertible. In our example we will consider the following equations :
2x + y - z = 7
x -2y + 5z = -13
3x + 5y - 4z = 18
We will convert these equations into matrices A and b :
% declaring the matrices based on the equationsA = [2 1 -1; 1 -2 5; 3 5 -4]b = [7; -13; 18]
Output :
A =
2 1 -1
1 -2 5
3 5 -4
b =
7
-13
18
Now we will create an augmented matrix Ab. We will compare the ranks of Ab and A, if the ranks are equal then a unique solution exists.
% creating augmented matrixAb = [A b] % checking the ranksif rank(A) == rank(Ab) display("Unique solution exists")else display("Unique solution does not exist") end
Output :
Ab =
2 1 -1 7
1 -2 5 -13
3 5 -4 18
Unique solution exists
Now we can find the solution to this system of equations by using 3 methods:
conventional way : inv(A) * b
using mid-divide routine : A \ b
using linsolve routine : linsolve(A, b)
% conventional way of finding solutionx_inv = inv(A) * b % using mid-divide routine of MATLABx_bslash = A \ b % using linsolve routine of MATLABx_linsolve = linsolve(A, b)
Output :
x_inv =
2.0000e+00
8.8818e-16
-3.0000e+00
x_bslash =
2.0000e+00
9.6892e-16
-3.0000e+00
x_linsolve =
2.0000e+00
9.6892e-16
-3.0000e+00
We can verify the correctness of the solution by finding the error using A * x - b. The error should be 0.
% check for errorsEr1 = A * x_inv - b Er2 = A * x_bslash - b Er3 = A * x_linsolve - b
Output :
Er1 =
-8.8818e-16
-3.5527e-15
0.0000e+00
Er2 =
-1.7764e-15
-1.7764e-15
0.0000e+00
Er3 =
-1.7764e-15
-1.7764e-15
0.0000e+00
As all the errors are close to 0, we can say that the solution is correct.
Example 2 : Non-homogeneous system Ax = b, where A is a square and it is not invertible. In our example we will consider the following equations :
2x + 4y + 6z = 7
3x -2y + 1z = 2
1x + 2y + 3z = 5
% declaring the matrices based on the equationsA = [2 4 6; 3 -2 1; 1 2 3]b = [7; 2; 5] % creating augmented matrixAb = [A b] % checking the ranksif rank(A) == rank(Ab) display("Unique solution exists")else display("Unique solution does not exist") end % conventional way of finding solution% gives warning and wrong answer.x_inv = inv(A) * b % using mid-divide routine of MATLAB% this too gives warning and wrong answer. x_bslash = A \ b % check for errorsEr1 = A * x_inv - b Er2 = A * x_bslash - b
Output :
A =
2 4 6
3 -2 1
1 2 3
b =
7
2
5
Ab =
2 4 6 7
3 -2 1 2
1 2 3 5
Unique solution does not exist
warning: matrix singular to machine precision
warning: called from
testing at line 17 column 7
x_inv =
Inf
Inf
Inf
warning: matrix singular to machine precision
warning: called from
testing at line 21 column 10
x_bslash =
-Inf
-Inf
Inf
Er1 =
Inf
NaN
Inf
Er2 =
NaN
NaN
NaN
Example 3 : Non-homogeneous system Ax = b where A is not a square. In our example we will consider the following equations :
2a + c - d + e = 2
a + c - d + e = 1
12a + 2b + 8c + 2e = 12
% declaring the matrices based on the equationsA = [2 0 1 -1 1; 1 0 1 -1 1; 12 2 8 0 2] b = [2; 1; 12] % creating augmented matrixAb = [A b] % checking the ranksif rank(A) == rank(Ab) display("Solution exists")else display("Solution does not exist") end % checking for unique solutionif rank(A) == 5 display("Unique solution exists")else display("Unique solution does not exist") end
Output :
A =
2 0 1 -1 1
1 0 1 -1 1
12 2 8 0 2
b =
2
1
12
Ab =
2 0 1 -1 1 2
1 0 1 -1 1 1
12 2 8 0 2 12
Solution exists
Unique solution does not exist
Example 4 : Homogeneous system Ax = 0 where A is a square and is invertible. In our example we will consider the following equations :
6x + 2y + 3z = 0
4x - y + 2z = 0
2x + y + 5z = 0
% declaring the matrices based on the equationsA = [6 2 3; 4 -1 2; 2 1 5] b = [0; 0; 0] % checking for unique solutionif rank(A) == 3 display("Unique solution exists")else display("Unique solution does not exist") endif % trivial solutionx = A \ b % getting a null set. % this is obvious as A is invertible. % so its null space contains only zero vectorx = null(A)
Output :
A =
6 2 3
4 -1 2
2 1 5
b =
0
0
0
Unique solution exists
x =
0
0
0
x = [](3x0)
Example 5 : Homogeneous system Ax = 0 where A is a square and is not invertible. In our example we will consider the following equations :
1x + 2y + 3z = 0
4x + 5y + 6z = 0
7x + 8y + 9z = 0
% declaring the matrices based on the equationsA = [1 2 3; 4 5 6; 7 8 9] b = [0; 0; 0] % checking for unique solutionif rank(A) == 3 display("Unique solution exists")else display("Unique solution does not exist") endif % trivial solution with warningx = A \ b % this will return a set containing % only one basis vector of null space of A% the null space of A is spanned by this vector% hence this vector or its scalar multiple % is the solution of the given homogeneous systemx = null(A) % finding the errorsErr = A*x - b
Output :
A =
1 2 3
4 5 6
7 8 9
b =
0
0
0
Unique solution does not exist
warning: matrix singular to machine precision, rcond = 1.54198e-18
warning: called from
testing at line 13 column 3
x =
0
0
0
x =
0.40825
-0.81650
0.40825
Err =
-1.3323e-15
-4.4409e-16
4.4409e-16
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
System Design Tutorial
Copying Files to and from Docker Containers
Python | Decision tree implementation
Decision Tree Introduction with example
ML | Underfitting and Overfitting
ML | Label Encoding of datasets in Python
Clustering in Machine Learning
Docker - COPY Instruction
KDD Process in Data Mining | [
{
"code": null,
"e": 24575,
"s": 24547,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 24718,
"s": 24575,
"text": "Let us see how to solve a system of linear equations in MATLAB. Here are the various operators that we will be deploying to execute our task :"
},
{
"code"... |
Introduction to Ethical Hacking - GeeksforGeeks | 05 Sep, 2019
Ethical Hacking:To crack passwords or to steal data? No, it is much more than that. Ethical hacking is to scan vulnerabilities and to find potential threats on a computer or networks. An ethical hacker finds the weak points or loopholes in a computer, web applications or network and reports them to the organization. So, let’s explore more about Ethical Hacking step-by-step.
These are various types of hackers:
(1) White Hat Hackers (Cyber-Security Hacker)
(2) Black Hat Hackers (Cracker)
(3) Gray Hat Hackers (Both)
Let’s summarize them one-by-one.
White Hat Hackers:Here, we look for bugs and ethically report it to the organization. We are authorized as a user to test for bugs in a website or network and report it to them. White hat hackers generally get all the needed information about the application or network to test for, from the organization itself. They use their skills to test it before the website goes live or attacked by malicious hackers.Black Hat Hackers:Here, the organization doesn’t allow the user to test it. They unethically enter inside the website and steal data from the admin panel or manipulate the data. They only focus on themselves and the advantages they will get from the personal data for personal financial gain. They can cause major damage to the company by altering the functions which lead to the loss of the company at a much higher extent. This can even lead you to extreme consequences.Grey Hat Hackers:They sometimes access to the data and violates the law. But never have the same intention as Black hat hackers, they often operate for the common good. The main difference is that they exploit vulnerability publicly whereas white hat hackers do it privately for the company.
White Hat Hackers:Here, we look for bugs and ethically report it to the organization. We are authorized as a user to test for bugs in a website or network and report it to them. White hat hackers generally get all the needed information about the application or network to test for, from the organization itself. They use their skills to test it before the website goes live or attacked by malicious hackers.
Black Hat Hackers:Here, the organization doesn’t allow the user to test it. They unethically enter inside the website and steal data from the admin panel or manipulate the data. They only focus on themselves and the advantages they will get from the personal data for personal financial gain. They can cause major damage to the company by altering the functions which lead to the loss of the company at a much higher extent. This can even lead you to extreme consequences.
Grey Hat Hackers:They sometimes access to the data and violates the law. But never have the same intention as Black hat hackers, they often operate for the common good. The main difference is that they exploit vulnerability publicly whereas white hat hackers do it privately for the company.
Cyber-security
Information-Security
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Working with csv files in Python
Types of Software Testing
Working with PDF files in Python
10 Best IDE For Web Developers in 2022
Top 10 System Design Interview Questions and Answers | [
{
"code": null,
"e": 24743,
"s": 24715,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 25120,
"s": 24743,
"text": "Ethical Hacking:To crack passwords or to steal data? No, it is much more than that. Ethical hacking is to scan vulnerabilities and to find potential threats on a c... |
IBM HR Analytics on Employee Attrition & Performance using Random Forest Classifier - GeeksforGeeks | 17 Aug, 2020
Attrition is a problem that impacts all businesses, irrespective of geography, industry and size of the company. It is a major problem to an organization, and predicting turnover is at the forefront of the needs of Human Resources (HR) in many organizations. Organizations face huge costs resulting from employee turnover. With advances in machine learning and data science, it’s possible to predict the employee attrition, and we will predict using Random Forest Classifier algorithm.
Dataset: The dataset that is published by the Human Resource department of IBM is made available at Kaggle.
Code: Implementation of Random Forest Classifier algorithm for classification.
Code: Loading the Libraries
Python3
# performing linear algebraimport numpy as np # data processingimport pandas as pd # visualisationimport matplotlib.pyplot as pltimport seaborn as sns % matplotlib inline
Code: Importing the dataset
Python3
dataset = pd.read_csv("WA_Fn-UseC_-HR-Employee-Attrition.csv")print (dataset.head)
Output :
Code: Information about the dataset
Python3
dataset.info()
Output :
RangeIndex: 1470 entries, 0 to 1469
Data columns (total 35 columns):
Age 1470 non-null int64
Attrition 1470 non-null object
BusinessTravel 1470 non-null object
DailyRate 1470 non-null int64
Department 1470 non-null object
DistanceFromHome 1470 non-null int64
Education 1470 non-null int64
EducationField 1470 non-null object
EmployeeCount 1470 non-null int64
EmployeeNumber 1470 non-null int64
EnvironmentSatisfaction 1470 non-null int64
Gender 1470 non-null object
HourlyRate 1470 non-null int64
JobInvolvement 1470 non-null int64
JobLevel 1470 non-null int64
JobRole 1470 non-null object
JobSatisfaction 1470 non-null int64
MaritalStatus 1470 non-null object
MonthlyIncome 1470 non-null int64
MonthlyRate 1470 non-null int64
NumCompaniesWorked 1470 non-null int64
Over18 1470 non-null object
OverTime 1470 non-null object
PercentSalaryHike 1470 non-null int64
PerformanceRating 1470 non-null int64
RelationshipSatisfaction 1470 non-null int64
StandardHours 1470 non-null int64
StockOptionLevel 1470 non-null int64
TotalWorkingYears 1470 non-null int64
TrainingTimesLastYear 1470 non-null int64
WorkLifeBalance 1470 non-null int64
YearsAtCompany 1470 non-null int64
YearsInCurrentRole 1470 non-null int64
YearsSinceLastPromotion 1470 non-null int64
YearsWithCurrManager 1470 non-null int64
dtypes: int64(26), object(9)
memory usage: 402.0+ KB
Code: Visualizing the data
Python3
# heatmap to check the missing valueplt.figure(figsize =(10, 4))sns.heatmap(dataset.isnull(), yticklabels = False, cbar = False, cmap ='viridis')
Output:
So, we can see that there are no missing values in the dataset. This is a Binary Classification Problem, so the Distribution of instances among the 2 classes, is visualized below :
Code:
Python3
sns.set_style('darkgrid')sns.countplot(x ='Attrition', data = dataset)
Output:
Code:
Python3
sns.lmplot(x = 'Age', y = 'DailyRate', hue = 'Attrition', data = dataset)
Output:
Code:
Python3
plt.figure(figsize =(10, 6))sns.boxplot(y ='MonthlyIncome', x ='Attrition', data = dataset)
Output:
Code: Preprocessing the data
In the dataset there are 4 irrelevant columns, i.e:EmployeeCount, EmployeeNumber, Over18, and StandardHour. So, we have to remove these for more accuracy.
Python3
dataset.drop('EmployeeCount', axis = 1, inplace = True)dataset.drop('StandardHours', axis = 1, inplace = True)dataset.drop('EmployeeNumber', axis = 1, inplace = True)dataset.drop('Over18', axis = 1, inplace = True) print(dataset.shape)
Output:
(1470, 31)
So, we have removed the irrelevant column.
Code: Input and Output data
Python3
y = dataset.iloc[:, 1]X = dataset X.drop('Attrition', axis = 1, inplace = True)
Code: Label Encoding
Python3
from sklearn.preprocessing import LabelEncoderlb = LabelEncoder()y = lb.fit_transform(y)
In the dataset there are 7 categorical data, so we have to change them to int data, i.e we have to create 7 dummy variables for better accuracy.
Code: Dummy variable creation
Python3
dum_BusinessTravel = pd.get_dummies(dataset['BusinessTravel'], prefix ='BusinessTravel') dum_Department = pd.get_dummies(dataset['Department'], prefix ='Department') dum_EducationField = pd.get_dummies(dataset['EducationField'], prefix ='EducationField') dum_Gender = pd.get_dummies(dataset['Gender'], prefix ='Gender', drop_first = True) dum_JobRole = pd.get_dummies(dataset['JobRole'], prefix ='JobRole') dum_MaritalStatus = pd.get_dummies(dataset['MaritalStatus'], prefix ='MaritalStatus') dum_OverTime = pd.get_dummies(dataset['OverTime'], prefix ='OverTime', drop_first = True) # Adding these dummy variable to input XX = pd.concat([x, dum_BusinessTravel, dum_Department, dum_EducationField, dum_Gender, dum_JobRole, dum_MaritalStatus, dum_OverTime], axis = 1) # Removing the categorical dataX.drop(['BusinessTravel', 'Department', 'EducationField', 'Gender', 'JobRole', 'MaritalStatus', 'OverTime'], axis = 1, inplace = True) print(X.shape)print(y.shape)
Output:
(1470, 49)
(1470, )
Code: Splitting data to training and testing
Python3
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.25, random_state = 40)
So, the preprocessing is done, now we have to apply the Random forest classifier to the dataset.
Code: Model Execution
Python3
from sklearn.model_selection import cross_val_predict, cross_val_scorefrom sklearn.metrics import accuracy_score, classification_report, confusion_matrixfrom sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(n_estimators=10, criterion='entropy')rf.fit(X_train, y_train)y_pred = rf.predict(X_test) def print_score(clf, X_train, y_train, X_test, y_test, train=True): if train: print("Train Result:") print("------------") print("Classification Report: \n {}\n".format(classification_report( y_train, clf.predict(X_train)))) print("Confusion Matrix: \n {}\n".format(confusion_matrix( y_train, clf.predict(X_train)))) res = cross_val_score(clf, X_train, y_train, cv=10, scoring='accuracy') print("Average Accuracy: \t {0:.4f}".format(np.mean(res))) print("Accuracy SD: \t\t {0:.4f}".format(np.std(res))) print("----------------------------------------------------------") elif train == False: print("Test Result:") print("-----------") print("Classification Report: \n {}\n".format( classification_report(y_test, clf.predict(X_test)))) print("Confusion Matrix: \n {}\n".format( confusion_matrix(y_test, clf.predict(X_test)))) print("accuracy score: {0:.4f}\n".format( accuracy_score(y_test, clf.predict(X_test)))) print("-----------------------------------------------------------") print_score(rf, X_train, y_train, X_test, y_test, train=True) print_score(rf, X_train, y_train, X_test, y_test, train=False)
Output:
Train Result:
------------
Classification Report:
precision recall f1-score support
0 0.98 1.00 0.99 988
1 1.00 0.90 0.95 188
accuracy 0.98 1176
macro avg 0.99 0.95 0.97 1176
weighted avg 0.98 0.98 0.98 1176
Confusion Matrix:
[[988 0]
[ 19 169]]
Average Accuracy: 0.8520
Accuracy SD: 0.0122
----------------------------------------------------------
Test Result:
-----------
Classification Report:
precision recall f1-score support
0 0.86 0.98 0.92 245
1 0.71 0.20 0.32 49
accuracy 0.85 294
macro avg 0.79 0.59 0.62 294
weighted avg 0.84 0.85 0.82 294
Confusion Matrix:
[[241 4]
[ 39 10]]
accuracy score: 0.8537
-----------------------------------------------------------
Code: Key features for deciding the result
Python3
pd.Series(rf.feature_importances_, index = X.columns).sort_values(ascending = False).plot(kind = 'bar', figsize = (14,6));
Output:
So, According to Random forest classifier the most important feature for predicting the result is Monthly Income and the least important feature is jobRole_Manager.
python-utility
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation functions in Neural Networks
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
Python | Decision tree implementation
Search Algorithms in AI
ML | Underfitting and Overfitting
Clustering in Machine Learning
Intuition of Adam Optimizer
Random Forest Regression in Python
Elbow Method for optimal value of k in KMeans | [
{
"code": null,
"e": 25979,
"s": 25951,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 26466,
"s": 25979,
"text": "Attrition is a problem that impacts all businesses, irrespective of geography, industry and size of the company. It is a major problem to an organization, and pred... |
JavaFX | DatePicker with examples - GeeksforGeeks | 23 Oct, 2019
DatePicker is a part of the JavaFX package, DatePicker allows to select the date from the popup calendar or type the text manually in the text field of date-picker.
Constructor of the DatePicker class are :
DatePicker():Creates a default DatePicker instance with a null date value set.DatePicker(LocalDate l):Creates a DatePicker instance and sets the value to the given date.
DatePicker():Creates a default DatePicker instance with a null date value set.
DatePicker(LocalDate l):Creates a DatePicker instance and sets the value to the given date.
Commonly used methods:
Below programs illustrate the DatePicker Class:
Program to create a date picker and display it in stage: This program creates a Date Picker indicated by the name d. The DatePicker will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results.// Java Program to create a date picker// and display it in stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class date_picker_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating date picker"); // create a tile pane TilePane r = new TilePane(); // create a date picker DatePicker d = new DatePicker(); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create a date picker and create a label to show the date: This program creates a DatePicker indicated by the name d. The Date Picker will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show which date is choosed. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the date picker events. The event handler would be added to the button using setOnAction() function.The setShowWeekNumbers() will set the date picker to show week number of respective weeks.// Java Program to create a date picker// and create a label to show the dateimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.*;import java.time.chrono.*;public class date_picker_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating date picker"); // create a tile pane TilePane r = new TilePane(); // label to show the date Label l = new Label("no date selected"); // create a date picker DatePicker d = new DatePicker(); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the date picker value LocalDate i = d.getValue(); // get the selected date l.setText("Date :" + i); } }; // show week numbers d.setShowWeekNumbers(true); // when datePicker is pressed d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note : The above programs might not run in an online IDE please use an offline IDE.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/DatePicker.htmlMy Personal Notes
arrow_drop_upSave
Program to create a date picker and display it in stage: This program creates a Date Picker indicated by the name d. The DatePicker will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button inside the scene. Finally, the show() method is called to display the final results.// Java Program to create a date picker// and display it in stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class date_picker_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating date picker"); // create a tile pane TilePane r = new TilePane(); // create a date picker DatePicker d = new DatePicker(); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a date picker// and display it in stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.LocalDate;public class date_picker_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating date picker"); // create a tile pane TilePane r = new TilePane(); // create a date picker DatePicker d = new DatePicker(); // add button and label r.getChildren().add(d); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Program to create a date picker and create a label to show the date: This program creates a DatePicker indicated by the name d. The Date Picker will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show which date is choosed. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the date picker events. The event handler would be added to the button using setOnAction() function.The setShowWeekNumbers() will set the date picker to show week number of respective weeks.// Java Program to create a date picker// and create a label to show the dateimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.*;import java.time.chrono.*;public class date_picker_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating date picker"); // create a tile pane TilePane r = new TilePane(); // label to show the date Label l = new Label("no date selected"); // create a date picker DatePicker d = new DatePicker(); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the date picker value LocalDate i = d.getValue(); // get the selected date l.setText("Date :" + i); } }; // show week numbers d.setShowWeekNumbers(true); // when datePicker is pressed d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note : The above programs might not run in an online IDE please use an offline IDE.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/DatePicker.htmlMy Personal Notes
arrow_drop_upSave
// Java Program to create a date picker// and create a label to show the dateimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;import java.time.*;import java.time.chrono.*;public class date_picker_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating date picker"); // create a tile pane TilePane r = new TilePane(); // label to show the date Label l = new Label("no date selected"); // create a date picker DatePicker d = new DatePicker(); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the date picker value LocalDate i = d.getValue(); // get the selected date l.setText("Date :" + i); } }; // show week numbers d.setShowWeekNumbers(true); // when datePicker is pressed d.setOnAction(event); // add button and label r.getChildren().add(d); r.getChildren().add(l); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note : The above programs might not run in an online IDE please use an offline IDE.
Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/DatePicker.html
ManasChhabra2
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java | [
{
"code": null,
"e": 25321,
"s": 25293,
"text": "\n23 Oct, 2019"
},
{
"code": null,
"e": 25486,
"s": 25321,
"text": "DatePicker is a part of the JavaFX package, DatePicker allows to select the date from the popup calendar or type the text manually in the text field of date-picker... |
How to Limit Query Results in SQL? - GeeksforGeeks | 14 Sep, 2021
In this article, we will learn how to limit query results in SQL using different examples. A MySQL supports the LIMIT clause to select a limited number of records. If we want to LIMIT the number of results that will return us a number of rows then we simply use the LIMIT command.
Use the below SQL statement to create a database called geeks:
Query:
CREATE DATABASE geeks;
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Query:
CREATE TABLE Participant (
ID INTEGER PRIMARY KEY,
Name TEXT NOT NULL,
Percent INTEGER NOT NULL,
Branch TEXT NOT NULL
);
Query:
INSERT INTO Participant VALUES (55, 'BB',81 ,'Civil');
INSERT INTO Participant VALUES (56, 'NN',75 ,'IT');
INSERT INTO Participant VALUES (57, 'RR',100 ,'CSE');
INSERT INTO Participant VALUES (58, 'SS',94 ,'Civil');
We can use the below statement to see the contents of the created table:
Query:
SELECT * FROM Participant;
Now let’s see how to use limit query here. For this we use SELECT with LIMIT and ORDER BY statement in MySQL.
Syntax:
SELECT column1, column2, ...
FROM table_name
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]]
LIMIT count;
In the above syntax, WHERE conditions are optional conditions that must be true for the records to be selected. ORDER BY expression is an optional statement in the query used to return the result in either ascending or descending order according to the keyword (ASC or DESC). The LIMIT count is used with the SELECT statement to restrict the number of rows in the result set.
Let’s understand this using some example queries.
Example:
Query 1:
SELECT *
FROM Participant
ORDER BY Percent DESC
LIMIT 2;
Query 1
Output:
The LIMIT operator can be used in situations such as the above, where we need to find the top 2 participants having maximum percent and do not want to use any condition statements. ORDER BY Percent DESC has sort the record in descending order and using LIMIT 2 we got the first 2 rows from sorted result.
We can also include some situations using the WHERE clause in the above example. Suppose if we don’t want the Civil branch in our result set and want the first 2 Participants to have a low Percent.
We can write queries like :
Query 2:
SELECT *
FROM Participant
WHERE Branch != 'Civil'
ORDER BY Percent
LIMIT 2;
Query 2
Output :
The above query will select all the participants according to the imposed condition (i.e. all Participants except Civil branch participants will be selected) then the results would be sorted by Percent in ascending order (The ORDER BY keyword sorts the records in ascending order by default). Finally, the first 2 rows would be returned by the above query.
This is how we can limit the records from tables in SQL. We can further play with the SQL queries and get the resultant data according to different conditions and limitations.
Picked
DBMS
How To
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Introduction of Relational Algebra in DBMS
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows? | [
{
"code": null,
"e": 25575,
"s": 25547,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 25856,
"s": 25575,
"text": "In this article, we will learn how to limit query results in SQL using different examples. A MySQL supports the LIMIT clause to select a limited number of records.... |
How to Update Data in Back4App Database in Android? - GeeksforGeeks | 24 May, 2021
In the previous article, we have seen adding as well as reading data from our Bac4App database in the Android app. In this article, we will take a look at Updating this data in your database.
We will be building a simple application in which we will be updating the previously added data in our Back4App database.
Step 1: Creating a new Activity for updating the data
For creating a new Activity navigate to the app > res > layout > Right-Click on it and click on New > then click on Empty Activity to create a new Activity, and we will name it as UpdateCourseActivity.
Step 2: Updating our Adapter class for opening a new activity on clicking the RecyclerView item
As we have created our Adapter class in the previous article for displaying the list of courses in Recycler View. In this article, we will add onClickListener() inside that Adapter class for RecyclerView item click listener. Add the following code snippet to the CourseRVAdapter.java file.
Java
// adding on click listener for our item of recycler view.holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a intent to open new activity. Intent i = new Intent(context, UpdateCourseActivity.class); // on below line we are passing data to our intent on below line. i.putExtra("courseName", courses.getCourseName()); i.putExtra("courseDescription", courses.getCourseDescription()); i.putExtra("courseDuration", courses.getCourseDuration()); // starting our activity on below line. context.startActivity(i); } });}
Below is the updated code for the CourseRVAdapter.java file.
Java
import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { private Context context; private ArrayList<CourseModal> courseModalArrayList; // creating a constructor class. public CourseRVAdapter(Context context, ArrayList<CourseModal> courseModalArrayList) { this.context = context; this.courseModalArrayList = courseModalArrayList; } @NonNull @Override public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // passing our layout file for displaying our card item return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false)); } @Override public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { // setting data to our text views from our modal class. CourseModal courses = courseModalArrayList.get(position); holder.courseNameTV.setText(courses.getCourseName()); holder.courseDurationTV.setText(courses.getCourseDuration()); holder.courseDescTV.setText(courses.getCourseDescription()); // adding on click listener for our item of recycler view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a intent to open new activity. Intent i = new Intent(context, UpdateCourseActivity.class); // on below line we are passing data to our intent on below line. i.putExtra("courseName", courses.getCourseName()); i.putExtra("courseDescription", courses.getCourseDescription()); i.putExtra("courseDuration", courses.getCourseDuration()); // starting our activity on below line. context.startActivity(i); } }); } @Override public int getItemCount() { return courseModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text views. private final TextView courseNameTV; private final TextView courseDurationTV; private final TextView courseDescTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); } }}
Step 3: Working with the activity_update_course.xml file
Navigate to the app > res > layout > activity_update_course.xml and add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".UpdateCourseActivity"> <!--Edit text for getting course Name--> <EditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Name" android:importantForAutofill="no" android:inputType="text" /> <!--Edittext for getting course Duration--> <EditText android:id="@+id/idEdtCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Duration in min" android:importantForAutofill="no" android:inputType="time" /> <!--Edittext for getting course Description--> <EditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Description" android:importantForAutofill="no" android:inputType="text" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:orientation="horizontal" android:weightSum="2"> <!--button for updating our course--> <Button android:id="@+id/idBtnUpdate" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:text="Update Course" android:textAllCaps="false" /> </LinearLayout> </LinearLayout>
Step 4: Working with the UpdateCourseActivity.java file
Navigate to the app > java > your app’s package name > UpdateCourseActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.GetCallback;import com.parse.ParseException;import com.parse.ParseObject;import com.parse.ParseQuery;import com.parse.SaveCallback; public class UpdateCourseActivity extends AppCompatActivity { // creating variables for our edit text private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; // creating variable for button private Button updateCourseBtn; // creating a strings for storing our values from edittext fields. private String courseName, courseDuration, courseDescription, originalCourseName, objectID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_course); // initializing our edittext and buttons updateCourseBtn = findViewById(R.id.idBtnUpdate); courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); // on below line we are setting data to our edit text field. courseNameEdt.setText(getIntent().getStringExtra("courseName")); courseDescriptionEdt.setText(getIntent().getStringExtra("courseDescription")); courseDurationEdt.setText(getIntent().getStringExtra("courseDuration")); originalCourseName = getIntent().getStringExtra("courseName"); updateCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { courseName = courseNameEdt.getText().toString(); courseDescription = courseDescriptionEdt.getText().toString(); courseDuration = courseDurationEdt.getText().toString(); // validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) { courseNameEdt.setError("Please enter Course Name"); } else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError("Please enter Course Description"); } else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration"); } else { // calling method to update data. updateData(originalCourseName, courseName, courseDescription, courseDuration); } } }); } private void updateData(String originalCourseName, String courseName, String courseDescription, String courseDuration) { // Configure Query with our query. ParseQuery<ParseObject> query = ParseQuery.getQuery("courses"); // adding a condition where our course name must be equal to the original course name query.whereEqualTo("courseName", originalCourseName); // in below method we are getting the unique id // of the course which we have to make update. query.getFirstInBackground(new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { // inside done method we check // if the error is null or not. if (e == null) { // if the error is null then we are getting // our object id in below line. objectID = object.getObjectId().toString(); // after getting our object id we will // move towards updating our course. // calling below method to update our course. query.getInBackground(objectID, new GetCallback<ParseObject>() { @Override public void done(ParseObject object, ParseException e) { // in this method we are getting the // object which we have to update. if (e == null) { // in below line we are adding new data // to the object which we get from its id. // on below line we are adding our data // with their key value in our object. object.put("courseName", courseName); object.put("courseDescription", courseDescription); object.put("courseDuration", courseDuration); // after adding new data then we are // calling a method to save this data object.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { // inside on done method we are checking // if the error is null or not. if (e == null) { // if the error is null our data has been updated. // we are displaying a toast message and redirecting // our user to home activity where we are displaying course list. Toast.makeText(UpdateCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show(); Intent i = new Intent(UpdateCourseActivity.this, HomeActivity.class); startActivity(i); } else { // below line is for error handling. Toast.makeText(UpdateCourseActivity.this, "Fail to update data " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } } }); } else { // on below line we are displaying a message // if we don't get the object from its id. Toast.makeText(UpdateCourseActivity.this, "Fail to update course " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } } }); } else { // this is error handling if we don't get the id for our object Toast.makeText(UpdateCourseActivity.this, "Fail to get object ID..", Toast.LENGTH_SHORT).show(); } } }); }}
Now run your app and try updating your course. Make sure you have previously added some courses to your list.
Output:
Below is the file structure in Android Studio after performing the Update operation:
AmiyaRanjanRout
anikaseth98
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 26574,
"s": 26381,
"text": "In the previous article, we have seen adding as well as reading data from our Bac4App database in the Android app. In this article, we will take a look at Updating... |
JavaScript | Math Object - GeeksforGeeks | 01 Mar, 2019
The Math object is used to perform mathematical operations on numbers. There are many math object properties which are listed below:
Math objects: There are many math objects exists in JavaScript which are listed below:
Example 1: This example use math object properties to return their values.
<!DOCTYPE html> <html> <head> <title> JavaScript Math Object </title> </head> <body> <h1>GeeksforGeeks</h1> <h2>JavaScript Math Object</h2> <p id="GFG"></p> <!-- Script to return math property values --> <script> document.getElementById("GFG").innerHTML = "Math.LN10: " + Math.LN10 + "<br>" + "Math.LOG2E: " + Math.LOG2E + "<br>" + "Math.Log10E: " + Math.LOG10E + "<br>" + "Math.SQRT2: " + Math.SQRT2 + "<br>" + "Math.SQRT1_2: " + Math.SQRT1_2 + "<br>" + "Math.LN2: " + Math.LN2 + "<br>" + "Math.E: " + Math.E + "<br>" + "Math.PI: " + Math.PI; </script> </body> </html>
Output:
Example 2: Math object methods are used in this example.
<!DOCTYPE html> <html> <head> <title> JavaScript Math Object </title> </head> <body> <h1>GeeksForGeeks</h1> <h2>JavaScript Math Object</h2> <p id="GFG" style = "color:green;"></p> <!-- Script to use math object method --> <script> document.getElementById("GFG").innerHTML = "<p><b>Math.abs(-4.7):</b> " + Math.abs(-4.7) + "</p>" + "<p><b>Math.ceil(4.4):</b> " + Math.ceil(4.4) + "</p>" + "<p><b>Math.floor(4.7):</b> " + Math.floor(4.7) + "</p>" + "<p><b>Math.sin(90 * Math.PI / 180):</b> " + Math.sin(90 * Math.PI / 180) + "</p>" + "<p><b>Math.min(0, 150, 30, 20, -8, -200):</b> " + Math.min(0, 150, 30, 20, -8, -200) + "</p>" + "<p><b>Math.random():</b> " + Math.random() + "</p>"; </script> </body> </html>
Output:
javascript-math
Picked
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
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
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? | [
{
"code": null,
"e": 31329,
"s": 31301,
"text": "\n01 Mar, 2019"
},
{
"code": null,
"e": 31462,
"s": 31329,
"text": "The Math object is used to perform mathematical operations on numbers. There are many math object properties which are listed below:"
},
{
"code": null,
... |
numpy.imag() function - Python - GeeksforGeeks | 11 Jun, 2020
numpy.imag() function return the imaginary part of the complex argument.
Syntax : numpy.imag(arr)
Parameters :arr : [array_like] Input array.
Return : [ndarray or scalar] The imaginary component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.
Code #1 :
# Python program explaining# numpy.imag() function # importing numpy as geek import numpy as geek arr = geek.array([1 + 3j, 5 + 7j, 9 + 11j]) gfg = arr.imag print (gfg)
Output :
[ 3. 7. 11.]
Code #2 :
# Python program explaining# numpy.imag() function # importing numpy as geek import numpy as geek arr = geek.array([2 + 3j, 5 + 6j, 8 + 9j]) gfg = arr.imag print (gfg)
Output :
[3. 6. 9.]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 25610,
"s": 25537,
"text": "numpy.imag() function return the imaginary part of the complex argument."
},
{
"code": null,
"e": 25635,
"s": 25610,
"text": "Syntax : numpy.im... |
C++ Program to check Prime Number - GeeksforGeeks | 29 Apr, 2022
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, Examples:
Input: n = 11Output: true
Input: n = 15Output: false
Input: n = 1Output: false
CPP
// A school method based C++ program to check if a// number is prime#include <bits/stdc++.h>using namespace std; bool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Driver Program to test above functionint main(){ isPrime(11) ? cout << " true\n" : cout << " false\n"; isPrime(15) ? cout << " true\n" : cout << " false\n"; return 0;}
true
false
Time Complexity: O(n) Auxiliary Space: O(1)
Optimized School Method
CPP
// A optimized school method based C++ program to check// if a number is prime#include <bits/stdc++.h>using namespace std; bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; // Using concept of prime number // can be represented in form of // (6*n + 1) or(6*n - 1) hence // we have to go for every multiple of 6 and // prime number would always be 1 less or 1 more then // the multiple of 6. for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Driver Program to test above functionint main(){ isPrime(4191) ? cout << " true\n" : cout << " false\n"; isPrime(15) ? cout << " true\n" : cout << " false\n"; return 0;}
false
false
Please refer complete article on Primality Test | Set 1 (Introduction and School Method) for more details!
vikaspandey1206
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
C program to sort an array in ascending order
time() function in C
C Program to Swap two Numbers
Producer Consumer Problem in C
Program to find Prime Numbers Between given Interval | [
{
"code": null,
"e": 25977,
"s": 25949,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 26202,
"s": 25977,
"text": "Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Ex... |
Python | Count the sublists containing given element in a list - GeeksforGeeks | 16 Mar, 2019
Given a list of lists, write a Python program to count the number of sublists containing the given element x.
Examples:
Input : lst = [1, 3, 5], [1, 3, 5, 7], [1, 3, 5, 7, 9]]
x = 1
Output : 3
Input : lst = (['a'], ['a', 'c', 'b'], ['d'])
x = 'a'
Output : 2
Approach #1 : Naive Approach
Count the number of lists containing x. Initialize count to 0, then start a for loop and check if x exists in each list or not. If yes, increment count.
# Python3 Program to count number of# list containing a certain element # in a list of lists def countList(lst, x): count = 0 for i in range(len(lst)): if x in lst[i]: count+= 1 return count # Driver Codelst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a'print(countList(lst, x))
2
Approach #2 : List comprehension (Alternative for naive)A simple one-liner list comprehension can also do the job by simply converting the above mentioned Naive approach into one-liner for loop.
# Python3 Program to count number of# list containing a certain element # in a list of lists def countList(lst, x): return sum(x in item for item in lst) # Driver Codelst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a'print(countList(lst, x))
2
Approach #3 : Using chain.from_iterable() and Counter
We can use Counter to count how many lists ‘x’ occurs in. Since we don’t want to count ‘x’ for more than once for each inner list, we’ll convert each inner list to sets. After this, join those sets of elements into one sequence using chain.from_iterable().
# Python3 Program to count number of# list containing a certain element # in a list of listsfrom itertools import chainfrom collections import Counter def countList(lst, x): return Counter(chain.from_iterable(set(i) for i in lst))[x] # Driver Codelst = (['a'], ['a', 'c', 'b'], ['d']) x = 'a'print(countList(lst, x))
2
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 26149,
"s": 26121,
"text": "\n16 Mar, 2019"
},
{
"code": null,
"e": 26259,
"s": 26149,
"text": "Given a list of lists, write a Python program to count the number of sublists containing the given element x."
},
{
"code": null,
"e": 26269,
"s": ... |
Program to check if all characters have even frequency - GeeksforGeeks | 24 May, 2021
Given a string S consisting only of lowercase letters check if the string has all characters appearing even times. Examples:
Input : abaccaba Output : Yes Explanation: ‘a’ occurs four times, ‘b’ occurs twice, ‘c’ occurs twice and the other letters occur zero times.Input : hthth Output : No
Approach: We will go through the string and count the occurrence of all characters after that we will check if the occurrences are even or not if there is any odd frequency character then we immediately print No.
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <iostream>using namespace std; bool check(string s){ // creating a frequency array int freq[26] = {0}; // Finding length of s int n = s.length(); for (int i = 0; i < s.length(); i++) // counting frequency of all characters freq[s[i] - 97]++; // checking if any odd frequency // is there or not for (int i = 0; i < 26; i++) if (freq[i] % 2 == 1) return false; return true;} // Driver Codeint main(){ string s = "abaccaba"; check(s) ? cout << "Yes" << endl : cout << "No" << endl; return 0;} // This code is contributed by// sanjeev2552
// Java implementation of the above approachclass GFG{ static boolean check(String s) { // creating a frequency array int[] freq = new int[26]; // Finding length of s int n = s.length(); // counting frequency of all characters for (int i = 0; i < s.length(); i++) { freq[(s.charAt(i)) - 97] += 1; } // checking if any odd frequency // is there or not for (int i = 0; i < freq.length; i++) { if (freq[i] % 2 == 1) { return false; } } return true; } // Driver Code public static void main(String[] args) { String s = "abaccaba"; if (check(s)) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code is contributed by Rajput-Ji
# Python implementation of the above approachdef check(s): # creating a frequency array freq =[0]*26 # Finding length of s n = len(s) for i in range(n): # counting frequency of all characters freq[ord(s[i])-97]+= 1 for i in range(26): # checking if any odd frequency # is there or not if (freq[i]% 2 == 1): return False return True # Driver codes ="abaccaba"if(check(s)): print("Yes")else: print("No")
// C# implementation of the approachusing System; class GFG{ static Boolean check(String s) { // creating a frequency array int[] freq = new int[26]; // Finding length of s int n = s.Length; // counting frequency of all characters for (int i = 0; i < s.Length; i++) { freq[(s[i]) - 97] += 1; } // checking if any odd frequency // is there or not for (int i = 0; i < freq.Length; i++) { if (freq[i] % 2 == 1) { return false; } } return true; } // Driver Code public static void Main(String[] args) { String s = "abaccaba"; if (check(s)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation of the above approach function check(s){ // creating a frequency array var freq = Array(26).fill(0); // Finding length of s var n = s.length; for (var i = 0; i < s.length; i++) // counting frequency of all characters freq[s[i] - 97]++; // checking if any odd frequency // is there or not for (var i = 0; i < 26; i++) if (freq[i] % 2 == 1) return false; return true;} // Driver Codevar s = "abaccaba";check(s) ? document.write("Yes") : document.write("No"); </script>
Output:
Yes
Approach:
We will scan the string and count the occurrence of all characters using the built-in Counter() function after that we traverse the counter list and check if the occurrences are even or not if there is any odd frequency character then we immediately print No.
Note: This method is applicable for all type of characters
Python3
# Python implementation for# the above approach # importing Counter functionfrom collections import Counter # Function to check if all# elements occur even timesdef checkString(s): # Counting the frequency of all # character using Counter function frequency = Counter(s) # Traversing frequency for i in frequency: # Checking if any element # has odd count if (frequency[i] % 2 == 1): return False return True # Driver codes = "geeksforgeeksfor"if(checkString(s)): print("Yes")else: print("No") # This code is contributed by vikkycirus
Output:
Yes
Rajput-Ji
princiraj1992
sanjeev2552
vikkycirus
famously
frequency-counting
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Vigenère Cipher
String class in Java | Set 1
sprintf() in C
Print all subsequences of a string
Convert character array to string in C++
Program to count occurrence of a given character in a string
How to Append a Character to a String in C
Naive algorithm for Pattern Searching | [
{
"code": null,
"e": 26073,
"s": 26045,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 26198,
"s": 26073,
"text": "Given a string S consisting only of lowercase letters check if the string has all characters appearing even times. Examples:"
},
{
"code": null,
"e": 2... |
How to validate a Password using Regular Expressions in Java - GeeksforGeeks | 16 Apr, 2020
Given a password, the task is to validate the password with the help of Regular Expression.A password is considered valid if all the following constraints are satisfied:
It contains at least 8 characters and at most 20 characters.
It contains at least one digit.
It contains at least one upper case alphabet.
It contains at least one lower case alphabet.
It contains at least one special character which includes !@#$%&*()-+=^.
It doesn’t contain any white space.
Examples:
Input: Str = “Geeks@portal20”Output: True.Explanation: This password satisfies all constraints mentioned above.
Input: Str = “Geeksforgeeks”Output: False.Explanation: It contains upper case and lower case alphabet but doesn’t contains any digits, and special characters.
Input: Str = “Geeks@ portal9”Output: False.Explanation: It contains upper case alphabet, lower case alphabet, special characters, digits along with white space which is not valid.
Input: Str = “12345”Output: False.Explanation: It contains only digits but doesn’t contains upper case alphabet, lower case alphabet, special characters, and 8 characters.
Approach: This problem can be solved by using Regular Expression.
Get the password.Create a regular expression to check the password is valid or not as mentioned below:regex = “^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&-+=()])(?=\\S+$).{8, 20}$”where:^ represents starting character of the string.(?=.*[0-9]) represents a digit must occur at least once.(?=.*[a-z]) represents a lower case alphabet must occur at least once.(?=.*[A-Z]) represents an upper case alphabet that must occur at least once.(?=.*[@#$%^&-+=()] represents a special character that must occur at least once.(?=\\S+$) white spaces don’t allowed in the entire string..{8, 20} represents at least 8 characters and at most 20 characters.$ represents the end of the string.Match the given string with the Regex. In java, this can be done using Pattern.matcher().Return true if the string matches with the given regex, else return false.
Get the password.
Create a regular expression to check the password is valid or not as mentioned below:regex = “^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&-+=()])(?=\\S+$).{8, 20}$”where:^ represents starting character of the string.(?=.*[0-9]) represents a digit must occur at least once.(?=.*[a-z]) represents a lower case alphabet must occur at least once.(?=.*[A-Z]) represents an upper case alphabet that must occur at least once.(?=.*[@#$%^&-+=()] represents a special character that must occur at least once.(?=\\S+$) white spaces don’t allowed in the entire string..{8, 20} represents at least 8 characters and at most 20 characters.$ represents the end of the string.
regex = “^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&-+=()])(?=\\S+$).{8, 20}$”
where:
^ represents starting character of the string.
(?=.*[0-9]) represents a digit must occur at least once.
(?=.*[a-z]) represents a lower case alphabet must occur at least once.
(?=.*[A-Z]) represents an upper case alphabet that must occur at least once.
(?=.*[@#$%^&-+=()] represents a special character that must occur at least once.
(?=\\S+$) white spaces don’t allowed in the entire string.
.{8, 20} represents at least 8 characters and at most 20 characters.
$ represents the end of the string.
Match the given string with the Regex. In java, this can be done using Pattern.matcher().
Return true if the string matches with the given regex, else return false.
Below is the implementation of the above approach:
// Java program to validate// the password using ReGex import java.util.regex.*;class GFG { // Function to validate the password. public static boolean isValidPassword(String password) { // Regex to check valid password. String regex = "^(?=.*[0-9])" + "(?=.*[a-z])(?=.*[A-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\S+$).{8,20}$"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the password is empty // return false if (password == null) { return false; } // Pattern class contains matcher() method // to find matching between given password // and regular expression. Matcher m = p.matcher(password); // Return if the password // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = "Geeks@portal20"; System.out.println(isValidPassword(str1)); // Test Case 2: String str2 = "Geeksforgeeks"; System.out.println(isValidPassword(str2)); // Test Case 3: String str3 = "Geeks@ portal9"; System.out.println(isValidPassword(str3)); // Test Case 4: String str4 = "1234"; System.out.println(isValidPassword(str4)); // Test Case 5: String str5 = "Gfg@20"; System.out.println(isValidPassword(str5)); // Test Case 6: String str6 = "geeks@portal20"; System.out.println(isValidPassword(str6)); }}
true
false
false
false
false
false
java-regular-expression
Java
Java Programs
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List 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 | [
{
"code": null,
"e": 26549,
"s": 26521,
"text": "\n16 Apr, 2020"
},
{
"code": null,
"e": 26719,
"s": 26549,
"text": "Given a password, the task is to validate the password with the help of Regular Expression.A password is considered valid if all the following constraints are sati... |
Moment.js isSame() Function - GeeksforGeeks | 29 Jul, 2020
You can check whether a given date is equal to another date in Moment.js using isSame() function that checks if a moment is the same as another moment. The first argument will be parsed as a moment, if not already so.
Syntax:
moment().isSame(Moment|String|Number|Date|Array);
moment().isSame(Moment|String|Number|Date|Array, String);
Parameter: It can hold String/Number/Data/Array/Object.
Returns: True or False
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing the moment module, you can check your moment version in command prompt using the command.npm version moment
npm version moment
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Example 1: Filename: index.js
// Requiring moduleconst moment = require('moment'); var bool1 = moment('2010-08-21') .isSame('2010-09-21'); //falseconsole.log(bool1); var bool2 = moment('2019-10-20') .isSame('2019-10-20'); //trueconsole.log(bool2);
Steps to run the program:
The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:false
true
The project structure will look like this:
Make sure you have installed moment module using the following command:npm install moment
npm install moment
Run index.js file using below command:node index.jsOutput:false
true
node index.js
Output:
false
true
Example 2: Filename: index.js
// Requiring moduleconst moment = require('moment'); function checkSame(date1, date2) { return moment(date1).isSame(date2);} var bool = checkSame('2019-10-20', '2019-10-20')console.log(bool);
Run index.js file using below command:
node index.js
Output:
true
Reference: https://momentjs.com/docs/#/query/is-same/
Moment.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 26485,
"s": 26267,
"text": "You can check whether a given date is equal to another date in Moment.js using isSame() function that checks if a moment is the same as another moment. The first a... |
Difference between Deterministic and Non-deterministic Algorithms - GeeksforGeeks | 24 Nov, 2021
In deterministic algorithm, for a given particular input, the computer will always produce the same output going through the same states but in case of non-deterministic algorithm, for the same input, the compiler may produce different output in different runs. In fact non-deterministic algorithms can’t solve the problem in polynomial time and can’t determine what is the next step. The non-deterministic algorithms can show different behaviors for the same input on different execution and there is a degree of randomness to it.
To implement a non-deterministic algorithm, we have a couple of languages like Prolog but these don’t have standard programming language operators and these operators are not a part of any standard programming languages.
Some of the terms related to the non-deterministic algorithm are defined below:
choice(X) : chooses any value randomly from the set X.
failure() : denotes the unsuccessful solution.
success() : Solution is successful and current thread terminates.
Example :
Problem Statement : Search an element x on A[1:n] where n>=1, on successful search return j if a[j] is equals to x otherwise return 0.
Non-deterministic Algorithm for this problem :
1.j= choice(a, n)
2.if(A[j]==x) then
{
write(j);
success();
}
3.write(0); failure();
Algorithms-Analysis of Algorithms
Picked
Algorithms
Analysis
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
How to Start Learning DSA?
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Understanding Time Complexity with Simple Examples
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Time Complexity and Space Complexity
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) | [
{
"code": null,
"e": 25424,
"s": 25396,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25956,
"s": 25424,
"text": "In deterministic algorithm, for a given particular input, the computer will always produce the same output going through the same states but in case of non-determi... |
How to Fix: NameError name ‘np’ is not defined - GeeksforGeeks | 28 Nov, 2021
In this article, we will discuss how to fix NameError np that is not defined in Python.
When we imported the NumPy module without alias and used np in the code, the error comes up.
Example: Code to depict error
Python3
# import numpymoduleimport numpy # create numpy arraya = np.array([1, 2, 3, 45]) # displaya
Output:
name 'np' is not defined
Here np is an alias of the NumPy module so we can either import the NumPy module with the alias or import NumPy without the alias and use the name directly.
We can use an alias at the time of import to resolve the error.
Syntax:
import numpy as np
Example: Program to import numpy as alias
Python3
# import numpymoduleimport numpy as np # create numpy arraya = np.array([1, 2, 3, 45]) # displaya
Output:
array([ 1, 2, 3, 45])
We can use NumPy module directly to use in a data structure.
Syntax:
import numpy
Example: Using NumPy directly
Python3
# import numpymoduleimport numpy # create numpy arraya = numpy.array([1, 2, 3, 45]) # displaya
Output:
array([ 1, 2, 3, 45])
Picked
Python How-to-fix
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25625,
"s": 25537,
"text": "In this article, we will discuss how to fix NameError np that is not defined in Python."
},
{
"code": null,
"e": 25718,
"s": 25625,
"text": "Wh... |
C# | Method returning an object - GeeksforGeeks | 10 May, 2019
In C#, a method can return any type of data including objects. In other words, methods are allowed to return objects without any compile time error.
Example 1:
// C# program to illustrate the concept// of the method returning an objectusing System; class Example { // Private data member private string str; // Method to set the value of str public void setdata(string s) { str = s; } // Method to display the value of str public void Display() { Console.WriteLine("String is: " + str); } // Method that return object public Example Astr(Example ex) { // Creating object of Example Example obj = new Example(); // Adding the value of passed // an object in the current object // and adding the sum in another object obj.str = str + ex.str; // Returning the object return obj; }} // Driver Classclass GFG { // Main method static void Main() { // Declaring objects of Example Example o1 = new Example(); Example o2 = new Example(); // Initialize the values to the objects o1.setdata("Geeks"); o2.setdata("forGeeks"); // Adding value of both objects // and the result will be // assigned into third object Example o3 = o1.Astr(o2); // Display the data o1.Display(); o2.Display(); o3.Display(); }}
String is: Geeks
String is: forGeeks
String is: GeeksforGeeks
Explanation: In the above example, we have a class named as Example. Example class contains setdata() method which is used to set the value of str, and Display() method is used to display the value of str, and Astr() is used to add the value of passed object in current object and adding the sum in another object. In Main method, three objects o1, o2, and o3 of Example class are created. In this statement, Example o3 = o1.Astr(o2);, the value of o1 and o2 object is added and the result is assigned into o3 object.
Example 2:
// C# program to illustrate the // concept that how method returns // an objectusing System; class Triangle { // Data member of class int Base; int Height; // Constructor of class public Triangle(int b, int h) { Base = b; Height = h; } // Method return area of triangle public int Area() { return ((Base * Height) / 2); } // Method display the dimension of triangle public void Display() { Console.WriteLine("\nBase of the triangle is: " + Base + "\nHeight of the triangle is: " + Height); } public Triangle newdimension(int d) { return new Triangle(Base * d, Height * d); }} class GFG { // Main method public static void Main() { // Creating and initializing object Triangle t1 = new Triangle(2, 8); // Display the dimensions and area of triangle Console.Write("Dimensions of Triangle is: "); t1.Display(); Console.Write("Area of Triangle is: {0}", t1.Area()); Console.WriteLine(); Console.WriteLine(); Triangle t2 = t1.newdimension(2); Console.Write("New Dimensions of Triangle is: "); t2.Display(); Console.Write("New area of Triangle is: {0}", t2.Area()); }}
Dimensions of Triangle is:
Base of the triangle is: 2
Height of the triangle is: 8
Area of Triangle is: 8
New Dimensions of Triangle is:
Base of the triangle is: 4
Height of the triangle is: 16
New area of Triangle is: 32
Explanation: In the above example, we have a class named as the Triangle. The Triangle class contains constructor Triangle(), method Area() to find the area of the triangle, method Display() to display the dimension of the triangle, and method newdimension() to provide a new dimension of the triangle. The value of the dimension is returned by the object. Now in the Main method there are two objects named as t1 and t2. In this statement Triangle t2 = t1.newdimension(2);, the previous dimension, i.e. 2 and 8 of the triangle is enlarged by 2 and the result assigned to the t2 object.
Akanksha_Rai
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
C# | How to insert an element in an Array?
Switch Statement in C#
Convert String to Character Array in C#
Linked List Implementation in C# | [
{
"code": null,
"e": 25571,
"s": 25543,
"text": "\n10 May, 2019"
},
{
"code": null,
"e": 25720,
"s": 25571,
"text": "In C#, a method can return any type of data including objects. In other words, methods are allowed to return objects without any compile time error."
},
{
... |
Java Program to Find All Palindromic Sub-Strings of a String - GeeksforGeeks | 21 Apr, 2021
Given a string, the task is to count all palindrome substring in a given string.
Input : aba
Output : 4
Explanation : All palindrome substring are : "aba" , "a" , "b", "a"
Input : TENET
Output : 7
Explanation : All palindrome sub-string are : "T" , "E" , "N", "E", "T" , "ENE" , "TENET"
Approach:
Take the substrings from the given string.Now check whether the substring is Palindrome or not.If the substring is Palindrome increment the count by 1 else if not count is not incremented.Return the count as it represents the number of substrings.Print and display on the console.
Take the substrings from the given string.
Now check whether the substring is Palindrome or not.
If the substring is Palindrome increment the count by 1 else if not count is not incremented.
Return the count as it represents the number of substrings.
Print and display on the console.
Example:
Java
// Java Program to Find all palindromic sub-strings // of a given string // Importing input output classesimport java.io.*; // Main class// To check for pallindromic sub-stringspublic class GFG { // Method 1 // To check for substring public static boolean check(String subS) { int size = subS.length(); // Iterating over string till midway to // check pallindromic behavior for (int i = 0; i < size / 2; i++) { if (subS.charAt(i) != subS.charAt(size - i - 1)) { // Non-pallindromic behavior return false; } } // Pallindromic behavior return true; } // Method 2 // Main driver method public static void main(String[] args) { // Custom input string String str = "MALAYALAM"; int count = 0; // Outer loop iterating over input string for (int i = 0; i < str.length(); i++) { // Inner loop iterating from current starting // character of outer loop current starting // character for (int j = i; j < str.length(); j++) { // Getting the substrings String subString = str.substring(i, j + 1); // Checking whether the substring is // pallindrome if (check(subString)) { // Increment the count only if // substring is pallindrome count++; } } } // Print and display the number of substrings that // are pallindromic System.out.println( "No.of palindromic substrings in the given string are " + count); }}
No.of palindromic substrings in the given string are 15
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file 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?
Program to print ASCII Value of a character | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25306,
"s": 25225,
"text": "Given a string, the task is to count all palindrome substring in a given string."
},
{
"code": null,
"e": 25541,
"s": 25306,
"text": "Input ... |
Automatic Captcha Verification using JavaScript - GeeksforGeeks | 01 Feb, 2019
Captcha: Captcha is a program used to protects websites through bots. It generates some tests that human can read and pass it but current computer can not do. For example, humans can read distorted text but computer can not read. The CAPTCHA is the abbreviation of Completely Automated Public Turing Test To Tell Computers and Humans Apart.
There are many paid software in market which detect captcha code. The Tessaract.js library is used to identifying numbers from the text.
Note: Its prediction is not 100% accurate however it can improve accuracy by using the str.replace(“”, “”) method. Only numeric captcha can be solved easily by using this method.
Example:
<!DOCTYPE html><html> <head> <title> Auto captcha verification </title> <script src ='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'> </script></head> <body> <img id = "img" src = "https://i.ibb.co/L97ShyB/download.jpg" /> <div id = "GFG"></div> <!-- script for auto captcha verification --> <script> let progress = document.querySelector('#GFG'); Tesseract.recognize('https://i.ibb.co/L97ShyB/download.jpg') .progress(function(p) { progress.innerHTML += JSON.stringify(p) + "<br>" }) .then(function(result) { var captcha = result.text; alert(captcha) }) </script></body> </html>
Output:
Web-Programs
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
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
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 | [
{
"code": null,
"e": 25587,
"s": 25559,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 25928,
"s": 25587,
"text": "Captcha: Captcha is a program used to protects websites through bots. It generates some tests that human can read and pass it but current computer can not do. For ... |
HTML | Window atob( ) Method - GeeksforGeeks | 26 Jul, 2019
The Window atob() method is used for decoding a base-64 encoded string. It is used to decode a string of data which has been encoded using the btoa() method.It returns a string which represents the decoded string.
Syntax :
window.atob(EncodedString)
Parameters Used :
EncodedString : It is a mandatory parameter which specifies the encoded string.
Below program illustrates the Window atob() Method :
Decoding a string encoded using the btoa() method.
<!DOCTYPE html><html> <head> <title> Window atob() Method in HTML </title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Window atob() Method</h2> <p> For decoding a base-64 encoded string, double click the "Decode Message" button: </p> <button ondblclick="decode()"> Decode Message </button> <p id="myDecoding"></p> <script> function decode() { var original = "GeeksforGeeks"; var encoded = window.btoa(original); var decoded = window.atob(encoded); var output = "Encoded String : " + encoded + "<br>" + "Decoded String : " + decoded; document.getElementById("myDecoding").innerHTML = output; } </script> </body> </html>
Output:
After clicking the button
Supported Browsers: The browser supported by Window atob( ) Method are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Methods
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
How to create an HTML button that acts like a link?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers | [
{
"code": null,
"e": 25090,
"s": 25062,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 25304,
"s": 25090,
"text": "The Window atob() method is used for decoding a base-64 encoded string. It is used to decode a string of data which has been encoded using the btoa() method.It ret... |
Computer Vision for Beginners: Part 1 | by Jiwon Jeong | Towards Data Science | Computer Vision is one of the hottest topics in artificial intelligence. It is making tremendous advances in self-driving cars, robotics as well as in various photo correction apps. Steady progress in object detection is being made every day. GANs is also a thing researchers are putting their eyes on these days. Vision is showing us the future of technology and we can’t even imagine what will be the end of its possibilities.
So do you want to take your first step in Computer Vision and participate in this latest movement? Welcome you are at the right place. From this article, we’re going to have a series of tutorials on the basics of image processing and object detection. This is the first part of OpenCV tutorial for beginners and the complete set of the series is as follows:
Understanding color models and drawing figures on imagesThe basics of image processing with filteringFrom feature detection to face detectionContour detection and having a little bit of fun
Understanding color models and drawing figures on images
The basics of image processing with filtering
From feature detection to face detection
Contour detection and having a little bit of fun
The first story of this series will be about installing OpenCV, explaining color models and drawing figures on images. The complete code for this tutorial is also available on Github. Now let’s get it started.
Image processing is performing some operations on images to get an intended manipulation. Think about what we do when we start a new data analysis. We do some data preprocessing and feature engineering. It’s the same with image processing. We do image processing to manipulate the pictures for extracting some useful information from them. We can reduce noises, control the brightness and color contrast. To learn detailed image processing fundamentals, visit this video.
OpenCV stands for Open Source Computer Vision library and it’s invented by Intel in 1999. It’s first written in C/C++ so you may see tutorials more in C languages than Python. But now it’s also getting commonly used in Python for computer vision as well. First things first, let’s set up a proper environment for using OpenCV. The installation can be processed as follows but you can also find the detailed description here.
pip install opencv-python==3.4.2pip install opencv-contrib-python==3.3.1
After you finish the installation, try importing the package to see if it works well. If you get the return without any errors, then you’re now ready to go!
import cv2cv2.__version__
The first step we’re going to do with OpenCV is importing an image and it can be done as follows.
import numpy as npimport matplotlib.pyplot as plt%matplotlib inline# Import the imageimg = cv2.imread('burano.jpg')plt.imshow(img)
Have you ever been to Burano? It’s one of the most beautiful islands in Italy. If you haven’t been there, you should definitely check this place for your next holidays. But if you already know this island, you’d probably notice there’s something different in this picture. It’s a little bit different from the pictures we usually see from Burano. It should be more delightful than this!
This is because the default setting of the color mode in OpenCV comes in the order of BGR, which is different from that of Matplotlib. Therefore to see the image in RGB mode, we need to convert it from BGR to RGB as follows.
# Convert the image into RGBimg_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)plt.imshow(img_rgb)
Now, this is Burano! Such a lovely island in Italy!
Let’s talk about color modes a little bit more. A color model is a system for creating a full range of colors using the primary colors. There are two different color models here: additive color models and subtractive color models. Additive models use light to represent colors in computer screens while subtractive models use inks to print those digital images on papers. The primary colors are red, green and blue (RGB) for the first one and cyan, magenta, yellow and black (CMYK) for the latter one. All the other colors we see on images are made by combining or mixing these primary colors. So the pictures can be depicted a little bit differently when they are represented in RGB and CMYK.
You would be pretty accustomed to these two kinds of models. In the world of color models, however, there are more than two kinds of models. Among them, grayscale, HSV and HLS are the ones you’re going to see quite often in computer vision.
A grayscale is simple. It represents images and morphologies by the intensity of black and white, which means it has only one channel. To see images in grayscale, we need to convert the color mode into gray just as what we did with the BGR image earlier.
# Convert the image into gray scaleimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)plt.imshow(img_gray, cmap = 'gray')
Actually, RGB images are made up by stacking three channels: R, G, and B. So if we take each channel and depict them one by one, we can comprehend how the color channels are structured.
# Plot the three channels of the imagefig, axs = plt.subplots(nrows = 1, ncols = 3, figsize = (20, 20))for i in range(0, 3): ax = axs[i] ax.imshow(img_rgb[:, :, i], cmap = 'gray')plt.show()
Take a look at the images above. The three images show you how each channel is composed of. In the R channel picture, the part with the high saturation of red colors looks white. Why is that? This is because the values in the red color parts will be near 255. And in grayscale mode, the higher the value is, the whiter the color becomes. You can also check this with G or B channels and compare how certain parts differ one from another.
HSV and HLS take a bit different aspect. As you can see above, they have a three-dimensional representation, and it’s more similar to the way of human perception. HSV stands for hue, saturation and value. HSL stands for hue, saturation and lightness. The center axis for HSV is the value of colors while that for HSL is the amount of light. Along the angles from the center axis, there is hue, the actual colors. And the distance from the center axis belongs to saturation. Transforming the color mode can be done as follows.
# Transform the image into HSV and HLS modelsimg_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)img_hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)# Plot the converted imagesfig, (ax1, ax2) = plt.subplots(nrows = 1, ncols = 2, figsize = (20, 20))ax1.imshow(img_hsv)ax2.imshow(img_hls)plt.show()
But why do we have to transform the colors? What are these for? One example that can give the answer is lane detection. Please take a look at the picture below. See how the lanes are detected in different color modes. During the computer vision task, we do multiple color mode transformation along with masking. If you’d like to find more about how image processing is applied in the lane detection task, feel free to check out this post by nachiket tanksale.
Now I believe you get the idea. Image processing is ‘data preprocessing.’ It’s reducing noises and extracting useful patterns to make classification and detection tasks easier. Therefore all these techniques including the ones we’ll discuss later, are for helping the model to detect the patterns easier.
Let’s bring some figures on the image. Now, we’re going to Paris. Have you ever heard of the wall of love? It’s a wall which is filled with the words “I love you” in all kinds of international languages. What we’re going to do is finding the words in our language and marking them with a rectangle. As I’m from South Korea, I’ll look up for ‘I love you’ in Korean. First, I’ll make a copy of the original image and then draw a rectangle with cv2.rectangle() We need to give the coordinates values for the upper left point and the lower right point.
# Copy the imageimg_copy = img.copy()# Draw a rectangle cv2.rectangle(img_copy, pt1 = (800, 470), pt2 = (980, 530), color = (255, 0, 0), thickness = 5)plt.imshow(img_copy)
Great! I think I caught the right position. Let’s try again. I can see one more Korean word from the image so I’ll make a circle this time. With cv2.circle() , we need to specify the point of its center and the length of its radius.
# Draw a circle cv2.circle(img_copy, center = (950, 50), radius = 50, color = (0, 0, 255), thickness = 5)plt.imshow(img_copy)
We can also put text data on the image. Why don’t we write the name of this wall this time? With cv2.putText() , we can designate the position and the font style and size of the text.
# Add text cv2.putText(img_copy, text = "the Wall of Love", org = (250, 250), fontFace = cv2.FONT_HERSHEY_DUPLEX, fontScale = 2, color = (0, 255, 0), thickness = 2, lineType = cv2.LINE_AA)plt.imshow(img_copy)
This is really a “lovely” wall, isn’t it? Try this yourself and find “I love you” in your language! 😍
Now we’ve been to Italy and France. Where would you like to go next? Why don’t we put a map and mark the places? We’re going to create a window and draw figures not by designating the points but by clicking directly on the window. Let’s try a circle first. We first create a function which will draw a circle with the data for the position and clicking of the mouse.
# Step 1. Define callback functiondef draw_circle(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: cv2.circle(img, center = (x, y), radius = 5, color = (87, 184, 237), thickness = -1) elif event == cv2.EVENT_RBUTTONDOWN: cv2.circle(img, center = (x, y), radius = 10, color = (87, 184, 237), thickness = 1)
With cv2.EVENT_LBUTTONDOWN or cv2.EVENT_RBUTTONDOWN , we can bring the data for the position when we press the buttons of the mouse. The position of the mouse will be (x, y) and we’ll draw a circle whose center is at that point.
# Step 2. Call the windowimg = cv2.imread('map.png')cv2.namedWindow(winname = 'my_drawing')cv2.setMouseCallback('my_drawing', draw_circle)
We’ll set a map as the background of the window and name the window as my_drawing. The name of the window can be anything, but it should be the same because this acts like the id of the window. Using the cv2.setMouseCallback() , we make a connection between the window and the function draw_circle we made at step 1.
# Step 3. Executionwhile True: cv2.imshow('my_drawing',img) if cv2.waitKey(10) & 0xFF == 27: breakcv2.destroyAllWindows()
Now we execute the window using while loop. Don’t forget to set the break unless you are making an infinite loop. The condition of the if clause is setting the window to be shut down when we press ESC on the keyboard. Save this as a file and import it on your terminal. If you’re to use jupyter lab, put the codes in one cell and execute. Now, tell me! Where do you want to go?
Let’s try a rectangle. As a rectangle requires two points for pt1 and pt2 in cv2.rectangle() , we need an additional step to set the first click point as pt1 and the last point as pt2. And we’re going to detect the movement of the mouse with cv2.EVENT_MOUSEMOVE and cv2.EVENT_LBUTTONUP .
We first define drawing = False as a default. When the left button is pressed, drawing becomes true and we give that first position as pt1. If drawing is on, it’ll take the current point as pt2 and keep drawing rectangles while we move the mouse. It’s like overlapping the figures. When the left button is up, drawing becomes false and it takes the last position of the mouse as its final point of pt2.
# Initializationdrawing = Falseix = -1iy = -1# create a drawing functiondef draw_rectangle(event, x, y, flags, params): global ix, iy, drawing if event == cv2.EVENT_LBUTTONDOWN: drawing = True ix, iy = x, y elif event == cv2.EVENT_MOUSEMOVE: if drawing == True: cv2.rectangle(img, pt1=(ix, iy), pt2=(x, y), color = (87, 184, 237), thickness = -1) elif event == cv2.EVENT_LBUTTONUP: drawing = False cv2.rectangle(img, pt1=(ix, iy), pt2=(x, y), color = (87, 184, 237), thickness = -1)
Replace draw_circle function to draw_rectangle in step 1. Please don’t forget to make a change inside the callback function, cv2.setMouseCallback() as well. So the whole code script will be as follows. Save this script file and run it on the terminal or the jupyter notebook.
Did you enjoy the first time with OpenCV? You can also try other functions such as drawing a line or a polygon. Feel free to check the documentation for it, which can be found here. Next time, we’re going to talk about more advanced technologies such as attaching two different images, image contour and object detection.
⭐️ And you might also find these series interesting as well ⭐️
The basic concept of convolutional neural networks:
towardsdatascience.com
Advanced networks of convolutional neural networks:
towardsdatascience.com
Are there errors you would love to correct? Please share your insight with us. I’m always open to talk, so feel free to leave comments below and share your thoughts. I also share interesting and useful resources on LinkedIn so feel free to follow or reach out to me. I’ll be back again with another interesting story next time! | [
{
"code": null,
"e": 601,
"s": 172,
"text": "Computer Vision is one of the hottest topics in artificial intelligence. It is making tremendous advances in self-driving cars, robotics as well as in various photo correction apps. Steady progress in object detection is being made every day. GANs is also... |
How to check two objects have same data using JavaScript ? - GeeksforGeeks | 01 Jul, 2020
In JavaScript, we cannot directly compare two objects by equality operators (double equals == or triple equals ===) to see whether they are equal or not. Comparing two objects like this results in false even if they have the same data. It is because those are two different object instances, they are referring to two different objects.
There is no direct method in javascript to check whether two objects have the same data or not.
Below is the pseudo-code of the function, followed by the code snippet:
Pseudo Code:
function hasSameData
if both objects have the same number of keys (properties)
if every key of obj1 matches with the corresponding key
of obj2 and values of the same keys of both objects match.
return true
return false
Approach:
We will find keys of both objects by Object.keys(), which returns an array of keys of that object.
For checking that every key in obj1 is also present in obj2, and if values of those key matches, we will use every() method. The every() method accepts a callback and returns “true” or “false” according to the callback condition.
Example:
javascript
<script> const obj1 = { name: 'Ram', age: 21 }; const obj2 = { name: 'Ram', age: 21 }; const haveSameData = function (obj1, obj2) { const obj1Length = Object.keys(obj1).length; const obj2Length = Object.keys(obj2).length; if (obj1Length === obj2Length) { return Object.keys(obj1).every( key => obj2.hasOwnProperty(key) && obj2[key] === obj1[key]); } return false; } document.write(haveSameData(obj1, obj2));</script>
Output:
true
Note: The above approach does not work for nested objects (Objects and arrays inside anobject). In such cases, it needs function according to the nested object.
Applying the above function would fail in case of nested objects as shown below:
javascript
<script> const obj1 = { name: 'Ram', age: 21, hobbies: ['Cricket', 'Swimming'] }; const obj2 = { name: 'Ram', age: 21, hobbies: ['Cricket', 'Swimming'] }; const haveSameData = function(obj1, obj2) { const obj1Length = Object.keys(obj1).length; const obj2Length = Object.keys(obj2).length; if(obj1Length === obj2Length) { return Object.keys(obj1).every( key => obj2.hasOwnProperty(key) && obj2[key] === obj1[key]); } return false; } document.write(haveSameData(obj1, obj2));</script>
Output:
false
prerak_jain
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 25637,
"s": 25300,
"text": "In JavaScript, we cannot directly compare two objects by equality operators (double equals == or triple equals ===) to see whether they are equal or not. Comparing... |
What are the arguments to Tkinter variable trace method callbacks? | Tkinter variable (var) is defined for a particular widget (textvariable=var) to store the updated value of a widget. Sometimes, there might be a case, while updating the variable information, we need to process some extra operations such as read, write, or undefined.
Tkinter provides a way to update the variable with a callback function trace (self, mode, callback) which takes the operation of the process such as read(r), write(w), or undefined(u). On the basis of these values, the callback decides what the process needs to do in the callback function. The other two values define the variable which needs to be traced (contains widget information) and the index of the variable.
In this example, we will trace the value of the Entry widget that gets updated when the user enters a value in it.
#Import the required library
from tkinter import*
#Create an instance of Tkinter frame
win = Tk()
win.geometry("750x250")
#create a variable to store the User Input
my_variable = StringVar()
def trace_when_Entry_widget_is_updated(var, index, mode):
print ("{}".format(my_variable.get()))
my_variable.trace_variable("w", trace_when_Entry_widget_is_updated)
Label(win, textvariable = my_variable).pack(padx=5, pady=5)
Entry(win, textvariable = my_variable, width=20).pack(ipadx=20,padx=5, pady=5)
win.mainloop()
Executing the above code will display an Entry widget that stores the input in a variable. The callback function will trace the updated value of the variable and display it in a Label widget.
Now, type something in the given Entry widget. The label widget will mimic the input value and display the output on the window.
On the console, you will get to see the following −
H
He
Hel
Hell
Hello
Hello
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World | [
{
"code": null,
"e": 1330,
"s": 1062,
"text": "Tkinter variable (var) is defined for a particular widget (textvariable=var) to store the updated value of a widget. Sometimes, there might be a case, while updating the variable information, we need to process some extra operations such as read, write,... |
Make 3D interactive Matplotlib plot in Jupyter Notebook - GeeksforGeeks | 28 Jul, 2021
Matplotlib is a data visualization library. It is difficult to analyze/get an insight into the data without visualizing it. And matplotlib is a great library for doing the visual analysis of data in python. Using matplotlib we can plot 1-D, 2-D and even 3-D data. In this article, we are going to learn how we can plot various 3-D plots using the matplotlib. To plot 3-D plots in python, we need to import the mplot3d library from the standard installation of matplotlib library from python.
As matplotlib is a third-party library, it doesn’t come with a standard installation of python, so you need to install matplotlib before following this article. Below is the command using which you can install the matplotlib library.
Syntax:
pip3 install matplotlib
To make the plots interactive all you need to do is install another library called ipympl i.e. interactive python matplotlib.
Syntax:
pip3 install ipympl
For creating 3d figure Axes3D.plot() function is used.
Syntax:
Axes3D.plot(xs, ys, zs,*args, **kwargs)
Parameter:
xs: the x coordinate value of the vertices.
ys: the y coordinate values of the vertices.
zs: The z coordinate value(s), either one for all points or one for each point.
To generate an interactive 3D plot first import the necessary packages and create a random dataset. Now using Axes3D(figure) function from the mplot3d library we can generate a required plot directly. Pass the data to the 3D plot and configure the title and labels.
Note: We must needed to add ” %matplotlib widget “, it is a Jupyter magic widget and used to tell jupyter to use interactive backend for plot. We have to add it to the top of the script to create an interactive plot in the ipython notebook (i.e. Jupyter notebook, Google Colab, Kaggle Kernel, etc.) to renders the figure as an interactive figure.
Given below are some implementations to do the same.
Example: Interactive scatter plot
Python3
# creating 3d plot using matplotlib # in python # for creating a responsive plot%matplotlib widget # importing required librariesfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as plt # creating random datasetxs = [14, 24, 43, 47, 54, 66, 74, 89, 12, 44, 1, 2, 3, 4, 5, 9, 8, 7, 6, 5] ys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 6, 3, 5, 2, 4, 1, 8, 7, 0, 5] zs = [9, 6, 3, 5, 2, 4, 1, 8, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0] # creating figurefig = plt.figure()ax = Axes3D(fig) # creating the plotplot_geeks = ax.scatter(xs, ys, zs, color='green') # setting title and labelsax.set_title("3D plot")ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')ax.set_zlabel('z-axis') # displaying the plotplt.show()
Output:
Interactive 3D plot in Jupyter notebook
Example: Interactive bar plot
Python
# creating 3d bar plot using matplotlib # in python # to interacte with plot%matplotlib widget # importing required librariesfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as pltimport numpy as np # creating random datasetxs = [2, 3, 4, 5, 1, 6, 2, 1, 7, 2]ys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]zs = np.zeros(10)dx = np.ones(10)dy = np.ones(10)dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # creating figurefigg = plt.figure()ax = figg.add_subplot(111, projection='3d') # creating the plotplot_geeks = ax.bar3d(xs, ys, zs, dx, dy, dz, color='green') # setting title and labelsax.set_title("3D bar plot")ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')ax.set_zlabel('z-axis') # displaying the plotplt.show()
Output:
Interactive 3D plot
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 26158,
"s": 25665,
"text": "Matplotlib is a data visualization library. It is difficult to analyze/get an insight into the data without visualizing it. And matplotlib is a great library for d... |
How to write multiple lines in text file using Python? | You can use write function to write multiple lines by separating lines by '\n'.
line1 = "First line"
line2 = "Second line"
line3 = "Third line"
with open('my_file.txt','w') as out:
out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
Alternatively, you can use writelines function to write these lines.
line1 = "First line"
line2 = "Second line"
line3 = "Third line"
with open('my_file.txt','w') as out:
out.writelines([line1, line2, line3]) | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "You can use write function to write multiple lines by separating lines by '\\n'."
},
{
"code": null,
"e": 1299,
"s": 1142,
"text": "line1 = \"First line\"\nline2 = \"Second line\"\nline3 = \"Third line\"\nwith open('my_file.txt','w')... |
SWING - JButton Class | The class JButton is an implementation of a push button. This component has a label and generates an event when pressed. It can also have an Image.
Following is the declaration for javax.swing.JButton class −
public class JButton
extends AbstractButton
implements Accessible
JButton()
Creates a button with no set text or icon.
JButton(Action a)
Creates a button where properties are taken from the Action supplied.
JButton(Icon icon)
Creates a button with an icon.
JButton(String text)
Creates a button with the text.
JButton(String text, Icon icon)
Creates a button with an initial text and an icon.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JButton.
String getUIClassID()
Returns a string that specifies the name of the L&F class which renders this component.
boolean isDefaultButton()
Gets the value of the defaultButton property, which if true means that this button is the current default button for its JRootPane.
boolean isDefaultCapable()
Gets the value of the defaultCapable property.
protected String paramString()
Returns a string representation of this JButton.
void removeNotify()
Overrides JComponent.removeNotify to check if this button is currently set as the default button on the RootPane. And if so, sets the RootPane's default button to null to ensure the RootPane doesn't hold onto an invalid button reference.
void setDefaultCapable(boolean defaultCapable)
Sets the defaultCapable property, which determines whether this button can be made the default button for its root pane.
void updateUI()
Resets the UI property to a value from the current look and feel.
This class inherits methods from the following classes −
javax.swing.AbstractButton
javax.swing.JComponent
java.awt.Container
java.awt.Component
java.lang.Object
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showButtonDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private static ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = SwingControlDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private void showButtonDemo(){
headerLabel.setText("Control in action: Button");
//resources folder should be inside SWING folder.
ImageIcon icon = createImageIcon("/resources/java_icon.png","Java");
JButton okButton = new JButton("OK");
JButton javaButton = new JButton("Submit", icon);
JButton cancelButton = new JButton("Cancel", icon);
cancelButton.setHorizontalTextPosition(SwingConstants.LEFT);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Ok Button clicked.");
}
});
javaButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Submit Button clicked.");
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Cancel Button clicked.");
}
});
controlPanel.add(okButton);
controlPanel.add(javaButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.
30 Lectures
3.5 hours
Pranjal Srivastava
13 Lectures
1 hours
Pranjal Srivastava
25 Lectures
4.5 hours
Emenwa Global, Ejike IfeanyiChukwu
14 Lectures
1.5 hours
Travis Rose
14 Lectures
1 hours
Travis Rose
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1911,
"s": 1763,
"text": "The class JButton is an implementation of a push button. This component has a label and generates an event when pressed. It can also have an Image."
},
{
"code": null,
"e": 1972,
"s": 1911,
"text": "Following is the declaration for j... |
SVG - Line | <line> element is used to draw line with a start point and end point.
Following is the syntax declaration of <line> element. We've shown main attributes only.
<line
x1="x-axis co-ordinate"
y1="y-axis co-ordinate"
x2="x-axis co-ordinate"
y2="y-axis co-ordinate" >
</line>
<html>
<title>SVG Line</title>
<body>
<h1>Sample SVG Line Image</h1>
<svg width="800" height="800">
<g>
<text x="0" y="15" fill="black" >Line #1: Without opacity.</text>
<line x1="20" y1="20" x2="150" y2="150"
stroke="black" stroke-width="3" fill="rgb(121,0,121)"></line>
</g>
</svg>
</body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.
<html>
<title>SVG Line</title>
<body>
<h1>Sam>le SVG Line Image</h1>
<svg width="800" height="800">
<g>
<text x="0" y="15" fill="black" >Line #2: With opacity </text>
<line x1="20" y1="20" x2="150" y2="150"
style="fill:rgb(121,0,121);stroke-width:3;
stroke:rgb(0,0,0);stroke-opacity:0.5;opacity:0.5"></line>
</g>
</svg>
</body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2435,
"s": 2364,
"text": "<line> element is used to draw line with a start point and end point."
},
{
"code": null,
"e": 2524,
"s": 2435,
"text": "Following is the syntax declaration of <line> element. We've shown main attributes only."
},
{
"code": ... |
Python - Nested List to single value Tuple - GeeksforGeeks | 03 Jul, 2020
Sometimes, while working with Python data, we can have problems in which we need to convert Python Nested lists to single values tuples. This kind of problem can have applications in domains such as web development and competitive programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [[5, 6], [4, 7, 10, 17]]Output : [(5, ), (6, ), (4, ), (7, ), (10, ), (17, )]
Input : test_list = [[5, 6, 7, 8]]Output : [(5, ), (6, ), (7, ), (8, )]
Method #1 : Using list comprehension ( For single nesting )This is one of the way in which this task can be performed. We iterate each inner list and convert each element as separate tuple. This caters just for a single nesting.
# Python3 code to demonstrate working of # Convert Nested List to 1 value Tuple# Using list comprehension # initializing listtest_list = [[5, 6], [4, 7, 10], [12], [9, 11]] # printing original listprint("The original list is : " + str(test_list)) # Convert Nested List to 1 value Tuple# Using list comprehensionres = [(ele, ) for sub in test_list for ele in sub] # printing result print("The converted container : " + str(res))
The original list is : [[5, 6], [4, 7, 10], [12], [9, 11]]
The converted container : [(5, ), (6, ), (4, ), (7, ), (10, ), (12, ), (9, ), (11, )]
Method #2 : Using isinstance() + recursionThe combination of above functions can be used to solve this problem. In this, we perform the task of flattening and conversion using isinstance() and recursion to cater the case of random nesting as well.
# Python3 code to demonstrate working of # Convert Nested List to 1 value Tuple# Using isinstance() + recursion # helper_fncdef hlper_fnc(test_list): res = [] if isinstance(test_list, list): for ele in test_list: res.extend(hlper_fnc(ele)) elif isinstance(test_list, int): res.append((test_list, )) return res # initializing listtest_list = [[5, [6]], [4, 7, [10, 45]], [12], [9, 11]] # printing original listprint("The original list is : " + str(test_list)) # Convert Nested List to 1 value Tuple# Using isinstance() + recursionres = hlper_fnc(test_list) # printing result print("The converted container : " + str(res))
The original list is : [[5, [6]], [4, 7, [10, 45]], [12], [9, 11]]
The converted container : [(5, ), (6, ), (4, ), (7, ), (10, ), (45, ), (12, ), (9, ), (11, )]
Python list-programs
Python-list-of-lists
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 24600,
"s": 24292,
"text": "Sometimes, while working with Python data, we can have problems in which we need to convert Python Nested lists to single values tuples. This kind of problem can h... |
Arduino - Multi-Dimensional Arrays | Arrays with two dimensions (i.e., subscripts) often represent tables of values consisting of information arranged in rows and columns.
Following are the key features of multidimensional arrays −
To identify a particular table element, we must specify two subscripts.
To identify a particular table element, we must specify two subscripts.
By convention, the first identifies the element’s row and the second identifies the element’s column.
By convention, the first identifies the element’s row and the second identifies the element’s column.
Arrays that require two subscripts to identify a particular element are called two-dimensional arrays or 2-D arrays.
Arrays that require two subscripts to identify a particular element are called two-dimensional arrays or 2-D arrays.
Arrays with two or more dimensions are known as multidimensional arrays and can have more than two dimensions.
Arrays with two or more dimensions are known as multidimensional arrays and can have more than two dimensions.
The following figure illustrates a two-dimensional array, a. The array contains three rows and four columns, so it is a 3-by-4 array. In general, an array with m rows and n columns is called an m-by-n array.
Every element in array a is identified by an element name of the form a[i][j]. Here, a is the name of the array, and i and j are the subscripts that uniquely identify each element in a. Notice that the names of the elements in row 0 all have a first subscript of 0; the names of the elements in column 3 all have a second subscript of 3.
A multidimensional array can be initialized in its declaration much like a one-dimensional array. For example, a two-dimensional array b with values 1 and 2 in its row 0 elements and values 3 and 4 in its row 1 elements could be declared and initialized as follows −
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
The values are grouped by row in braces. Therefore, 1 and 2 initialize b[0][0] and b[0][1], respectively, and 3 and 4 initialize b[1][0] and b[1][1], respectively. If there are not enough initializers for a given row, the remaining elements of that row are initialized to 0. Thus, the following declaration initializes b[0][0] to 1, b[0][1] to 0, b[1][0] to 3 and b[1][1] to 4.
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Here is an example that demonstrates initializing two-dimensional arrays in declarations.
Lines a–c declare three arrays, each with two rows and three columns.
Lines a–c declare three arrays, each with two rows and three columns.
The declaration of array1 (line a) provides six initializers in the two sub lists. The first sub list initializes row 0 of the array to the values 1, 2 and 3; the second sub list initializes row 1 of the array to the values 4, 5 and 6.
The declaration of array1 (line a) provides six initializers in the two sub lists. The first sub list initializes row 0 of the array to the values 1, 2 and 3; the second sub list initializes row 1 of the array to the values 4, 5 and 6.
If the braces around each sub-list are removed from the array1 initializer list, the compiler initializes the elements of row 0 followed by the elements of row 1, yielding the same result.
If the braces around each sub-list are removed from the array1 initializer list, the compiler initializes the elements of row 0 followed by the elements of row 1, yielding the same result.
The declaration of array2 (line b) provides only five initializers.
The declaration of array2 (line b) provides only five initializers.
The initializers are assigned to row 0, then row 1. Any elements that do not have an explicit initializer are initialized to zero, so array2[1][2] is initialized to zero.
The initializers are assigned to row 0, then row 1. Any elements that do not have an explicit initializer are initialized to zero, so array2[1][2] is initialized to zero.
The declaration of array3 (line c) provides three initializers in two sub lists.
The declaration of array3 (line c) provides three initializers in two sub lists.
The sub list for row 0 explicitly initializes the first two elements of row 0 to 1 and 2; the third element is implicitly initialized to zero.
The sub list for row 0 explicitly initializes the first two elements of row 0 to 1 and 2; the third element is implicitly initialized to zero.
The sub list for row 1 explicitly initializes the first element to 4 and implicitly initializes the last two elements to zero.
The sub list for row 1 explicitly initializes the first element to 4 and implicitly initializes the last two elements to zero.
The program calls function printArray to output each array’s elements. Notice that the function prototype (line k) specify the parameter const int a[][columns].
The program calls function printArray to output each array’s elements. Notice that the function prototype (line k) specify the parameter const int a[][columns].
When a function receives a one-dimensional array as an argument, the array brackets are empty in the function’s parameter list.
When a function receives a one-dimensional array as an argument, the array brackets are empty in the function’s parameter list.
The size of a two-dimensional array’s first dimension (i.e., the number of rows) is not required either, but all the subsequent dimension sizes are required. The compiler uses these sizes to determine the locations in memory of elements in multidimensional arrays.
The size of a two-dimensional array’s first dimension (i.e., the number of rows) is not required either, but all the subsequent dimension sizes are required. The compiler uses these sizes to determine the locations in memory of elements in multidimensional arrays.
All array elements are stored consecutively in memory, regardless of the number of dimensions. In a two-dimensional array, row 0 is stored in memory followed by row 1.
All array elements are stored consecutively in memory, regardless of the number of dimensions. In a two-dimensional array, row 0 is stored in memory followed by row 1.
void printArray ( const int [][ 3 ] ); // prototype
const int rows = 2;
const int columns = 3;
int array1[ rows ][ columns ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ rows ][ columns ] = { 1, 2, 3, 4, 5 };
int array3[ rows ][ columns ] = { { 1, 2 }, { 4 } };
void setup () {
}
void loop () {
Serial.print ("Values in array1 by row are: ") ;
Serial.print (“\r” ) ;
printArray(array1) ;
Serial.print ("Values in array2 by row are: ") ;
Serial.print (“\r” ) ;
printArray(array2) ;
Serial.print ("Values in array3 by row are: ") ;
Serial.print (“\r” ) ;
printArray(array3) ;
}
// output array with two rows and three columns
void printArray( const int a[][ columns ] ) {
// loop through array's rows
for ( int i = 0; i < rows; ++i ) {
// loop through columns of current row
for ( int j = 0; j < columns; ++j )
Serial.print (a[ i ][ j ] );
Serial.print (“\r” ) ; // start new line of output
}
// end outer for
}
// end function printArray
Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0
Note − Each row is a one-dimensional array. To locate an element in a particular row, the function must know exactly how many elements are in each row so it can skip the proper number of memory locations when accessing the array. Thus, when accessing a[1][2], the function knows to skip row 0’s three elements in memory to get to row 1. Then, the function accesses element 2 of that row. Many common array manipulations use FOR statements.
For example, the following FOR statement sets all the elements in row 2 of array a.
for ( int column = 0; column < 4; ++column )
a[ 2 ][ column ] = 0;
The FOR statement varies only the second subscript (i.e., the column subscript). The preceding FOR statement is equivalent to the following assignment statements −
a[ 2 ][ 0 ] = 0;
a[ 2 ][ 1 ] = 0;
a[ 2 ][ 2 ] = 0;
a[ 2 ][ 3 ] = 0;
The following Nested FOR statement determines the total of all the elements in array a −
total = 0;
for ( int row = 0; row < 3; ++row )
for ( int column = 0; column < 4; ++column )
total += a[ row ][ column ];
The FOR statement totals the elements of the array one row at a time. The outer FOR statement begins by setting the row (i.e., the row subscript) to 0. Therefore, the elements of row 0 may be totaled by the inner FOR statement.
The outer FOR statement then increments row to 1, so that, the elements of row 1 can be totaled. Then, the outer FOR statement increments row to 2, so that, the elements of row 2 can be totaled. When the nested FOR statement terminates, the total contains the sum of all the array elements.
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3005,
"s": 2870,
"text": "Arrays with two dimensions (i.e., subscripts) often represent tables of values consisting of information arranged in rows and columns."
},
{
"code": null,
"e": 3065,
"s": 3005,
"text": "Following are the key features of multidimensio... |
Groovy - round() | The method round returns the closest long or int, as given by the methods return type.
long round(double d)
int round(float f)
d - A double or float primitive data type
f - A float primitive data type
This method Returns the closest long or int, as indicated by the method's return type, to the argument.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
double d = 100.675;
double e = 100.500;
float f = 100;
float g = 90f;
System.out.println(Math.round(d));
System.out.println(Math.round(e));
System.out.println(Math.round(f));
System.out.println(Math.round(g));
}
}
When we run the above program, we will get the following result −
101
101
100
90
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2325,
"s": 2238,
"text": "The method round returns the closest long or int, as given by the methods return type."
},
{
"code": null,
"e": 2370,
"s": 2325,
"text": "long round(double d)\n \nint round(float f) \n"
},
{
"code": null,
"e": 2412,
... |
Difference Between Structure and Union | In this post, we will understand the difference between structure and union.
The ‘struct’ keyword is used to define a structure.
The ‘struct’ keyword is used to define a structure.
Every member in the structure is provided with a unique memory location.
Every member in the structure is provided with a unique memory location.
When the value of one data member is changed, it doesn’t affect other data members in structure.
When the value of one data member is changed, it doesn’t affect other data members in structure.
It helps initialize multiple members at once.
It helps initialize multiple members at once.
Total size of the structure is equivalent to the sum of the size of every data member.
Total size of the structure is equivalent to the sum of the size of every data member.
It is used to store various data types.
It is used to store various data types.
It takes memory for every member which is present within the structure.
It takes memory for every member which is present within the structure.
A member can be retrieved at a time.
A member can be retrieved at a time.
It supports flexible arrays.
It supports flexible arrays.
Following is the syntax of Structure Definition −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The ‘union’ keyword is used to define a union.
The ‘union’ keyword is used to define a union.
A memory location is shared by all of its data members.
A memory location is shared by all of its data members.
Changing the value of one data member will affect/change the value of other data members as well.
Changing the value of one data member will affect/change the value of other data members as well.
It allows the user to initialize the first member of union only.
It allows the user to initialize the first member of union only.
Total size of the union is equivalent to the size of the largest data member in the union.
Total size of the union is equivalent to the size of the largest data member in the union.
It is used to store one of the multiple data types available.
It is used to store one of the multiple data types available.
It takes memory for a member that has the highest size.
It takes memory for a member that has the highest size.
Only one member can be accessed at a time.
Only one member can be accessed at a time.
It doesn’t support flexible arrays.
It doesn’t support flexible arrays.
Following is the syntax of Union Definition −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables]; | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "In this post, we will understand the difference between structure and union."
},
{
"code": null,
"e": 1191,
"s": 1139,
"text": "The ‘struct’ keyword is used to define a structure."
},
{
"code": null,
"e": 1243,
"s": 1... |
\href - Tex Command | \href - Used to make a math object into a link.
{ \href{ <url> } #1 }
\href command is used to make a math object into a link where the argument (#1) is the clickable area.
\href{http://www.tutorialspoint.com}{M^{A^{T^H}}}
MATH
\href{http://www.tutorialspoint.com}{M^{A^{T^H}}}
MATH
\href{http://www.tutorialspoint.com}{M^{A^{T^H}}}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8034,
"s": 7986,
"text": "\\href - Used to make a math object into a link."
},
{
"code": null,
"e": 8056,
"s": 8034,
"text": "{ \\href{ <url> } #1 }"
},
{
"code": null,
"e": 8159,
"s": 8056,
"text": "\\href command is used to make a math o... |
Consecutive 1's not allowed | Practice | GeeksforGeeks | Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s. Output your answer modulo 10^9 + 7.
Example 1:
Input:
N = 3
Output: 5
Explanation: 5 strings are (000,
001, 010, 100, 101).
Example 2:
Input:
N = 2
Output: 3
Explanation: 3 strings are
(00,01,10).
Your Task:
Complete the function countStrings() which takes single integer n, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 105
+1
kashyapjhon5 days ago
C++ Solution Time=(0.01/1.12) EASY:
ll countStrings(int n) { // code here vector<ll> dp(n+1,0); dp[0]=1; dp[1]=2; for(int i=2;i<=n;i++){ dp[i]=(dp[i-1]+dp[i-2])%1000000007; } return dp[n];}
0
manjeetdhaterwal3 weeks ago
java sol
long countStrings(int n) {
int f = 1;
int s = 2;
int t = 0;
if(n==0) return f;
if(n==1) return s;
for(int i=2; i<=n; i++)
{
t = (f+s)%1000000007;
f = s;
s = t;
}
return t;
}
0
parikhsharan61 month ago
// JAVA solutoin Top down approach, 0.2s
class Solution { long dp[][]; private final long MOD = 1000000007; long countStrings(int n) { dp = new long[n + 1][2]; for(long[] a : dp) { Arrays.fill(a, -1); } return helper(n, 0); } private long helper(int n, int isPrevOne) { if(n == 0) { return 1; } if(dp[n][isPrevOne] != -1) { return dp[n][isPrevOne]; } if(isPrevOne == 1) { return dp[n][isPrevOne] = helper(n - 1, 0) % MOD; } else { return dp[n][isPrevOne] = (helper(n - 1, 0) % MOD + helper(n - 1, 1) % MOD) % MOD; } }}
0
50n_0f_b3n9a12 months ago
PYTHON(0.1 sec)---
def countStrings(self,n):
z = 1;o = 0;
for i in range(1,n+1):
z,o = z + o, z;
return (z+o)%1000000007;
+1
kashifamir2742 months ago
perfect solution doesnt exist
ll countStrings(int n) { int arr[n+1]; arr[0]=1; arr[1]=2; for( int i=2;i<=n; i++) { arr[i]=(arr[i-1]+arr[i-2])%1000000007; } return arr[n];}
0
rajeevsahu852 months ago
if(n==1) return 2; if(n==2) return 3; ll mod=1e9+7; ll prev_prev=2; ll prev=3; int ans=0; for(int i=3;i<=n;i++){ ans=(prev+prev_prev)%mod; prev_prev=prev; prev=ans; } return ans%mod;
0
lietester00
This comment was deleted.
+1
rahuluttam9382 months ago
class Solution{public:// #define ll long longll dp[100002][2];ll mod=1000000007;ll slove(int n, int take_zero, int take_one){ if(n==0){ return 1; } if(take_zero==true && dp[n][0]!=0){ return dp[n][0]%mod; } if(take_one==true && dp[n][1]!=0){ return dp[n][1]%mod; } if(take_one==1){ return dp[n][1]= (slove(n-1, 1, 0))%mod; } return dp[n][0]= (slove(n-1, 1, 0)+ slove(n-1, 0, 1))%mod;}ll countStrings(int n) { int take_zero=0; int take_one=0; int count =0; for(int i=0; i<n+3; i++){ for(int j=0; j<2; j++){ dp[i][j]=0; } } ll ans= slove(n, take_zero, take_one); ans%=mod; return ans; }};
0
mayank20213 months ago
c++ll countStrings(int n) {
return (fibonacci(n+1)+fibonacci(n))%1000000007 ;
}ll fibonacci(ll n){ int first=1, second=1, temp; for(int i=3; i<=n; i++) { temp=(first+second)%1000000007; first=second%1000000007; second=temp; } return second; }
0
mydirtymind694 months ago
long z = 1, o = 1;
for(int i = 2; i <= n; i++) {
long temp = z;
z = (z + o) % mod;
o = temp % mod;
}
return (z + o) % mod;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 397,
"s": 238,
"text": "Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s. Output your answer modulo 10^9 + 7."
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Example 1:"
},
{
"c... |
HDFS Simple Docker Installation Guide for Data Science Workflow | by Paras Varshney | Towards Data Science | In this small article, we would be discussing how to set up the Docker-based Hadoop distributed file system on your computer and will discuss a simple example to demonstrate the use-case. Also once the setup is ready to be with on your machine, you can start building your own map-reduce jobs to play around with Hadoop DFS.
First, you need to clone the following Git repository into your desired directory in your system. I prefer cloning it into the home for demonstration and easy access.
git clone https://github.com/big-data-europe/docker-hadoop
then enter the project repository using the change directory command:
cd docker-hadoop
Now on doing an “ls -l” command you can see all the files inside this repository as shown below.
After that, you need to spin up the containers required to setup HDFS on your system. To do that, there is a docker-compose.yml file in the project directory, you need to use the “docker-compose up” command to download and install the required images from the Docker hub and configure the containers based on the docker-compose.yml file. The “-d” flag runs the containers in detached mode. If the images are not found locally, Docker downloads them from DockerHub, but if you want to manually download them you can use “docker-compose pull”.
Note: Use “sudo ” as the prefix of these commands, if you get a permission error.
# download images required for setting up HDFS and spin up necessary # containers.docker-compose up -d
The above command will download all the necessary Docker images from the docker hub for setting up HDFS containers. It might take a little while to download images depending on your internet speed.
Now, to have a look at your current running Docker containers, use the command to list all active containers.
# List all the available running docker containers.docker container ls
Once you have all your files copied inside your Hadoop cluster in a directory(note: in this example, I have copied files in /tmp), now you would go inside the namenode using the following command in an interactive terminal mode in bash mode.
# Enter inside namenode and open its bashdocker exec -it namenode /bin/bash
Example: sudo docker cp my_input.txt namenode:/tmp/
Now we need to copy the jar files which contains our map-reduce jobs and copy them inside the namenode (which will be running your jobs) in HDFS using the following Docker command:
docker cp <file_name> namenode:/<path>
Once you enter the name node in an interactive terminal, use the following HDFS commands to interact with the namenode.
# HDFS list commands to show all the directories in root "/"hdfs dfs -ls /# Create a new directory inside HDFS using mkdir tag.hdfs dfs -mkdir -p /user/root# Copy the files to the input path in HDFS.hdfs dfs -put <file_name> <path># Have a look at the content of your input file.hdfs dfs -cat <input_file>
Now you can run your map-reduce job using the following command:
# Run map reduce job from the path where you have the jar file.hadoop jar <jar_file_name> <class_name> input output
Example: hadoop jar word_counter.jar org.apache.hadoop.examples.WordCount input output
Once this command runs successfully, you will notice that the map-reduce job completes its execution with some information on the console about the process.
Once the job is executed successfully, you can check your output using the cat command in HDFS:
# Check the content of the output file after running the jobhdfs dfs -cat <output_file>
You will see the word frequency of your word counter job should be printed on the console.
Congratulations! You have successfully configured and created your first Hadoop HDFS map-reduce job!
You can access the HDFS namenode’s UI dashboard on your localhost at port 9870. Use the following link:
http://<your_ip_address>:9870
So basically the setup of HDFS was straightforward for simple data science workflow and you have learned after reading this article that how simple it is to set up a local Docker-based HDFS set up and start writing your own map-reduce jobs to execute various tasks. If you are not very familiar with the map-reduce jobs so I have attached a few useful links. Enjoy!
https://en.wikipedia.org/wiki/MapReducehttps://hadoop.apache.org/docs/r1.2.1/mapred_tutorial.htmlhttps://hadoop.apache.org/docs/r1.2.1/hdfs_user_guide.html
https://en.wikipedia.org/wiki/MapReduce
https://hadoop.apache.org/docs/r1.2.1/mapred_tutorial.html
https://hadoop.apache.org/docs/r1.2.1/hdfs_user_guide.html
Hope you found the article helpful!Thank You! | [
{
"code": null,
"e": 497,
"s": 172,
"text": "In this small article, we would be discussing how to set up the Docker-based Hadoop distributed file system on your computer and will discuss a simple example to demonstrate the use-case. Also once the setup is ready to be with on your machine, you can st... |
7 Best Terminal Emulators For Linux - GeeksforGeeks | 02 Dec, 2020
Despite various GUI advancements, Terminal Emulators have still its adequate presence in the tech market. A terminal emulator is a software that allows to you interact with the host machine with the help of commands. Terminal Emulator is a lifeline for every Linux distro as it enables you to utilize the real strength of Linux.
For developers, their major time is spent in front of the terminal (terminal emulator), but the problem is that the default terminal emulator provided by most of the Linux distro doesn’t provide many functionalities. However, you don’t have to worry as you can always install a terminal emulator of your choice. Here, in this article, we’ve compiled a list of the best terminal emulators which you can use to make things more convenient & interesting:
What if we have a terminal in which you can open multiple Terminals in a single window? (Sound cool, right??) Terminator is a pretty cool terminal emulator that provides you this functionality. You can open multiple terminals in a single window and can split them vertically or horizontally as you want. It also provides you the functionality to give a custom title to every terminal and several prominent features like multi grid-like structure, layouts saving, etc.
You can install Terminator using the following command:
$ sudo apt install terminator
$ sudo yum install terminator
$ sudo pacman -S terminator
Guake is a drop-down Linux terminal emulator that is mostly written in Python. The key feature of this emulator is that you can customize its behavior and appearance. If you just don’t like the design of your terminal then you can simply customize it the way you want. You can also configure the keyboard shortcuts for your Guake emulator. Guake would be the best choice for you if you love customization. Also, Guake enables the easy integration of the terminal into GUI and supports multi-tab.
You can install Guake using the following commands:
$ sudo apt install guake
$ sudo yum install guake
$ sudo pacman -S guake
If you are from the ’90s then this emulator is only for you. This emulator mimics the old cathode display and will give you an old school feel. This emulator is quite lightweight and easy to use.
Tip: You can always know about the key features of any application in Linux by using the man command. It provides you the official documentation of the application.
You can install Cool Retro Term using the following command:
$ sudo add-apt-repository ppa:vantuz/cool-retro-term
$ sudo apt update
$ sudo apt install cool-retro-term
$ sudo snap install cool-retro-term --classic
$ sudo pacman -S cool-retro-term
If you are on the LTS version of Ubuntu then this is the default terminal emulator. This emulator is quite stable and efficient and like other terminal emulators, it also provides colored text, a variety of themes, etc. The GNOME terminal also has the feature which parses the URLs and email in output and makes them clickable. Upon clicking, the appropriate application will open to access that resource (email or URL).
You can install GNOME terminal using the following command:
$ sudo add-apt-repository ppa:gnome3-team/gnome3
$ sudo apt-get update && sudo apt-get install gnome-shell ubuntu-gnome-desktop
Some people are fully dependent on the terminal for their day-to-day tasks. They don’t like to navigate on GUI for doing their tasks, for such users Terminology is the best emulator. Terminology provides its user the functionality to preview the files, videos, images within the terminal. Just use the below command and you can preview a variety of files within Terminology.
$ tycat <filename>
You can install Terminology using the following command:
$ sudo apt install -y terminology
$ sudo snap install terminology --classic
$ sudo pacman -S terminology
Kitty is a scriptable OpenGL based terminal emulator with True Color, ligatures support, protocol extensions for keyboard input and image rendering. The key feature of the kitty is that it is a GPU based emulator so it offloads rendering to the GPU for lower system load and buttery smooth scrolling. Unlike gnome-terminal, Kitty actually opens up to full-screen if you used it in full-screen mode last, this feature of Kitty makes it pretty cool. You can set up your custom fonts, custom colors, and custom layout on the kitty.
You can install Kitty using the following command:
$ sudo apt install kitty
$ curl -L https://sw.kovidgoyal.net/kitty/installer.sh | sh /dev/stdin
Rxvt-Unicode is a customizable terminal emulator forked from rxvt. Features of rxvt-unicode include international language support through Unicode. Rxvt-Unicode uses very little memory and takes a lightweight approach without losing many important functionalities.
You can install rxvt-unicode using the following command:
$ sudo apt install rxvt-unicode
$ sudo yum install rxvt-unicode
$ sudo pacman -S rxvt-unicode
GBlog
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
10 Best IDE For Web Developers in 2022
A Freshers Guide To Programming
Top 10 Python Books for Beginners and Advanced Programmers
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C | [
{
"code": null,
"e": 24984,
"s": 24956,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 25313,
"s": 24984,
"text": "Despite various GUI advancements, Terminal Emulators have still its adequate presence in the tech market. A terminal emulator is a software that allows to you inte... |
Cucumber - Features | A Feature can be defined as a standalone unit or functionality of a project. Let’s take a very common example of a social networking site. How does the feature of this product/project look like? Few basic features can be determined as −
Create and remove the user from the social networking site.
Create and remove the user from the social networking site.
User login functionality for the social networking site.
User login functionality for the social networking site.
Sharing photos or videos on the social networking site.
Sharing photos or videos on the social networking site.
Sending a friend request.
Sending a friend request.
Logout.
Logout.
By now, it is clear that, each independent functionality of the product under test can be termed as a feature when we talk about Cucumber. It is a best practice later when you start testing, that before deriving the test scripts, we should determine the features to be tested.
A feature usually contains a list of scenarios to be tested for that feature. A file in which we store features, description about the features and scenarios to be tested is known as Feature File. We will see more about feature files in the following chapter.
The keyword to represent a feature under test in Gherkins is “Feature”. The suggested best practice is, to write a small description of the feature beneath the feature title in the feature file. This will fulfill the need of a good documentation as well.
Feature − Login functionality for a social networking site.
The user should be able to login into the social networking site if the username and the password are correct.
The user should be shown the error message if the username and the password are incorrect.
The user should be navigated to home page, if the username and password are correct.
The file, in which Cucumber tests are written, is known as feature files. It is advisable that there should be a separate feature file, for each feature under test. The extension of the feature file needs to be “.feature”.
One can create as many feature files as needed. To have an organized structure, each feature should have one feature file.
For Example −
The naming convention to be used for feature name, feature file name depends on the individual’s choice. There is no ground rule in Cucumber about names.
A simple feature file consists of the following keywords/parts −
Feature − Name of the feature under test.
Feature − Name of the feature under test.
Description (optional) − Describe about feature under test.
Description (optional) − Describe about feature under test.
Scenario − What is the test scenario.
Scenario − What is the test scenario.
Given − Prerequisite before the test steps get executed.
Given − Prerequisite before the test steps get executed.
When − Specific condition which should match in order to execute the next step.
When − Specific condition which should match in order to execute the next step.
Then − What should happen if the condition mentioned in WHEN is satisfied.
Then − What should happen if the condition mentioned in WHEN is satisfied.
Feature − User login on social networking site.
The user should be able to login into the social networking site when the username and the password are correct.
The user should be shown an error message when the username and the password are incorrect.
The user should be navigated to the home page if the username and the password are correct.
Outline − Login functionality for a social networking site.
The given user navigates to Facebook. When I enter Username as "<username>" and Password as "<password>". Then, login should be unsuccessful.
| username | password |
| username1 | password1 |
* AND keyword is used to show conjunction between two conditions. AND can be used with any other keywords like GIVEN, WHEN and THEN.
There are no logic details written in the feature file.
We have got our feature file ready with the test scenarios defined. However, this is not the complete job done. Cucumber doesn’t really know which piece of code is to be executed for any specific scenario outlined in a feature file.
This calls the need of an intermediate – Step Definition file. Steps definition file stores the mapping between each step of the scenario defined in the feature file with a code of function to be executed.
So, now when Cucumber executes a step of the scenario mentioned in the feature file, it scans the step definition file and figures out which function is to be called.
public void goToFacebook() {
driver = new FirefoxDriver();
driver.navigate().to("https://www.facebook.com/");
}
@When "^user logs in using Username as \"([^\"]*)\" and Password as \"([^\"]*)\"$"
public void I_enter_Username_as_and_Password_as(String arg1, String arg2) {
driver.findElement(By.id("email")).sendKeys(arg1);
driver.findElement(By.id("pass")).sendKeys(arg2);
driver.findElement(By.id("u_0_v")).click();
}
@Then"^login should be unsuccessful$"
public void validateRelogin() {
if(driver.getCurrentUrl().equalsIgnoreCase(
"https://www.facebook.com/login.php?login_attempt=1&lwv=110")){
System.out.println("Test Pass");
} else {
System.out.println("Test Failed");
}
driver.close();
}
So with each function, whatever code you want to execute with each test step (i.e. GIVEN/THEN/WHEN), you can write it within Step Definition file. Make sure that code/function has been defined for each of the steps.
This function can be Java functions, where we can use both Java and Selenium commands in order to automate our test steps.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2199,
"s": 1962,
"text": "A Feature can be defined as a standalone unit or functionality of a project. Let’s take a very common example of a social networking site. How does the feature of this product/project look like? Few basic features can be determined as −"
},
{
"c... |
Program to calculate Kinetic Energy and Potential Energy - GeeksforGeeks | 12 Jul, 2021
Given three float values M, H, and V representing the mass, velocity, and height of an object respectively the task is to calculate its Kinetic Energy as well as its Potential Energy, Note: The value of acceleration due to gravity (g) is 9.8 and ignore units.
Examples:
Input: M = 25, H = 10, V = 15Output:Kinetic Energy = 2812.5Potential Energy = 2450Explanation : The kinetic energy of the particle is 2812.5 and the potential energy is 2450.
Input : M=5.5, H=23.5, V= 10.5Output :303.1881266.65
Approach: The required values of Kinetic Energy and Potential Energy can be calculated using the following two formulas:
Kinetic Energy = 0.5 * Mass ( M ) * Velocity ( V ) 2
Potential Energy = Mass ( M ) * Height ( H ) * Acceleration due to gravity ( g )
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate Kinetic Energy
float kineticEnergy(float M, float V)
{
// Stores the Kinetic Energy
float KineticEnergy;
KineticEnergy = 0.5 * M * V * V;
return KineticEnergy;
}
// Function to calculate Potential Energy
float potentialEnergy(float M, float H)
{
// Stores the Potential Energy
float PotentialEnergy;
PotentialEnergy = M * 9.8 * H;
return PotentialEnergy;
}
// Driver Code
int main()
{
float M = 5.5, H = 23.5, V = 10.5;
cout << "Kinetic Energy = "
<< kineticEnergy(M, V) << endl;
cout << "Potential Energy = "
<< potentialEnergy(M, H) << endl;
return 0;
}
// Java program to implement
// the above approach
class GFG{
// Function to calculate Kinetic Energy
static double kineticEnergy(double M, double V)
{
// Stores the Kinetic Energy
double KineticEnergy;
KineticEnergy = 0.5 * M * V * V;
return KineticEnergy;
}
// Function to calculate Potential Energy
static double potentialEnergy(double M, double H)
{
// Stores the Potential Energy
double PotentialEnergy;
PotentialEnergy = M * 9.8 * H;
return PotentialEnergy;
}
// Driver Code
public static void main(String []args)
{
double M = 5.5, H = 23.5, V = 10.5;
System.out.println("Kinetic Energy = " +
kineticEnergy(M, V));
System.out.println("Potential Energy = " +
potentialEnergy(M, H));
}
}
// This code is contributed by AnkThon
# Python3 program to implement
# the above approach
# Function to calculate Kinetic Energy
def kineticEnergy(M, V):
# Stores the Kinetic Energy
KineticEnergy = 0.5 * M * V * V
return KineticEnergy
# Function to calculate Potential Energy
def potentialEnergy(M, H):
# Stores the Potential Energy
PotentialEnergy = M * 9.8 * H
return PotentialEnergy
# Driver Code
if __name__ == "__main__":
M = 5.5
H = 23.5
V = 10.5
print("Kinetic Energy = ", kineticEnergy(M, V))
print("Potential Energy = ", potentialEnergy(M, H))
# This code is contributed by AnkThon
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
/// Function to calculate Kinetic Energy
static double kineticEnergy(double M, double V)
{
// Stores the Kinetic Energy
double KineticEnergy;
KineticEnergy = 0.5 * M * V * V;
return KineticEnergy;
}
// Function to calculate Potential Energy
static double potentialEnergy(double M, double H)
{
// Stores the Potential Energy
double PotentialEnergy;
PotentialEnergy = M * 9.8 * H;
return PotentialEnergy;
}
// Driver Code
public static void Main()
{
double M = 5.5, H = 23.5, V = 10.5;
Console.WriteLine("Kinetic Energy = " +
kineticEnergy(M, V));
Console.Write("Potential Energy = " +
potentialEnergy(M, H));
}
}
// This code is contributed by bgangwar59
<script>
// Javascript program for the above approach
// Function to calculate Kinetic Energy
function kineticEnergy(M, V)
{
// Stores the Kinetic Energy
let KineticEnergy;
KineticEnergy = 0.5 * M * V * V;
return KineticEnergy;
}
// Function to calculate Potential Energy
function potentialEnergy(M, H) {
// Stores the Potential Energy
let PotentialEnergy;
PotentialEnergy = M * 9.8 * H;
return PotentialEnergy;
}
// Driver Code
let M = 5.5, H = 23.5, V = 10.5;
document.write("Kinetic Energy = "
+ kineticEnergy(M, V))
document.write("<br>");
document.write( "Potential Energy = "
+ potentialEnergy(M, H))
// This code is contributed by Hritik
</script>
Kinetic Energy = 303.188
Potential Energy = 1266.65
Time Complexity: O(1)Auxiliary Space: O(1)
bgangwar59
ankthon
hritikrommie
parthagarwal1962000
Mathematical
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 25365,
"s": 25334,
"text": " \n12 Jul, 2021\n"
},
{
"code": null,
"e": 25628,
"s": 25365,
"text": "Given three float values M, H, and V representing the mass, velocity, and height of an object respectively the task is to calculate its Kinetic Energy as well a... |
Using underscore in Numeric Literals in Java | Followig is the code showing how to use underscore in numeric literals in Java −
Live Demo
public class Demo{
public static void main (String[] args) throws java.lang.Exception{
int my_num_1 = 6_78_00_120;
System.out.println("The number is : " + my_num_1);
long my_num_2 = 2_00_11_001;
System.out.println("The number is : " + my_num_2);
float my_num_3 = 4.01_981F;
System.out.println("The number is : " + my_num_3);
double my_num_4 = 12.89_46_061;
System.out.println("The number is : " + my_num_4);
}
}
The number is : 67800120
The number is : 20011001
The number is : 4.01981
The number is : 12.8946061
A class named Demo contains the main function which uses various formats of integer, long, floating point values and double values to display data with the help of underscotres. This is assigned to a variable each, that is printed on the console. | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Followig is the code showing how to use underscore in numeric literals in Java −"
},
{
"code": null,
"e": 1154,
"s": 1143,
"text": " Live Demo"
},
{
"code": null,
"e": 1620,
"s": 1154,
"text": "public class Demo{\... |
Solving Sudoku with Convolution Neural Network | Keras | by Shiva Verma | Towards Data Science | I used to solve sudoku a long time ago. A few days back I was wondering if I can solve it with Convolution Neural Network(CNN). I knew Sudoku has spatial features since it has a particular arrangement of numbers and CNNs are good at extracting spatial features. Let’s see how this experiment goes.
I found the following data on Kaggle, which contains 1 million unsolved and solved Sudoku games. Please take a look at the data below.
The dataset contains 2 columns. The column quizzes has the unsolved games and the column solutions has respective solved games. Each game is represented by a string of 81 numbers. Following is a 9x9 sudoku converted from the string. The number 0 represents the blank position in unsolved games.
[[0 0 4 3 0 0 2 0 9] [0 0 5 0 0 9 0 0 1] [0 7 0 0 6 0 0 4 3] [0 0 6 0 0 2 0 8 7] [1 9 0 0 0 7 4 0 0] [0 5 0 0 8 3 0 0 0] [6 0 0 0 0 0 1 0 5] [0 0 3 5 0 8 6 9 0] [0 4 2 9 1 0 3 0 0]]
Our task is to feed the unsolved sudoku to a neural network and get the solved sudoku out of it. This means we have to feed 81 numbers to the network and need to have 81 output numbers from it.
We have to convert the input data(unsolved games) into a 3D array since we have to feed it to the CNN. I have converted each string of 81 numbers in a shape of (9,9,1). Then I normalized the input data by dividing it with 9 and subtracting 0.5. By doing so data becomes zero mean-centred and in the range of (-0.5 – 0.5). Neural networks generally perform better with zero centred normalized data.
In a typical multi-class classification, the neural network outputs scores for each class. Then we apply softmax function on the final scores to convert them into probabilities. And the data is classified into a class that has the highest probability value(refer to the following image).
But in sudoku, the scenario is different. We have to get 81 numbers for each position in the sudoku game, not just one. And we have a total of 9 classes for each number because a number can fall in a range of 1 to 9.
To comply with this design, our network should output 81x9 numbers. Where each row represents one of the 81 numbers, and each column represents one of 9 classes. Then we can apply softmax and take the maximum along with each row so that we have 81 numbers classified into one of the 9 classes.
I created the following simple network for this task. The network consists of 3 Convolution layers and one Dense layer on top for classification.
Note I am reshaping the output of the Dense layers in a shape of (81, 9) then adding a softmax layer on it. I compiled the model with sparse_categorical_crossentropy loss and adam optimizer.
Since we are using SCC loss, we don't need to provide a one-hot encoded target vector. Our target vectors shape is(81,1) where the vector elements represent the true class of 81 numbers.
I trained the network for 2 epochs, with batch size 64. The learning rate for the first epoch was 0.001 and for second epochs I reduced it to 0.0001. The final training loss settled down to 0.34. I tried a few different network architecture and strategies but could not reduce the loss further so I went ahead with this network. Its time to test the network.
Now, I tried to solve the game using our trained network. I saw that the network always predict few values wrong. Following is a game predicted by the network. You can see a few numbers repeating in rows and columns.
> Input (Unsolved)[[0 1 6 9 0 4 0 0 7] [0 0 4 0 3 0 0 8 0] [0 0 3 0 6 1 9 2 0] [5 0 9 1 4 0 8 0 0] [1 7 0 0 0 0 0 0 0] [0 0 8 7 0 0 0 6 5] [6 0 0 0 0 2 0 4 0] [0 2 0 8 0 5 3 1 0] [0 3 0 0 0 0 0 0 9]]> Output[[2 1 6 9 8 4 5 3 7] [2 9 4 2 3 7 6 8 1] [7 8 3 5 6 1 9 2 4] [5 6 9 1 4 6 8 7 3] [1 7 2 5 5 8 4 9 4] [4 4 8 7 2 9 1 6 5] [6 9 1 3 1 2 5 4 8] [9 2 7 8 9 5 3 1 6] [4 3 1 4 1 6 2 5 9]]
I had to try something else instead of changing network architecture to solve the game since training loss was not going below a certain number.
As humans when we solve Sudoku, we fill numbers one by one. We do not simply look at the sudoku once and fill all the numbers. The advantage of filling the numbers one by one is that each time we fill a number we keep getting a better idea about the next move.
I implemented the same approach while solving the sudoku now. Instead of predicting all 81 numbers at once, I am picking just one number among all blank position that has the highest probability value, and filling that number in the sudoku. After filling one number we again feed this puzzle to the network and make a prediction. We keep repeating this and filling the blank positions one by one with the highest probability number until we are left with no blank positions.
This approach boosted the performance and the network was able to solve almost all the games in this dataset. Test accuracy on 1000 games was 0.99.
Following is a sudoku game picked from the web, and the model solved it correctly. You can replace the following game string with your sudoku game in my jupyter notebook and check the results.
However I need to check my model on more authentic games picked form the web, since those games can be different from randomly generated ones. It takes a lot of time to manually copy the sudoku in string format, so I have left that part for the future.
Following is the GitHub link to this project with the saved model. I will keep posting more such projects.
github.com
If you enjoyed this article, then you should also check out the following article. | [
{
"code": null,
"e": 470,
"s": 172,
"text": "I used to solve sudoku a long time ago. A few days back I was wondering if I can solve it with Convolution Neural Network(CNN). I knew Sudoku has spatial features since it has a particular arrangement of numbers and CNNs are good at extracting spatial fea... |
MomentJS - Humanize | This method displays the date in human readable format.
moment.duration().humanize();
var a = moment.duration(24, "hours").humanize();
In case you need suffix such as ago or in to the output, add true to humanize as follows
var a = moment.duration(24, "hours").humanize(true);
var a = moment.duration(-1, "days").humanize(true);
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2016,
"s": 1960,
"text": "This method displays the date in human readable format."
},
{
"code": null,
"e": 2047,
"s": 2016,
"text": "moment.duration().humanize();\n"
},
{
"code": null,
"e": 2096,
"s": 2047,
"text": "var a = moment.duration... |
Count the number of ways to fill K boxes with N distinct items - GeeksforGeeks | 17 Nov, 2021
Given two values N and K. Find the number of ways to arrange the N distinct items in the boxes such that exactly K (K<N) boxes are used from the N distinct boxes. The answer can be very large so return the answer modulo 109 + 7.Note: 1 <= N <= K <= 105. Prerequisites: Factorial of a number, Compute nCr % p
Examples:
Input: N = 5, k = 5 Output: 120
Input: N = 5, k = 3 Output: 1500
Approach: We will use the inclusion-exclusion principle to count the ways.
Let us assume that the boxes are numbered 1 to N and now we have to choose any K boxes and use them. The number of ways to do this is NCK.Now any item can be put in any of the chosen boxes, hence the number of ways to arrange them is KN But here, we may count arrangements with some boxes empty. Hence, we will use the inclusion-exclusion principle to ensure that we count ways with all K boxes filled with at least one item.Let us understand the application of the inclusion-exclusion principle: So out of KN ways, we subtract the case when at least 1 box(out of K) is empty. Hence, subtract (KC1)*((K-1)N).Note that here, The cases where exactly two boxes are empty are subtracted twice(once when we choose the first element in (KC1) ways, and then when we choose the second element in (KC1) ways).Hence, we add these ways one time to compensate. So we add (KC2)*((K – 2)N).Similarly, here we need to add the number of ways when at least 3 boxes were empty, and so on...Hence, the total number of ways:
Let us assume that the boxes are numbered 1 to N and now we have to choose any K boxes and use them. The number of ways to do this is NCK.
Now any item can be put in any of the chosen boxes, hence the number of ways to arrange them is KN But here, we may count arrangements with some boxes empty. Hence, we will use the inclusion-exclusion principle to ensure that we count ways with all K boxes filled with at least one item.
Let us understand the application of the inclusion-exclusion principle: So out of KN ways, we subtract the case when at least 1 box(out of K) is empty. Hence, subtract (KC1)*((K-1)N).Note that here, The cases where exactly two boxes are empty are subtracted twice(once when we choose the first element in (KC1) ways, and then when we choose the second element in (KC1) ways).Hence, we add these ways one time to compensate. So we add (KC2)*((K – 2)N).Similarly, here we need to add the number of ways when at least 3 boxes were empty, and so on...
So out of KN ways, we subtract the case when at least 1 box(out of K) is empty. Hence, subtract (KC1)*((K-1)N).
Note that here, The cases where exactly two boxes are empty are subtracted twice(once when we choose the first element in (KC1) ways, and then when we choose the second element in (KC1) ways).
Hence, we add these ways one time to compensate. So we add (KC2)*((K – 2)N).
Similarly, here we need to add the number of ways when at least 3 boxes were empty, and so on...
Hence, the total number of ways:
C++
Java
Python3
C#
// C++ program to calculate the// above formula#include <bits/stdc++.h>#define mod 1000000007#define int long long using namespace std; // To store the factorials// of all numbersint factorial[100005]; // Function to calculate factorial// of all numbersvoid StoreFactorials(int n){ factorial[0] = 1; for (int i = 1; i <= n; i++) { factorial[i] = (i * factorial[i - 1]) % mod; }} // Calculate x to the power y// in O(log n) timeint Power(int x, int y){ int ans = 1; while (y > 0) { if (y % 2 == 1) { ans = (ans * x) % mod; } x = (x * x) % mod; y /= 2; } return ans;} // Function to find inverse mod of// a number xint invmod(int x){ return Power(x, mod - 2);} // Calculate (n C r)int nCr(int n, int r){ return (factorial[n] * invmod((factorial[r] * factorial[n - r]) % mod)) % mod;} int CountWays(int n,int k){ StoreFactorials(n); // Loop to compute the formula // evaluated int ans = 0; for (int i = k; i >= 0; i--) { if (i % 2 == k % 2) { // Add even power terms ans = (ans + (Power(i, n) * nCr(k, i)) % mod) % mod; } else { // Subtract odd power terms ans = (ans + mod - (Power(i, n) * nCr(k, i)) % mod) % mod; } } // Choose the k boxes which // were used ans = (ans * nCr(n, k)) % mod; return ans;} // Driver codesigned main(){ int N = 5; int K = 5; cout << CountWays(N, K) << "\n"; return 0;}
// Java program to calculate the// above formula import java.util.*; class GFG{ static long mod = 1000000007; // To store the factorials// of all numbersstatic long factorial[] = new long[100005]; // Function to calculate factorial// of all numbersstatic void StoreFactorials(int n){ factorial[0] = 1; for(int i = 1; i <= n; i++) { factorial[i] = (i * factorial[i - 1]) % mod; }} // Calculate x to the power y// in O(log n) timestatic long Power(long x, long y){ long ans = 1; while (y > 0) { if (y % 2 == 1) { ans = (ans * x) % mod; } x = (x * x) % mod; y /= 2; } return ans;} // Function to find inverse mod of// a number xstatic long invmod(long x){ return Power(x, mod - 2);} // Calculate (n C r)static long nCr(int n, int r){ return (factorial[n] * invmod((factorial[r] * factorial[n - r]) % mod)) % mod;} static long CountWays(int n,int k){ StoreFactorials(n); // Loop to compute the formula // evaluated long ans = 0; for(int i = k; i >= 0; i--) { if (i % 2 == k % 2) { // Add even power terms ans = (ans + (Power(i, n) * nCr(k, i)) % mod) % mod; } else { // Subtract odd power terms ans = (ans + mod - (Power(i, n) * nCr(k, i)) % mod) % mod; } } // Choose the k boxes which // were used ans = (ans * nCr(n, k)) % mod; return ans;} // Driver Code public static void main (String[] args){ int N = 5; int K = 5; System.out.print(CountWays(N, K) + "\n");} } // This code is contributed by math_lover
# Python3 program to calculate the# above formula mod = 1000000007 # To store the factorials# of all numbersfactorial = [0 for i in range(100005)] # Function to calculate factorial# of all numbersdef StoreFactorials(n): factorial[0] = 1 for i in range(1, n + 1, 1): factorial[i] = (i * factorial[i - 1]) % mod # Calculate x to the power y# in O(log n) timedef Power(x, y): ans = 1 while (y > 0): if (y % 2 == 1): ans = (ans * x) % mod x = (x * x) % mod y //= 2 return ans # Function to find inverse mod# of a number xdef invmod(x): return Power(x, mod - 2) # Calculate (n C r)def nCr(n, r): return ((factorial[n] * invmod((factorial[r] * factorial[n - r]) % mod)) % mod) def CountWays(n, k): StoreFactorials(n) # Loop to compute the formula # evaluated ans = 0 i = k while(i >= 0): if (i % 2 == k % 2): # Add even power terms ans = ((ans + (Power(i, n) * nCr(k, i)) % mod) % mod) else: # Subtract odd power terms ans = ((ans + mod - (Power(i, n) * nCr(k, i)) % mod) % mod) i -= 1 # Choose the k boxes which # were used ans = (ans * nCr(n, k)) % mod return ans # Driver codeif __name__ == '__main__': N = 5 K = 5 print(CountWays(N, K)) # This code is contributed by Surendra_Gangwar
// C# program to calculate the// above formula using System;using System.Collections;using System.Collections.Generic; class GFG{ static long mod = 1000000007; // To store the factorials// of all numbersstatic long []factorial = new long[100005]; // Function to calculate factorial// of all numbersstatic void StoreFactorials(int n){ factorial[0] = 1; for(int i = 1; i <= n; i++) { factorial[i] = (i * factorial[i - 1]) % mod; }} // Calculate x to the power y// in O(log n) timestatic long Power(long x, long y){ long ans = 1; while (y > 0) { if (y % 2 == 1) { ans = (ans * x) % mod; } x = (x * x) % mod; y /= 2; } return ans;} // Function to find inverse mod of// a number xstatic long invmod(long x){ return Power(x, mod - 2);} // Calculate (n C r)static long nCr(int n, int r){ return (factorial[n] * invmod((factorial[r] * factorial[n - r]) % mod)) % mod;} static long CountWays(int n,int k){ StoreFactorials(n); // Loop to compute the formula // evaluated long ans = 0; for(int i = k; i >= 0; i--) { if (i % 2 == k % 2) { // Add even power terms ans = (ans + (Power(i, n) * nCr(k, i)) % mod) % mod; } else { // Subtract odd power terms ans = (ans + mod - (Power(i, n) * nCr(k, i)) % mod) % mod; } } // Choose the k boxes which // were used ans = (ans * nCr(n, k)) % mod; return ans;} // Driver Code public static void Main (string[] args){ int N = 5; int K = 5; Console.Write(CountWays(N, K) + "\n");} } // This code is contributed by rutvik_56
120
Time complexity: O(N*log N)
Auxiliary Space: O(105)
SURENDRA_GANGWAR
rutvik_56
math_lover
subham348
Arrays
Combinatorial
Mathematical
Arrays
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
Trapping Rain Water
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Count ways to reach the nth stair using step 1, 2 or 3 | [
{
"code": null,
"e": 24742,
"s": 24714,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 25050,
"s": 24742,
"text": "Given two values N and K. Find the number of ways to arrange the N distinct items in the boxes such that exactly K (K<N) boxes are used from the N distinct boxes. ... |
How to check if a string is a valid keyword in Java? | To check if a string is a valid keyword in Java, the code is as follows −
Live Demo
import java.util.*;
public class Demo{
static boolean valid_identifier(String my_str, int n){
if (!((my_str.charAt(0) >= 'a' && my_str.charAt(0) <= 'z')
|| (my_str.charAt(0)>= 'A' && my_str.charAt(1) <= 'Z')
|| my_str.charAt(0) == '_'))
return false;
for (int i = 1; i < my_str.length(); i++){
if (!((my_str.charAt(i) >= 'a' && my_str.charAt(i) <= 'z')
|| (my_str.charAt(i) >= 'A' && my_str.charAt(i) <= 'Z')
|| (my_str.charAt(i) >= '0' && my_str.charAt(i) <= '9')
|| my_str.charAt(i) == '_'))
return false;
}
return true;
}
public static void main(String args[]){
String my_str = "Hi_there!3";
int n = my_str.length();
if (valid_identifier(my_str, n))
System.out.println("It is valid");
else
System.out.println("It is invalid");
}
}
It is invalid
A class named Demo contains a function named ‘valid_identifier’ that returns Boolean output. It takes a string and an integer, checks to see if the string contains characters between ‘a’ to ‘z’ or ‘A’ to ‘Z’ or an underscore character, otherwise returns false. It iterates through the length of the string, and checks for the validity of the string and sees if it contains integers between ‘0’ and ‘9’ too. Otherwise, it returns false. In the main function, the string is defined, and the length of the string is assigned to a variable. The function is called by passing the string and the string length. This displays the relevant message. | [
{
"code": null,
"e": 1136,
"s": 1062,
"text": "To check if a string is a valid keyword in Java, the code is as follows −"
},
{
"code": null,
"e": 1147,
"s": 1136,
"text": " Live Demo"
},
{
"code": null,
"e": 2040,
"s": 1147,
"text": "import java.util.*;\npubli... |
SQL Tryit Editor v1.6 | 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. | [
{
"code": null,
"e": 98,
"s": 35,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 158,
"s": 98,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 226,
"s": 158,
"tex... |
Count of subsets with sum equal to X | Set-2 - GeeksforGeeks | 11 Feb, 2022
Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X.
Examples:
Input: arr[] = {1, 2, 3, 3}, X = 6 Output: 3 Explanation: All the possible subsets are {1, 2, 3}, {1, 2, 3} and {3, 3}.
Input: arr[] = {1, 1, 1, 1}, X = 1 Output: 4
Space Efficient Approach: This problem has already been discussed in the article here. This article focuses on a similar Dynamic Programming approach which uses only O(X) space. The standard DP relation of solving this problem as discussed in the above article is:
dp[i][C] = dp[i – 1][C – arr[i]] + dp[i – 1][C]
where dp[i][C] stores the number of subsets of the subarray arr[0... i] such that their sum is equal to C. It can be noted that the dp[i]th state only requires the array values of the dp[i – 1]th state. Hence the above relation can be simplified into the following:
dp[C] = dp[C – arr[i]] + dp[C]
Here, a good point to note is that during the calculation of dp[C], the variable C must be iterated in decreasing order in order to avoid the duplicity of arr[i] in the subset-sum count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of subsets// having the given sumint subsetSum(int arr[], int n, int sum){ // Initializing the dp-table int dp[sum + 1] = {}; // Case for sum of elements in empty set dp[0] = 1; // Loop to iterate over array elements for (int i = 0; i < n; i++) { for (int j = sum; j >= 0; j--) { // If j-arr[i] is a valid index if (j - arr[i] >= 0) { dp[j] = dp[j - arr[i]] + dp[j]; } } } // Return answer return dp[sum];} // Driven Codeint main(){ int arr[] = { 1, 1, 1, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int sum = 1; cout << subsetSum(arr, N, sum) << endl; return 0;}
// Java implementation of the above approachimport java.util.*;public class GFG{ // Function to find the count of subsets// having the given sumstatic int subsetSum(int arr[], int n, int sum){ // Initializing the dp-table int dp[] = new int[sum + 1]; // Case for sum of elements in empty set dp[0] = 1; // Loop to iterate over array elements for (int i = 0; i < n; i++) { for (int j = sum; j >= 0; j--) { // If j-arr[i] is a valid index if (j - arr[i] >= 0) { dp[j] = dp[j - arr[i]] + dp[j]; } } } // Return answer return dp[sum];} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 1, 1, 1 }; int N = arr.length; int sum = 1; System.out.println(subsetSum(arr, N, sum));}} // This code is contributed by Samim Hossain Mondal.
# Python implementation of the above approach # Function to find the count of subsets# having the given sumdef subsetSum(arr, n, sum): # Initializing the dp-table dp = [0] * (sum + 1) # Case for sum of elements in empty set dp[0] = 1; # Loop to iterate over array elements for i in range(n): for j in range(sum, 0, -1): # If j-arr[i] is a valid index if (j - arr[i] >= 0): dp[j] = dp[j - arr[i]] + dp[j]; # Return answer return dp[sum]; # Driven Codearr = [1, 1, 1, 1];N = len(arr)sum = 1; print(subsetSum(arr, N, sum)) # This code is contributed by gfgking.
// C# implementation of the above approachusing System; public class GFG{ // Function to find the count of subsets// having the given sumstatic int subsetSum(int []arr, int n, int sum){ // Initializing the dp-table int []dp = new int[sum + 1]; // Case for sum of elements in empty set dp[0] = 1; // Loop to iterate over array elements for (int i = 0; i < n; i++) { for (int j = sum; j >= 0; j--) { // If j-arr[i] is a valid index if (j - arr[i] >= 0) { dp[j] = dp[j - arr[i]] + dp[j]; } } } // Return answer return dp[sum];} // Driver codepublic static void Main(String []args){ int []arr = { 1, 1, 1, 1 }; int N = arr.Length; int sum = 1; Console.WriteLine(subsetSum(arr, N, sum));}} // This code is contributed by shikhasingrajput
<script>// Javascript implementation of the above approach // Function to find the count of subsets// having the given sumfunction subsetSum(arr, n, sum){ // Initializing the dp-table let dp = new Array(sum + 1).fill(0) // Case for sum of elements in empty set dp[0] = 1; // Loop to iterate over array elements for (let i = 0; i < n; i++) { for (let j = sum; j >= 0; j--) { // If j-arr[i] is a valid index if (j - arr[i] >= 0) { dp[j] = dp[j - arr[i]] + dp[j]; } } } // Return answer return dp[sum];} // Driven Codelet arr = [1, 1, 1, 1];let N = arr.length;let sum = 1; document.write(subsetSum(arr, N, sum)) // This code is contributed by gfgking.</script>
4
Time Complexity: O(N * X)Auxiliary Space: O(X)
gfgking
samim2000
shikhasingrajput
sagartomar9927
prasanna1995
subset
Arrays
Dynamic Programming
Arrays
Dynamic Programming
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Bellman–Ford Algorithm | DP-23
Longest Common Subsequence | DP-4
Floyd Warshall Algorithm | DP-16 | [
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 24938,
"s": 24822,
"text": "Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X."
},
{
"code": null,
"e": 24949,
... |
BigInteger multiply() Method in Java with Examples - GeeksforGeeks | 12 Apr, 2019
The java.math.BigInteger.multiply(BigInteger val) is used to calculate the multiplication of two BigIntegers. As BigInteger class internally uses an array of integers for processing, the operation on an object of BigInteger are not as fast as on primitives.
Syntax:
public BigInteger multiply(BigInteger val)
Parameters: This method accepts a parameter val which is the value to be multiplied to this BigInteger.
Return value: This method returns a BigInteger which holds multiplication (this * val).
Below programs is used to illustrate the multiply() method of BigInteger.
Example 1:
// Java program to demonstrate// multiply() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger mult; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values to calculate the multiplication String input1 = "012345678901234567" + "654632498739473"; String input2 = "0123456789012345" + "61247612748612746"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using multiply() method mult = a.multiply(b); // Display the result in BigInteger System.out.println("The multiplication of\n" + a + " \nand\n" + b + " " + "\nis\n" + mult); }}
Output:
The multiplication of12345678901234567654632498739473and12345678901234561247612748612746is152415787532388282591353462245536419067346861445890674421122858
Example 2:
// Java program to demonstrate// multiply() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger mult; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values to calculate the multiplication String input1 = "012345678901234567" + "8901234567890123" + "4567890123456789" + "0123456789012345" + "6789012345678901" + "654632498739473"; String input2 = "0123456789012345" + "6789012345678901" + "2345678901234567" + "8901234567890123" + "4567890123456789" + "61247612748612746"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using multiply() method mult = a.multiply(b); // Display the result in BigInteger System.out.println("The multiplication of\n" + a + " \nand\n" + b + " " + "\nis\n" + mult + "\n"); // Using double to hold the result double d = Double.parseDouble(mult.toString()); // Display the result in double System.out.println("Using double, multiplication is " + d); }}
Output:
The multiplication of123456789012345678901234567890123456789012345678901234567890123456789012345678901654632498739473and123456789012345678901234567890123456789012345678901234567890123456789012345678961247612748612746is15241578753238836750495351562566681945008382873376009755225118122311263526910008985036532509972574264073578551235889967606442208008929541925721486305055001841778994861500543809890674421122858
Using double, multiplication is 1.5241578753238838E190
As from the above examples, it is clear that the data is full precise when BigInteger is used.
Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigInteger.html#multiply(java.math.BigInteger)
Java-BigInteger
Java-Functions
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Set in Java
Initializing a List in Java
Exceptions in Java
LinkedList in Java
Queue Interface In Java | [
{
"code": null,
"e": 24516,
"s": 24488,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 24774,
"s": 24516,
"text": "The java.math.BigInteger.multiply(BigInteger val) is used to calculate the multiplication of two BigIntegers. As BigInteger class internally uses an array of integ... |
How to save the contents of a Textbox in Tkinter? | To save the contents of a Textbox in Tkinter, we can take the following steps −
Create an instance of tkinter frame.
Create an instance of tkinter frame.
Set the size of the frame using win.geometry method.
Set the size of the frame using win.geometry method.
Define a user-defined method "open_text" to open a text file in "read" mode. Read the contents of the text file and save it in a variable called "content". Then, use the "insert" method to insert the contentin a Textbox.
Define a user-defined method "open_text" to open a text file in "read" mode. Read the contents of the text file and save it in a variable called "content". Then, use the "insert" method to insert the contentin a Textbox.
Next, define another user-defined method called "save_text" and in it, use the "write" method to save the contents of the textbox in the text file.
Next, define another user-defined method called "save_text" and in it, use the "write" method to save the contents of the textbox in the text file.
Create a text widget using the Text method with specified height and width.
Create a text widget using the Text method with specified height and width.
Create a button to call the open_text method.
Create a button to call the open_text method.
Create a button to call the open_text method.
Create a button to call the open_text method.
Finally, run the mainloop of the application window.
Finally, run the mainloop of the application window.
# Import tkinter library
from tkinter import *
# Create an instance of tkinter window
win = Tk()
win.geometry("700x250")
def open_text():
text_file = open("test.txt", "r")
content = text_file.read()
my_text_box.insert(END, content)
text_file.close()
def save_text():
text_file = open("test.txt", "w")
text_file.write(my_text_box.get(1.0, END))
text_file.close()
# Creating a text box widget
my_text_box = Text(win, height=10, width=40)
my_text_box.pack()
open_btn = Button(win, text="Open Text File", command=open_text)
open_btn.pack()
# Create a button to save the text
save = Button(win, text="Save File", command=save_text)
save.pack()
win.mainloop()
When you execute the code, it will show the following screen −
Now, click the "Open Text File" button to open the text file "test.txt". It will display the contents of the file in the Textbox.
Next, type a new line inside the Textbox and click "Save File" to save the contents in "test.txt". | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To save the contents of a Textbox in Tkinter, we can take the following steps −"
},
{
"code": null,
"e": 1179,
"s": 1142,
"text": "Create an instance of tkinter frame."
},
{
"code": null,
"e": 1216,
"s": 1179,
"te... |
Julia For Data Science. Python and R are undoubtedly the... | by Bernard Brenyah | Towards Data Science | Currently, Python and R are undoubtedly the most widely used programming languages in the machine learning world. Unfortunately, the high-level and elegant abstractions from these programming usually come at a cost, especially when working with large systems. Before we even begin, this post will not be some endless bashing of either Python or R so any reader with such expectations should look elsewhere. Rather, this post seeks to enlighten and inform readers about the potential addition of Julia to their toolbox. At the end of the day, all these programming languages are mere tools with different use cases.
Julia is described as a dynamic programming language which focuses on being highly performant even with high-level abstractions. As a result, this language is well suited for numerical and scientific computing. Julia was co-created by 4 computer scientists (3 of which are pictured below ) in 2009.
This line has been one of the most-used references, to sum up, the main advantage of this programming language. Some readers may have read about the infamous “two language problem”. For the uninitiated ones, the two language problem simply describes the situation where;
developers have to re-write the critical and performant parts of a codebase in a low-level language like C/C++ as high-level languages like Python/R can be slow with certain tasks due to their high-level abstractions
It is comparably easier to quickly prototype new ideas in high-level languages like Python and R. A major reason why these languages have such a dominant position in the data science ecosystem which heavily relies on trying new ideas as quickly as possible. The tradeoff (in terms of speed) here is acceptable for small and medium scale applications but very noticeable on large scale systems and applications.
Julia is being dubbed as the language that can solve this two-language problem by offering the friendliness of a high-level language like Python/R while matching the speed of a low-level language like C/C++.
I had heard about Julia but I always wondered about its usage. Is it as easy as it is with Python/R?
This post simply tries to test this assertion by building from scratch multivariate linear regression using gradient descent with Julia. I have been using both Python and R for some years now so I decided to see how fast I can use Julia to quickly solve such a task. This post won’t be a benchmark test between Julia and other languages as such tests are well covered but rather a focus on the user-friendliness of the language to someone who is used to Python/R. I will end the post with some final thoughts after this process.
The dataset that will be used for this test is the Combined Cycle Power Plant Data Set (Sheet5) from the UCI data repository. The aim here is to generate a model that can predict Net hourly electrical energy output (EP) from 4 numerical (continuous) features:
Temperature (AT) in the range 1.81°C and 37.11°C.
Exhaust Vacuum (V) in the range 25.36–81.56 cm Hg.
Ambient Pressure (AP) in the range 992.89–1033.30 millibar.
Relative Humidity (RH) in the range of 25.56% to 100.16%.
The plan of attack for this experiment is just like a typical modelling workflow where the data will be:
loaded into memory: The data is loaded into memory as a DataFrame object that most readers will already be familiar with this code snippet:
pre-processed for algorithms: With the data loaded successfully loaded into memory, let’s now split it into a training and validation set using a ratio of 80% for the training of the model with 20% withheld for the evaluation of the generated model. This code snippet below does the trick (but a more robust way is to shuffle the indices). The goal is to quickly get up and running so this will suffice for now.
As you may have noticed, the features are on different scales (from percentages to millibars) which might be problematic for most algorithms so it’s common practice to standardise features so that they can be on the same ‘scale’. The two functions in the code snippet below are used to standardise both the training and testing features.
Our data is now pre-processed and ready for modelling.
model fitting & evaluation: The objective here is to find a linear model that best minimises the good old mean square error function. Our mean squared cost function is essentially a half mean squared function and it’s defined as follows:
With our cost function defined, let’s deploy gradient descent to find us the best weights for each of the features (including a constant as well) that minimises this cost function. The next function takes care of that:
NB: This implementation implements gradient descent without regularisation (which I encourage you to add to your own implementations).
Let’s now check if gradient descent works and minimises our cost function by plotting our cost history vector J:
As one can see from the plot, the cost drops as the number of iterations increases until it flatlines at some point. It appears that gradient descent is doing a good job of finding the weights that minimise our cost function.
It’s now time to make some predictions and evaluate the performance of our new shiny regression model. Two new functions are used to generate predictions and score both the training and testing datasets.
From the scoring function, the Root Mean Square Error (RMSE) for the training and testing set are:
RMSE for Training Set: 4.578258826855693RMSE for Testing Set: 4.473104537374325
Let’s now look at the predictive powers (in terms of R-squared value) of the model in both datasets as well with this function:
Training R2 score for test sets: 0.9274046053983883Testing R2 score for test sets: 0.9335248094191678
The scores appear to show that some decent predictive powers (0.927 & 0.934)!
However, the testing score is better than the training score which appears to suggest that the model is underfitting data. Tinkering with the alpha term (α) and/or the number of iterations (n_iter) should squeeze more performance from this model but I will leave that up to readers to tinker with.
From this experiment, I naturally have some likes and dislikes with Julia based on my previous interactions with Python and R.
Likes
Native Unicode/notation support: My favourite Julia is undoubtedly its native support for Unicode and scientific notations. There’s something cool and neat about using ‘θ’ instead of ‘theta’, ‘α’ instead of ‘alpha’ and in a script. It’s a language built from ground up for scientific/numeric computing! I found myself using smiling every time I had to use scientific notation.
Readable syntax: The syntax of a language plays a key role in its ability to quickly prototype ideas in. Julia’s syntax is not that different from Python. Personally, Julia feels like a love child between Python and Matlab in terms of its syntax. A quick lookup of the documentation, in most cases, was I needed to get past some bad syntax calls. Additionally, it’s very easy to share and read scientific code with real scientific notations!
Support for existing Python/R ecosystem: As a young language, it is expected that some much-needed packages are missing from the eco-system. It is, however, refreshing to know that existing Python/R packages can be used in Julia. This functionality allows Julia to enjoy the benefits of matured eco-systems and avoids the needless need to re-invent certain wheels.
Dislikes
Slow pre-compiling time: The first thing one notices is the time it takes to load packages in Julia compared to Python/R. Loading of packages every time requires pre-compiling which does take some noticeable seconds (more than 10 seconds). This can be frustrating for Python/R users who are so used to instantaneous package imports.
Young language/eco-system: There is almost always a package for some common data wrangling tasks in either Python/R. Julia, as a newcomer, naturally doesn’t have such a native rich eco-system that established languages enjoy. However, this issue can be addressed for now with the support for imports from both Python and R using PyCall & JuliaCall packages.
Lack of traditional OOP support: Part of the charm and wide-spread adoption of Python for data science application is the neat and convenient way functions are constructed with object-oriented programming. For example, it would have been neat and tidy if all the pre-processing functions as well all the learned parameters were available under one class. Julia adopts the “multiple dispatch” paradigm which helps it to be so fast compared to other high-level languages.
Julia is a promising language that is built from the ground up for numerical and scientific computing. In this post, I have shown that it’s relatively easy to prototype in Julia and successfully implemented a multivariate linear regression using gradient descent. It’s one language that every data should at least keep and a digital eye on. There are some amazing data science packages out there for Julia. Grab some dataset, play with Julia and let me know what you think? The best way to get up and running, in my opinion, is to install JuliaPro which comes with an IDE using Atom.
As always I look forward to feedback (good or bad!). The script with all the functions for this post can be found on the GitHub repository for this blog. Finally, you can check out other posts on my personal blog. Until the next post, happy coding in Julia! | [
{
"code": null,
"e": 787,
"s": 172,
"text": "Currently, Python and R are undoubtedly the most widely used programming languages in the machine learning world. Unfortunately, the high-level and elegant abstractions from these programming usually come at a cost, especially when working with large syst... |
Python - Bubble Charts | Bubble charts display data as a cluster of circles. The required data to create bubble chart needs to have the xy coordinates, size of the bubble and the colour of the bubbles. The colours can be supplied by the
library itself.
Bubble chart can be created using the DataFrame.plot.scatter() methods.
import matplotlib.pyplot as plt
import numpy as np
# create data
x = np.random.rand(40)
y = np.random.rand(40)
z = np.random.rand(40)
colors = np.random.rand(40)
# use the scatter function
plt.scatter(x, y, s=z*1000,c=colors)
plt.show()
Its output is as follows −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2758,
"s": 2529,
"text": "Bubble charts display data as a cluster of circles. The required data to create bubble chart needs to have the xy coordinates, size of the bubble and the colour of the bubbles. The colours can be supplied by the \nlibrary itself."
},
{
"code": n... |
How to compare two string arrays, case insensitive and independent about ordering JavaScript, ES6 | We are required to write a function, say isEqual() that takes in two strings as argument and
checks if they both contains the same characters independent of their order and case.
For example −
const first = 'Aavsg';
const second = 'VSAAg';
isEqual(first, second); //true
In this method we convert the strings into arrays, make use of the Array.prototype.sort() method,
convert them back into strings and check for equality.
The code for this will be −
const first = 'Aavsg';
const second = 'VSAAg';
const stringSort = function(){
return this.split("").sort().join("");
}
String.prototype.sort = stringSort;
const isEqual = (first, second) => first.toLowerCase().sort() ===
second.toLowerCase().sort();
console.log(isEqual(first, second));
In this method we iterate over both the strings at the same time, store the character frequencies in a
map with values like this −
-1, if it appears in the first string,
+1, if it appears in the second string,
At last, if all the keys add up 0, we conclude that that the strings are same otherwise not.
The code for this will be −
const first = 'Aavsg';
const second = 'VSAAg';
const isEqual = (first, second) => {
if(first.length !== second.length){
return false;
}
first = first.toLowerCase();
second = second.toLowerCase();
const map = {};
for(ind in first){
if(map[first[ind]]){
map[first[ind]]++;
}else{
map[first[ind]] = 1;
}
if(map[second[ind]]){
map[second[ind]]--;
}else{
map[second[ind]] = -1;
}
};
return Object.values(map).reduce((acc, val) => val === 0 && acc, true);
};
console.log(isEqual(first, second));
The output in the console for both will be −
true | [
{
"code": null,
"e": 1241,
"s": 1062,
"text": "We are required to write a function, say isEqual() that takes in two strings as argument and\nchecks if they both contains the same characters independent of their order and case."
},
{
"code": null,
"e": 1255,
"s": 1241,
"text": "Fo... |
How to prevent MySQL double insert (duplicate entry)? | To prevent duplicate entry, add constraint UNIQUE. Let us first create a table −
mysql> create table DemoTable
(
Id int,
Name varchar(100)
);
Query OK, 0 rows affected (0.79 sec)
Here is the query to prevent MySQL double insert using UNIQUE −
mysql> alter table DemoTable add constraint id_NameUnKey UNIQUE(Id,Name);
Query OK, 0 rows affected (0.82 sec)
Records: 0 Duplicates: 0 Warnings: 0
Insert records in the table using insert command. When we will try to the same record again, then the “Duplicate entry” error will be visible −
mysql> insert into DemoTable values(11,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(12,'John');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(11,'John');
ERROR 1062 (23000): Duplicate entry '11-John' for key 'id_NameUnKey'
Display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+------+------+
| Id | Name |
+------+------+
| 11 | John |
| 12 | John |
+------+------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "To prevent duplicate entry, add constraint UNIQUE. Let us first create a table −"
},
{
"code": null,
"e": 1247,
"s": 1143,
"text": "mysql> create table DemoTable\n(\n Id int,\n Name varchar(100)\n);\nQuery OK, 0 rows affected (0.... |
Merge Sort using Multithreading in C++ | We are given an unsorted integer array. The task is to sort the array using merge sort technique implemented via Multi-threading
Merge sort is a sorting technique which is based on divide and conquer technique where we divide the array into equal halves and then combine them in a sorted manner.
check if there is one element in the list then return the element.
check if there is one element in the list then return the element.
Else, Divide the data recursively into two halves until it can’t be divided further.
Else, Divide the data recursively into two halves until it can’t be divided further.
Finally, merge the smaller lists into new lists in sorted order.
Finally, merge the smaller lists into new lists in sorted order.
In the operating system, Threads are the lightweight process which is responsible for executing the part of a task. Threads share common resources to execute the task concurrently.
Multi-threading is an implementation of multitasking where we can run multiple threads on a single processor to execute the tasks concurrently. It subdivides specific operations within a single application into individual threads. Each of the threads can run in parallel.
In −int arr[] = {3, 2, 1, 10, 8, 5, 7, 9, 4}
Out −Sorted array is: 1, 2, 3, 4, 5, 7, 8, 9, 10
Explanation −we are given an unsorted array with integer values. Now we will sort the array using merge sort with multithreading.
In −int arr[] = {5, 3, 1, 45, 32, 21, 50}
Out −Sorted array is: 1, 3, 5, 21, 32, 45, 50
Explanation −we are given an unsorted array with integer values. Now we will sort the array using merge sort with multithreading.
We will start by generating the random numbers using the rand() method in C++ STL.
We will start by generating the random numbers using the rand() method in C++ STL.
Create an array of pthread_t type i.e. P_TH[thread_size].
Create an array of pthread_t type i.e. P_TH[thread_size].
Start loop FOR from i to 0 till i is less than the size of a thread. Inside the loop, call pthread_create(&P_TH[i], NULL, Sorting_Threading, (void*)NULL) method to create the thread with given array values.
Start loop FOR from i to 0 till i is less than the size of a thread. Inside the loop, call pthread_create(&P_TH[i], NULL, Sorting_Threading, (void*)NULL) method to create the thread with given array values.
Call function as combine_array(0, (size / 2 - 1) / 2, size / 2 - 1), combine_array(size / 2, size/2 + (size-1-size/2)/2, size - 1) and combine_array(0, (size - 1)/2, size - 1)
Call function as combine_array(0, (size / 2 - 1) / 2, size / 2 - 1), combine_array(size / 2, size/2 + (size-1-size/2)/2, size - 1) and combine_array(0, (size - 1)/2, size - 1)
Print the sorted array stored in a arr[] of integer type.
Print the sorted array stored in a arr[] of integer type.
Inside the function void* Sorting_Threading(void* arg)Declare a variable as set_val to temp_val++, first to set_val * (size / 4), end to (set_val + 1) * (size / 4) - 1 and mid_val to first + (end - first) / 2Check IF first less than end then call Sorting_Threading(first, mid_val), Sorting_Threading(mid_val + 1, end) and combine_array(first, mid_val, end);
Inside the function void* Sorting_Threading(void* arg)
Declare a variable as set_val to temp_val++, first to set_val * (size / 4), end to (set_val + 1) * (size / 4) - 1 and mid_val to first + (end - first) / 2
Declare a variable as set_val to temp_val++, first to set_val * (size / 4), end to (set_val + 1) * (size / 4) - 1 and mid_val to first + (end - first) / 2
Check IF first less than end then call Sorting_Threading(first, mid_val), Sorting_Threading(mid_val + 1, end) and combine_array(first, mid_val, end);
Check IF first less than end then call Sorting_Threading(first, mid_val), Sorting_Threading(mid_val + 1, end) and combine_array(first, mid_val, end);
Inside the function void Sorting_Threading(int first, int end)Declare variable as mid_val to first + (end - first) / 2Check IF first less than end then call Sorting_Threading(first, mid_val), Sorting_Threading(mid_val + 1, end) and combine_array(first, mid_val, end)
Inside the function void Sorting_Threading(int first, int end)
Declare variable as mid_val to first + (end - first) / 2
Declare variable as mid_val to first + (end - first) / 2
Check IF first less than end then call Sorting_Threading(first, mid_val), Sorting_Threading(mid_val + 1, end) and combine_array(first, mid_val, end)
Check IF first less than end then call Sorting_Threading(first, mid_val), Sorting_Threading(mid_val + 1, end) and combine_array(first, mid_val, end)
Inside the function void combine_array(int first, int mid_val, int end)Declare variables as int* start to new int[mid_val - first + 1], int* last to new int[end - mid_val], temp_1 to mid_val - first + 1, temp_2 to end - mid_val, i, j, k to first.Start loop FOR from i to 0 till i less than temp_1. Inside the loop, set start[i] to arr[i + first].Start loop FOR from i to 0 till i less than temp_2. Inside the loop, set last[i] to arr[i + mid_val + 1]Set i to j to 0. Start loop While i is less than temp_1 AND j less than temp_2. Inside the while, check IF start[i] less than last[j] then set arr[k++] to start[i++]. ELSE, set arr[k++] = last[j++]Start WHILE i less than temp_1 then set arr[k++] = start[i++]. Start WHILE j less than temp_2 then set arr[k++] to last[j++]
Inside the function void combine_array(int first, int mid_val, int end)
Declare variables as int* start to new int[mid_val - first + 1], int* last to new int[end - mid_val], temp_1 to mid_val - first + 1, temp_2 to end - mid_val, i, j, k to first.
Declare variables as int* start to new int[mid_val - first + 1], int* last to new int[end - mid_val], temp_1 to mid_val - first + 1, temp_2 to end - mid_val, i, j, k to first.
Start loop FOR from i to 0 till i less than temp_1. Inside the loop, set start[i] to arr[i + first].
Start loop FOR from i to 0 till i less than temp_1. Inside the loop, set start[i] to arr[i + first].
Start loop FOR from i to 0 till i less than temp_2. Inside the loop, set last[i] to arr[i + mid_val + 1]
Start loop FOR from i to 0 till i less than temp_2. Inside the loop, set last[i] to arr[i + mid_val + 1]
Set i to j to 0. Start loop While i is less than temp_1 AND j less than temp_2. Inside the while, check IF start[i] less than last[j] then set arr[k++] to start[i++]. ELSE, set arr[k++] = last[j++]
Set i to j to 0. Start loop While i is less than temp_1 AND j less than temp_2. Inside the while, check IF start[i] less than last[j] then set arr[k++] to start[i++]. ELSE, set arr[k++] = last[j++]
Start WHILE i less than temp_1 then set arr[k++] = start[i++]. Start WHILE j less than temp_2 then set arr[k++] to last[j++]
Start WHILE i less than temp_1 then set arr[k++] = start[i++]. Start WHILE j less than temp_2 then set arr[k++] to last[j++]
#include <iostream>
#include <pthread.h>
#include <time.h>
#define size 20
#define thread_size 4
using namespace std;
int arr[size];
int temp_val = 0;
void combine_array(int first, int mid_val, int end){
int* start = new int[mid_val - first + 1];
int* last = new int[end - mid_val];
int temp_1 = mid_val - first + 1;
int temp_2 = end - mid_val;
int i, j;
int k = first;
for(i = 0; i < temp_1; i++){
start[i] = arr[i + first];
}
for (i = 0; i < temp_2; i++){
last[i] = arr[i + mid_val + 1];
}
i = j = 0;
while(i < temp_1 && j < temp_2){
if(start[i] <= last[j]){
arr[k++] = start[i++];
}
else{
arr[k++] = last[j++];
}
}
while (i < temp_1){
arr[k++] = start[i++];
}
while (j < temp_2){
arr[k++] = last[j++];
}
}
void Sorting_Threading(int first, int end){
int mid_val = first + (end - first) / 2;
if(first < end){
Sorting_Threading(first, mid_val);
Sorting_Threading(mid_val + 1, end);
combine_array(first, mid_val, end);
}
}
void* Sorting_Threading(void* arg){
int set_val = temp_val++;
int first = set_val * (size / 4);
int end = (set_val + 1) * (size / 4) - 1;
int mid_val = first + (end - first) / 2;
if (first < end){
Sorting_Threading(first, mid_val);
Sorting_Threading(mid_val + 1, end);
combine_array(first, mid_val, end);
}
}
int main(){
for(int i = 0; i < size; i++){
arr[i] = rand() % 100;
}
pthread_t P_TH[thread_size];
for(int i = 0; i < thread_size; i++){
pthread_create(&P_TH[i], NULL, Sorting_Threading, (void*)NULL);
}
for(int i = 0; i < 4; i++){
pthread_join(P_TH[i], NULL);
}
combine_array(0, (size / 2 - 1) / 2, size / 2 - 1);
combine_array(size / 2, size/2 + (size-1-size/2)/2, size - 1);
combine_array(0, (size - 1)/2, size - 1);
cout<<"Merge Sort using Multi-threading: ";
for (int i = 0; i < size; i++){
cout << arr[i] << " ";
}
return 0;
}
If we run the above code it will generate the following Output
Merge Sort using Multi-threading: 15 21 26 26 27 35 36 40 49 59 62 63 72 77 83 86 86 90 92 93 | [
{
"code": null,
"e": 1191,
"s": 1062,
"text": "We are given an unsorted integer array. The task is to sort the array using merge sort technique implemented via Multi-threading"
},
{
"code": null,
"e": 1358,
"s": 1191,
"text": "Merge sort is a sorting technique which is based on d... |
Set small modal in Bootstrap | Use the .modal-sm class in Bootstrap to set small modal with less width.
You can try to run the following code to implement the .modal-sm class −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h2>Examination</h2>
<button type = "button" class = "btn btn-lg" data-toggle = "modal" data-target = "#new">Result</button>
<div class = "modal fade" id = "new" role = "dialog">
<div class = "modal-dialog modal-sm">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss = "modal">×</button>
<h4 class = "modal-title">Warning</h4>
</div>
<div class = "modal-body">
<p>If JavaScript isn't enabled in your web browser, then you may not be able to see the result.</p>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-primary" data-dismiss = "modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "Use the .modal-sm class in Bootstrap to set small modal with less width."
},
{
"code": null,
"e": 1208,
"s": 1135,
"text": "You can try to run the following code to implement the .modal-sm class −"
},
{
"code": null,
"e":... |
Basic Concepts of Natural Language Processing (NLP) Models and Python Implementation | by Prasun Biswas | Towards Data Science | In the data science domain, Natural Language Processing (NLP) is a very important component for its vast applications in various industries/sectors. For a human it’s pretty easy to understand the language but machines are not capable enough to recognize it easily. NLP is the technique that enables the machines to interpret and to understand the way humans communicate.
At present social media is a golden data mine for natural languages, be it any type of reviews from any online sites (Amazon, Google, etc.), or simply posts from Twitter, Facebook, LinkedIn, or emails. The business use cases (Classifications, Text Summarization, Triaging, Interactive voice responses (IVR), Language translation, Chatbots) might be different in each sector but NLP defines the core underlying solution of these use cases.
Natural languages are a free form of text which means it is very much unstructured in nature. So, cleaning and preparing the data to extract the features are very important for the NLP journey while developing any model. This article will cover below the basic but important steps and show how we can implement them in python using different packages and develop an NLP-based classification model.
A) Data Cleaning
B) Tokenization
C) Vectorization/Word Embedding
D) Model Development
As mentioned above, data cleaning is basic but very important step in NLP. Below are a few ways for data cleaning. Let’s consider the below line.
line = ‘Reaching out for HELP. Please meet me in LONDON at 6 a.m xyz@abc.com #urgent’
1. Remove stopwords: There are a few words which are very commonly used when humans interact, but these words don’t make any sense or add any extra value. Additionally, there might be few words which are not required for the business case given in hand. So, these words need to be deleted from the data.
The NLTK package has a defined set of stopwords for different languages like English. Here, we will focus on ‘english’ stopwords. One can also consider additional stopwords if required.
import nltkimport refrom nltk.corpus import stopwords# Additional stopwordsextra_list = [“let”, “may”, “might”, “must”, “need”, “apologies”, “meet”]stopword = stopwords.words(“english”)stopword.extend(extra_list)line = ‘ ‘.join([i for i in line.split() if i not in stopword])
2. Make lower case: This is required to make all the words in lowercase just to maintain the uniformity.
line = line.lower()
3. Lemmatization: This helps to reduce the words into a single form. For example:
def lemmatize_text(text):w_tokenizer = nltk.tokenize.WhitespaceTokenizer()lemmatizer = nltk.stem.WordNetLemmatizer()return [lemmatizer.lemmatize(w) for w in w_tokenizer.tokenize(text)]lemmatize_text(line)
4. Stemming: This helps to reduce the words into their root form. For example:
def stem_porter(text):w_tokenizer = nltk.tokenize.WhitespaceTokenizer()ps = nltk.PorterStemmer()return [ps.stem(w) for w in w_tokenizer.tokenize(text)]stem_porter(line)
There are 2 more types of stemming apart from PorterStemmer. Those are Lancaster Stemming and Snowball. Snowball is an improvement over Porter stemming.
5. Removal of regular expressions: Regular expression helps to identify and to get rid of different patterns which are not required in the text.
line = re.sub(‘\S*@\S*\s?’,” “,line) #email removeline = re.sub(‘\s+’,” “,line) #new line character removeline = re.sub(“\’”,” “,line) #single quote removeline = re.sub(‘_’,” “,line) #underscore removeline = re.sub(‘http\S*\s?’,” “,line) #link removeline = ‘ ‘.join([i for i in line.split() if i.find(‘#’) < 0]) #hasgtag removeline = ‘ ‘.join([i for i in line.split() if i in re.findall(r’\w+’,line)]) #only keep words and numbers
6. Parts-of-Speech (POS) tagging: This helps to identify the parts of speech. Based on the use case one can keep or remove some of them.
import spacyfrom spacy.tokenizer import Tokenizernlp = spacy.load(“en_core_web_sm”)tokens_spacy = nlp(line)for token in tokens_spacy:print(token.text, ‘: ‘, token.pos_, ‘: ‘, token.is_stop)
7. Named-Entity-Recognition (NER): This helps to identify and categorize the different groups which includes names, places, currency etc.
for ent in tokens_spacy.ents:print(ent.text, ‘: ‘, ent.label_)
This is one of the common practices while working on text data. This helps to split a phrase, sentence, or paragraph into small units like words or terms. Each unit is called a token. There are different types of tokenization. We have already used this in above examples for stemming, POS tagging, and NER. Below are different ways to tokenize the text.
str1 = “I am eating pizza and, coke.”
1) Tokenization using split () function: Returns list of strings after breaking the given string by the specified separator. By default, a separator is a space.
str1.split()[‘I’, ‘am’, ‘eating’, ‘pizza’, ‘and,’, ‘coke.’]
2) Tokenization using Regular expression: Returns list based on the regular expressions.
re.findall(“[\w]+”,str1)[‘I’, ‘am’, ‘eating’, ‘pizza’, ‘and’, ‘coke’]
3) Tokenization using NLTK: There are different types of tokenizers under NLTK package like word tokenizer (word_tokenize), regex tokenizer (RegexpTokenizer), whitespace tokenizer (WhitespaceTokenizer) etc.
3.1)
from nltk import word_tokenizeword_tokenize(str1)[‘I’, ‘am’, ‘eating’, ‘pizza’, ‘and’, ‘,’, ‘coke’, ‘.’]
3.2)
space_tokenizer = nltk.tokenize.WhitespaceTokenizer()space _tokenizer.tokenize(str1)[‘I’, ‘am’, ‘eating’, ‘pizza’, ‘and,’, ‘coke,’]
3.3)
reg_tokenizer = nltk.tokenize.RegexpTokenizer(“[A-Za-z]+”)reg_tokenizer.tokenize(str1)[‘I’, ‘am’, ‘eating’, ‘pizza’, ‘and’, ‘coke’]
Further we can use these tokenized forms to count the number of words in a text or frequency of the words in a text.
Once cleaning and tokenization is done, extracting features from the clean data is very important as the machine doesn’t understand the words but numbers. Vectorization helps to map the words to a vector of real numbers, which further helps into predictions. This helps to extract the important features. Below are few techniques used for the purpose:
1. CountVec: Count number of times a particular word appears in the document. CountVectorizer helps to get this count.
from sklearn.feature_extraction.text import CountVectorizercount_vec = CountVectorizer(analyzer=’word’, ngram_range=(1, 3), stop_words = ‘english’)count_vec.fit(str2)count = count_vec.transform(str2)vectors = count_vec.get_feature_names()smatrix = count_vec.transform(str2)dense = smatrix.todense()dense_list = dense.tolist()df_countvec = pd.DataFrame(dense_list,columns=vectors)
2. TF-IDF: Term frequency Inverse document frequency (TF-IDF) provides an overall weightage of a word in the document. TfidfVectorizer helps to get this weighted score.
from sklearn.feature_extraction.text import TfidfVectorizertfidf_vec = TfidfVectorizer (analyzer=’word’, ngram_range=(1, 3), stop_words = ‘english’)tfidf_vec.fit(str2)tfidf = tfidf_vec.transform(str2)vectors = tfidf_vec.get_feature_names()smatrix = tfidf_vec.transform(str2)dense = smatrix.todense()dense_list = dense.tolist()df_ tfidf = pd.DataFrame(dense_list,columns=vectors)
Comparison: CountVec might provide biased results in favour of most frequent words. This ignores the rare words which might have higher importance. This means we need to penalize the most frequent words. TF-IDF enables the penalizing effect. It weighs the count by a measure of the words appearing in the document. For example,
str2 = [‘I am going to test Covid’,‘It seems ABC hospital is doing the Covid test’,‘Covaxin is still in WIP phase’]
Both these models provide one number (count or weight) per word. But to understand each word’s context and to identify the content, one vector per word is much more appropriate. Word2Vec provides one vector per word by skimming through the given documents, which is more useful than a simple bag of words or TF-IDF. But Word2Vec lacks to address ‘local understanding’ of the relationship, which was answered by Glove. Glove is a pre-trained vectorization technique that not only understands the local context but also the relationship with global words. Apart from Glove, FastText is another popular technique for word embedding, which works better for rare words or Out-of-vocabulary(OOV).
Having said all these, Bag of words or TF-IDF (mainly) is vastly used till now and very much integrated part of day-to-day NLP problems. As this article intends to cover only basic NLP concepts, Glove or FastText are not covered in details.
Here comes the final part! Finally we have a count based or TF-IDF matrix and the dependent variable (label) to develop the model.
One can use any of the classification models like logistic regression, random forest (RF), support vector machines (SVM) or any deep learning models like RNN, LSTM or state-of-art model like BERT, GPT3 to predict the label. As a measure of accuracy ROC, Recall, F1-score can be used based the problem statement in hand.
Before running the model, let's split the data into train and test.
X = df.drop(columns=’label’)y = df[‘label’]X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2, random_state=420,stratify=y)
Now, model the data and check accuracy metrics.
from sklearn.linear_model import LogisticRegression, RandomForestClassifiermodel = LogisticRegression()#model = RandomForestClassifier()model.fit(X_train, y_train)y_pred_class = model.predict(X_test)print(‘Accuracy: ‘, metrics.accuracy_score(y_test, y_pred_class))print(confusion_matrix(y_test, y_pred_class))
Apart from classification problems, NLP can be leveraged for several use cases like text summarization, Q&A, topic modeling (link), text translation etc.
Hope this article will help you to get the feel how to start with any NLP based problem. Till then, Happy Learning!
Disclaimer: The views expressed in this article is the opinion of the author in his personal capacity and not of his employer | [
{
"code": null,
"e": 543,
"s": 172,
"text": "In the data science domain, Natural Language Processing (NLP) is a very important component for its vast applications in various industries/sectors. For a human it’s pretty easy to understand the language but machines are not capable enough to recognize i... |
MySQL NULL Values - IS NULL and IS NOT NULL | A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or
update a record without adding a value to this field. Then, the field will be
saved with a NULL value.
Note: A NULL value is different from a zero value or a field that
contains spaces. A field with a NULL value is one that has been left blank
during record creation!
It is not possible to test for NULL values with comparison operators, such as
=, <, or <>.
We will have to use the IS NULL and
IS NOT NULL operators instead.
Below is a selection from the "Customers" table in the Northwind sample
database:
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
Tip: Always use IS NULL to look for NULL values.
The IS NOT NULL operator is used to test for non-empty values (NOT NULL
values).
The following SQL lists all customers with a value in the "Address" field:
Select all records from the Customers where
the PostalCode column is empty.
SELECT * FROM Customers
WHERE ;
Start the
Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 52,
"s": 0,
"text": "A field with a NULL value is a field with no value."
},
{
"code": null,
"e": 233,
"s": 52,
"text": "If a field in a table is optional, it is possible to insert a new record or \nupdate a record without adding a value to this field. Then, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.