title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Getting type of different data types in R Programming - typeof() Function - GeeksforGeeks | 12 Jun, 2020
typeof() function in R Language is used to return the types of data used as the arguments.
Syntax: typeof(x)
Parameters:x: specified data
Example 1:
# R program to illustrate# typeof function # Specifying "Biochemical oxygen demand"# data setx <- BODx # Calling typeof() functiontypeof(x)
Output:
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
[1] "list"
Example 2:
# R program to illustrate# typeof function # Calling typeof() function # over different types of data typeof(2)typeof(2.8)typeof("3")typeof("gfg")typeof(1 + 2i)
Output:
[1] "double"
[1] "double"
[1] "character"
[1] "character"
[1] "complex"
R Data-types
R Object-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming | [
{
"code": null,
"e": 24639,
"s": 24611,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 24730,
"s": 24639,
"text": "typeof() function in R Language is used to return the types of data used as the arguments."
},
{
"code": null,
"e": 24748,
"s": 24730,
"text": "Syntax: typeof(x)"
},
{
"code": null,
"e": 24777,
"s": 24748,
"text": "Parameters:x: specified data"
},
{
"code": null,
"e": 24788,
"s": 24777,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# typeof function # Specifying \"Biochemical oxygen demand\"# data setx <- BODx # Calling typeof() functiontypeof(x)",
"e": 24930,
"s": 24788,
"text": null
},
{
"code": null,
"e": 24938,
"s": 24930,
"text": "Output:"
},
{
"code": null,
"e": 25048,
"s": 24938,
"text": " Time demand\n1 1 8.3\n2 2 10.3\n3 3 19.0\n4 4 16.0\n5 5 15.6\n6 7 19.8\n[1] \"list\"\n"
},
{
"code": null,
"e": 25059,
"s": 25048,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# typeof function # Calling typeof() function # over different types of data typeof(2)typeof(2.8)typeof(\"3\")typeof(\"gfg\")typeof(1 + 2i)",
"e": 25221,
"s": 25059,
"text": null
},
{
"code": null,
"e": 25229,
"s": 25221,
"text": "Output:"
},
{
"code": null,
"e": 25302,
"s": 25229,
"text": "[1] \"double\"\n[1] \"double\"\n[1] \"character\"\n[1] \"character\"\n[1] \"complex\"\n"
},
{
"code": null,
"e": 25315,
"s": 25302,
"text": "R Data-types"
},
{
"code": null,
"e": 25333,
"s": 25315,
"text": "R Object-Function"
},
{
"code": null,
"e": 25344,
"s": 25333,
"text": "R Language"
},
{
"code": null,
"e": 25442,
"s": 25344,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25451,
"s": 25442,
"text": "Comments"
},
{
"code": null,
"e": 25464,
"s": 25451,
"text": "Old Comments"
},
{
"code": null,
"e": 25522,
"s": 25464,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 25566,
"s": 25522,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 25618,
"s": 25566,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 25670,
"s": 25618,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 25702,
"s": 25670,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 25734,
"s": 25702,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 25772,
"s": 25734,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 25807,
"s": 25772,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 25865,
"s": 25807,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
How do I prevent an iOS device from going to sleep mode? | When most apps have no touches as user input for a short period, the system puts the device into a "sleep” state where the screen dims. This is done for the purposes of conserving power.
Preventing iOS Device from going to sleep is easy, navigate to your Settings → Display & Brightness → Autolock, select never.
This will never lock your screen.
If you’re developing an iOS Application and you’re required to implement this feature, you should use isidletimerdisabled provided by apple, to read more about it https://developer.apple.com/documentation/uikit/uiapplication/1623070-isidletimerdisabled
In your viewDidLoad method write the following line of code to prevent the device from going to sleep.
UIApplication.shared.isIdleTimerDisabled = true | [
{
"code": null,
"e": 1249,
"s": 1062,
"text": "When most apps have no touches as user input for a short period, the system puts the device into a \"sleep” state where the screen dims. This is done for the purposes of conserving power."
},
{
"code": null,
"e": 1375,
"s": 1249,
"text": "Preventing iOS Device from going to sleep is easy, navigate to your Settings → Display & Brightness → Autolock, select never."
},
{
"code": null,
"e": 1409,
"s": 1375,
"text": "This will never lock your screen."
},
{
"code": null,
"e": 1662,
"s": 1409,
"text": "If you’re developing an iOS Application and you’re required to implement this feature, you should use isidletimerdisabled provided by apple, to read more about it https://developer.apple.com/documentation/uikit/uiapplication/1623070-isidletimerdisabled"
},
{
"code": null,
"e": 1765,
"s": 1662,
"text": "In your viewDidLoad method write the following line of code to prevent the device from going to sleep."
},
{
"code": null,
"e": 1813,
"s": 1765,
"text": "UIApplication.shared.isIdleTimerDisabled = true"
}
] |
Tryit Editor v3.6 - Show Python | mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor() | [
{
"code": null,
"e": 57,
"s": 25,
"text": "mydb = mysql.connector.connect("
},
{
"code": null,
"e": 77,
"s": 57,
"text": " host=\"localhost\","
},
{
"code": null,
"e": 98,
"s": 77,
"text": " user=\"myusername\","
},
{
"code": null,
"e": 123,
"s": 98,
"text": " password=\"mypassword\","
},
{
"code": null,
"e": 147,
"s": 123,
"text": " database=\"mydatabase\""
},
{
"code": null,
"e": 149,
"s": 147,
"text": ")"
},
{
"code": null,
"e": 151,
"s": 149,
"text": ""
}
] |
Split dataframe in Pandas based on values in multiple columns - GeeksforGeeks | 19 Dec, 2021
In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python. To divide a dataframe into two or more separate dataframes based on the values present in the column we first create a data frame.
Python3
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'First_Name': ["Aparna", "Pankaj", "Sudhir", "Geeku", "Anuj", "Aman", "Madhav", "Raj", "Shruti"], 'Last_Name': ["Pandey", "Gupta", "Mishra", "Chopra", "Mishra", "Verma", "Sen", "Roy", "Agarwal"], 'Email_ID': ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"], 'Degree': ["MBA", "BCA", "M.Tech", "MBA", "B.Sc", "B.Tech", "B.Tech", "MBA", "M.Tech"], 'Score': [90, 40, 75, 98, 94, 90, 80, 90, 95]} # creating dataframedf = pd.DataFrame(dict) print(df)
Output:
We can create multiple dataframes from a given dataframe based on a certain column value by using the boolean indexing method and by mentioning the required criteria.
Example 1: Creating a dataframe for the students with Score >= 80
Python3
# creating a new dataframe by applying the required # conditions in [] df1 = df[df['Score'] >= 80] print(df1)
Output:
Example 2: Creating a dataframe for the students with Last_Name as Mishra
Python3
# Creating on the basis of Last_Namedfname = df[df['Last_Name'] == 'Mishra'] print(dfname)
Output:
We can do the same for other columns as well by putting the appropriate condition
We create a mask variable for the condition of the column in the previous method
Example 1: To get dataframe of students with Degree as MBA
Python3
# creating the mask variable with appropriate# conditionmask_var = df['Degree'] =='MBA' # creating a dataframedf1_mask = df[mask_var] print(df1_mask)
Output :
Example 2: To get a dataframe for the rest of the students
To get the rest of the values in a dataframe we can simply invert the mask variable by adding a ~(tilde) after it.
Python3
# creating dataframe with inverted mask variabledf2_mask = df[~mask_var] print(df2_mask)
Output :
Using groupby() we can group the rows using a specific column value and then display it as a separate dataframe.
Example 1: Group all Students according to their Degree and display as required
Python3
# Creating an object using groupbygrouped = df.groupby('Degree') # the return type of the object 'grouped' is # pandas.core.groupby.generic.DataFrameGroupBy. # Creating a dataframe from the object using get_group().# dataframe of students with Degree as MBA.df_grouped = grouped.get_group('MBA') print(df_grouped)
Output: dataframe of students with Degree as MBA
Example 2: Group all Students according to their Score and display as required
Python3
# Creating another object using groupbygrouped2 = df.groupby('Score') # the return type of the object 'grouped2' is # pandas.core.groupby.generic.DataFrameGroupBy. # Creating a dataframe from the object # using get_group() dataframe of students# with Score = 90df_grouped2 = grouped2.get_group(90) print(df_grouped2)
Output: dataframe of students with Score = 90.
pandas-dataframe-program
Picked
Python pandas-dataFrame
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()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 24160,
"s": 23901,
"text": "In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python. To divide a dataframe into two or more separate dataframes based on the values present in the column we first create a data frame."
},
{
"code": null,
"e": 24168,
"s": 24160,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'First_Name': [\"Aparna\", \"Pankaj\", \"Sudhir\", \"Geeku\", \"Anuj\", \"Aman\", \"Madhav\", \"Raj\", \"Shruti\"], 'Last_Name': [\"Pandey\", \"Gupta\", \"Mishra\", \"Chopra\", \"Mishra\", \"Verma\", \"Sen\", \"Roy\", \"Agarwal\"], 'Email_ID': [\"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\"], 'Degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\", \"B.Sc\", \"B.Tech\", \"B.Tech\", \"MBA\", \"M.Tech\"], 'Score': [90, 40, 75, 98, 94, 90, 80, 90, 95]} # creating dataframedf = pd.DataFrame(dict) print(df)",
"e": 25053,
"s": 24168,
"text": null
},
{
"code": null,
"e": 25061,
"s": 25053,
"text": "Output:"
},
{
"code": null,
"e": 25228,
"s": 25061,
"text": "We can create multiple dataframes from a given dataframe based on a certain column value by using the boolean indexing method and by mentioning the required criteria."
},
{
"code": null,
"e": 25294,
"s": 25228,
"text": "Example 1: Creating a dataframe for the students with Score >= 80"
},
{
"code": null,
"e": 25302,
"s": 25294,
"text": "Python3"
},
{
"code": "# creating a new dataframe by applying the required # conditions in [] df1 = df[df['Score'] >= 80] print(df1)",
"e": 25413,
"s": 25302,
"text": null
},
{
"code": null,
"e": 25421,
"s": 25413,
"text": "Output:"
},
{
"code": null,
"e": 25495,
"s": 25421,
"text": "Example 2: Creating a dataframe for the students with Last_Name as Mishra"
},
{
"code": null,
"e": 25503,
"s": 25495,
"text": "Python3"
},
{
"code": "# Creating on the basis of Last_Namedfname = df[df['Last_Name'] == 'Mishra'] print(dfname)",
"e": 25595,
"s": 25503,
"text": null
},
{
"code": null,
"e": 25603,
"s": 25595,
"text": "Output:"
},
{
"code": null,
"e": 25685,
"s": 25603,
"text": "We can do the same for other columns as well by putting the appropriate condition"
},
{
"code": null,
"e": 25766,
"s": 25685,
"text": "We create a mask variable for the condition of the column in the previous method"
},
{
"code": null,
"e": 25825,
"s": 25766,
"text": "Example 1: To get dataframe of students with Degree as MBA"
},
{
"code": null,
"e": 25833,
"s": 25825,
"text": "Python3"
},
{
"code": "# creating the mask variable with appropriate# conditionmask_var = df['Degree'] =='MBA' # creating a dataframedf1_mask = df[mask_var] print(df1_mask)",
"e": 25985,
"s": 25833,
"text": null
},
{
"code": null,
"e": 25994,
"s": 25985,
"text": "Output :"
},
{
"code": null,
"e": 26053,
"s": 25994,
"text": "Example 2: To get a dataframe for the rest of the students"
},
{
"code": null,
"e": 26168,
"s": 26053,
"text": "To get the rest of the values in a dataframe we can simply invert the mask variable by adding a ~(tilde) after it."
},
{
"code": null,
"e": 26176,
"s": 26168,
"text": "Python3"
},
{
"code": "# creating dataframe with inverted mask variabledf2_mask = df[~mask_var] print(df2_mask)",
"e": 26266,
"s": 26176,
"text": null
},
{
"code": null,
"e": 26275,
"s": 26266,
"text": "Output :"
},
{
"code": null,
"e": 26388,
"s": 26275,
"text": "Using groupby() we can group the rows using a specific column value and then display it as a separate dataframe."
},
{
"code": null,
"e": 26468,
"s": 26388,
"text": "Example 1: Group all Students according to their Degree and display as required"
},
{
"code": null,
"e": 26476,
"s": 26468,
"text": "Python3"
},
{
"code": "# Creating an object using groupbygrouped = df.groupby('Degree') # the return type of the object 'grouped' is # pandas.core.groupby.generic.DataFrameGroupBy. # Creating a dataframe from the object using get_group().# dataframe of students with Degree as MBA.df_grouped = grouped.get_group('MBA') print(df_grouped)",
"e": 26793,
"s": 26476,
"text": null
},
{
"code": null,
"e": 26842,
"s": 26793,
"text": "Output: dataframe of students with Degree as MBA"
},
{
"code": null,
"e": 26921,
"s": 26842,
"text": "Example 2: Group all Students according to their Score and display as required"
},
{
"code": null,
"e": 26929,
"s": 26921,
"text": "Python3"
},
{
"code": "# Creating another object using groupbygrouped2 = df.groupby('Score') # the return type of the object 'grouped2' is # pandas.core.groupby.generic.DataFrameGroupBy. # Creating a dataframe from the object # using get_group() dataframe of students# with Score = 90df_grouped2 = grouped2.get_group(90) print(df_grouped2)",
"e": 27249,
"s": 26929,
"text": null
},
{
"code": null,
"e": 27296,
"s": 27249,
"text": "Output: dataframe of students with Score = 90."
},
{
"code": null,
"e": 27321,
"s": 27296,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 27328,
"s": 27321,
"text": "Picked"
},
{
"code": null,
"e": 27352,
"s": 27328,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27366,
"s": 27352,
"text": "Python-pandas"
},
{
"code": null,
"e": 27373,
"s": 27366,
"text": "Python"
},
{
"code": null,
"e": 27471,
"s": 27373,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27480,
"s": 27471,
"text": "Comments"
},
{
"code": null,
"e": 27493,
"s": 27480,
"text": "Old Comments"
},
{
"code": null,
"e": 27525,
"s": 27493,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27581,
"s": 27525,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27623,
"s": 27581,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27665,
"s": 27623,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27701,
"s": 27665,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27740,
"s": 27701,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27762,
"s": 27740,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27793,
"s": 27762,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27820,
"s": 27793,
"text": "Python Classes and Objects"
}
] |
React Suite Tooltip Component - GeeksforGeeks | 11 Apr, 2022
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Tooltip component allows the user to display informative text when users hover over, focus on, or tap an element. We can use the following approach in ReactJS to use the React Suite Tooltip Component.
Tooltip Props:
children: It is used to denote the primary content.
classPrefix: It is used to denote the prefix of the component CSS class.
visible: It is used to indicate whether the component is visible or not.
Whisper Props:
container: It is used to set the rendering container.
delay: It is used to denote the delay time.
delayHide: It is used to denote the hidden delay time.
delayShow: It is used to show delay time.
onBlur: It is a function that is triggered on lose focus.
onClick: It is a function that is triggered on click event.
onEnter: It is a function that is triggered before the overlay transitions in.
onEntered: It is a function that is triggered after the overlay finishes transitioning in.
onEntering: It is a function that is triggered as the overlay begins to transition in.
onExit: It is a function that is triggered right before the overlay transitions out.
onExited: It is a function that is triggered after the overlay finishes transitioning out.
onExiting: It is a function that is triggered as the overlay begins to transition out.
onFocus: It is a function that is triggered to get focus.
onMouseOut: It is a function that is triggered on mouse leave event.
placement: It is used for the placement of the component.
preventOverflow: It is used to prevent floating element overflow.
speaker: It is used for the displayed component.
trigger: It is used for the triggering events.
Whisper Methods:
open: This method is used to display a tooltip.
close: This method is used to close the tooltip.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install rsuite
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install rsuite
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import 'rsuite/dist/styles/rsuite-default.css';import { Button, Tooltip, Whisper } from 'rsuite' export default function App() { return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>React Suite Tooltip Component</h4> <Whisper trigger="click" placement="bottom" speaker={<Tooltip>Sample Tooltip Text!</Tooltip>} > <Button appearance="subtle">Open Tooltip</Button> </Whisper> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://rsuitejs.com/components/tooltip/
React-Suite
React-Suite Components
React-Suite General
JavaScript
ReactJS
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
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components | [
{
"code": null,
"e": 24921,
"s": 24893,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 25261,
"s": 24921,
"text": "React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Tooltip component allows the user to display informative text when users hover over, focus on, or tap an element. We can use the following approach in ReactJS to use the React Suite Tooltip Component."
},
{
"code": null,
"e": 25276,
"s": 25261,
"text": "Tooltip Props:"
},
{
"code": null,
"e": 25328,
"s": 25276,
"text": "children: It is used to denote the primary content."
},
{
"code": null,
"e": 25401,
"s": 25328,
"text": "classPrefix: It is used to denote the prefix of the component CSS class."
},
{
"code": null,
"e": 25474,
"s": 25401,
"text": "visible: It is used to indicate whether the component is visible or not."
},
{
"code": null,
"e": 25489,
"s": 25474,
"text": "Whisper Props:"
},
{
"code": null,
"e": 25543,
"s": 25489,
"text": "container: It is used to set the rendering container."
},
{
"code": null,
"e": 25587,
"s": 25543,
"text": "delay: It is used to denote the delay time."
},
{
"code": null,
"e": 25642,
"s": 25587,
"text": "delayHide: It is used to denote the hidden delay time."
},
{
"code": null,
"e": 25684,
"s": 25642,
"text": "delayShow: It is used to show delay time."
},
{
"code": null,
"e": 25742,
"s": 25684,
"text": "onBlur: It is a function that is triggered on lose focus."
},
{
"code": null,
"e": 25802,
"s": 25742,
"text": "onClick: It is a function that is triggered on click event."
},
{
"code": null,
"e": 25881,
"s": 25802,
"text": "onEnter: It is a function that is triggered before the overlay transitions in."
},
{
"code": null,
"e": 25972,
"s": 25881,
"text": "onEntered: It is a function that is triggered after the overlay finishes transitioning in."
},
{
"code": null,
"e": 26059,
"s": 25972,
"text": "onEntering: It is a function that is triggered as the overlay begins to transition in."
},
{
"code": null,
"e": 26144,
"s": 26059,
"text": "onExit: It is a function that is triggered right before the overlay transitions out."
},
{
"code": null,
"e": 26235,
"s": 26144,
"text": "onExited: It is a function that is triggered after the overlay finishes transitioning out."
},
{
"code": null,
"e": 26322,
"s": 26235,
"text": "onExiting: It is a function that is triggered as the overlay begins to transition out."
},
{
"code": null,
"e": 26380,
"s": 26322,
"text": "onFocus: It is a function that is triggered to get focus."
},
{
"code": null,
"e": 26449,
"s": 26380,
"text": "onMouseOut: It is a function that is triggered on mouse leave event."
},
{
"code": null,
"e": 26507,
"s": 26449,
"text": "placement: It is used for the placement of the component."
},
{
"code": null,
"e": 26573,
"s": 26507,
"text": "preventOverflow: It is used to prevent floating element overflow."
},
{
"code": null,
"e": 26622,
"s": 26573,
"text": "speaker: It is used for the displayed component."
},
{
"code": null,
"e": 26669,
"s": 26622,
"text": "trigger: It is used for the triggering events."
},
{
"code": null,
"e": 26686,
"s": 26669,
"text": "Whisper Methods:"
},
{
"code": null,
"e": 26734,
"s": 26686,
"text": "open: This method is used to display a tooltip."
},
{
"code": null,
"e": 26783,
"s": 26734,
"text": "close: This method is used to close the tooltip."
},
{
"code": null,
"e": 26835,
"s": 26785,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26930,
"s": 26835,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 26994,
"s": 26930,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27026,
"s": 26994,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27139,
"s": 27026,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 27239,
"s": 27139,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27253,
"s": 27239,
"text": "cd foldername"
},
{
"code": null,
"e": 27376,
"s": 27253,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install rsuite"
},
{
"code": null,
"e": 27481,
"s": 27376,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 27500,
"s": 27481,
"text": "npm install rsuite"
},
{
"code": null,
"e": 27552,
"s": 27500,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27570,
"s": 27552,
"text": "Project Structure"
},
{
"code": null,
"e": 27700,
"s": 27570,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 27707,
"s": 27700,
"text": "App.js"
},
{
"code": "import React from 'react'import 'rsuite/dist/styles/rsuite-default.css';import { Button, Tooltip, Whisper } from 'rsuite' export default function App() { return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>React Suite Tooltip Component</h4> <Whisper trigger=\"click\" placement=\"bottom\" speaker={<Tooltip>Sample Tooltip Text!</Tooltip>} > <Button appearance=\"subtle\">Open Tooltip</Button> </Whisper> </div> );}",
"e": 28206,
"s": 27707,
"text": null
},
{
"code": null,
"e": 28319,
"s": 28206,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28329,
"s": 28319,
"text": "npm start"
},
{
"code": null,
"e": 28428,
"s": 28329,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 28480,
"s": 28428,
"text": "Reference: https://rsuitejs.com/components/tooltip/"
},
{
"code": null,
"e": 28492,
"s": 28480,
"text": "React-Suite"
},
{
"code": null,
"e": 28515,
"s": 28492,
"text": "React-Suite Components"
},
{
"code": null,
"e": 28535,
"s": 28515,
"text": "React-Suite General"
},
{
"code": null,
"e": 28546,
"s": 28535,
"text": "JavaScript"
},
{
"code": null,
"e": 28554,
"s": 28546,
"text": "ReactJS"
},
{
"code": null,
"e": 28571,
"s": 28554,
"text": "Web Technologies"
},
{
"code": null,
"e": 28669,
"s": 28571,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28678,
"s": 28669,
"text": "Comments"
},
{
"code": null,
"e": 28691,
"s": 28678,
"text": "Old Comments"
},
{
"code": null,
"e": 28752,
"s": 28691,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28793,
"s": 28752,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28833,
"s": 28793,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28887,
"s": 28833,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28949,
"s": 28887,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28992,
"s": 28949,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29037,
"s": 28992,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 29102,
"s": 29037,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 29170,
"s": 29102,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
Difference between MySQL BigInt(20) and Int(20)? | The int type takes 4 byte signed integer i.e. 32 bits ( 232 values can be stored). The BigInt type takes 8 byte signed integer i.e. 64 bits (264 values can be stored).
Let us see an example.
Creating a table with zerofill, that would add leading zeros.
mysql> create table IntandBigint20Demo
-> (
-> Number int(20) zerofill,
-> Code BigInt(20) zerofill
-> );
Query OK, 0 rows affected (0.58 sec)
After creating a table, we will insert records into the table.
mysql> insert into IntandBigint20Demo values(987,987);
Query OK, 1 row affected (0.16 sec)
Now we can display all records with the help of select statment. The query is as follows −
mysql> select *from IntandBigint20Demo;
The following is the output.
+----------------------+----------------------+
| Number | Code |
+----------------------+----------------------+
| 00000000000000000987 | 00000000000000000987 |
+----------------------+----------------------+
1 row in set (0.00 sec)
Look at the sample output, in the beginning, 0 gets filled. This itself states that 20 is the width in let’s say.
Number int(20) zerofill | [
{
"code": null,
"e": 1230,
"s": 1062,
"text": "The int type takes 4 byte signed integer i.e. 32 bits ( 232 values can be stored). The BigInt type takes 8 byte signed integer i.e. 64 bits (264 values can be stored)."
},
{
"code": null,
"e": 1253,
"s": 1230,
"text": "Let us see an example."
},
{
"code": null,
"e": 1315,
"s": 1253,
"text": "Creating a table with zerofill, that would add leading zeros."
},
{
"code": null,
"e": 1470,
"s": 1315,
"text": "mysql> create table IntandBigint20Demo\n -> (\n -> Number int(20) zerofill,\n -> Code BigInt(20) zerofill\n -> );\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1533,
"s": 1470,
"text": "After creating a table, we will insert records into the table."
},
{
"code": null,
"e": 1624,
"s": 1533,
"text": "mysql> insert into IntandBigint20Demo values(987,987);\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1715,
"s": 1624,
"text": "Now we can display all records with the help of select statment. The query is as follows −"
},
{
"code": null,
"e": 1755,
"s": 1715,
"text": "mysql> select *from IntandBigint20Demo;"
},
{
"code": null,
"e": 1784,
"s": 1755,
"text": "The following is the output."
},
{
"code": null,
"e": 2049,
"s": 1784,
"text": "+----------------------+----------------------+\n| Number | Code |\n+----------------------+----------------------+\n| 00000000000000000987 | 00000000000000000987 |\n+----------------------+----------------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 2163,
"s": 2049,
"text": "Look at the sample output, in the beginning, 0 gets filled. This itself states that 20 is the width in let’s say."
},
{
"code": null,
"e": 2187,
"s": 2163,
"text": "Number int(20) zerofill"
}
] |
Dijkstra's shortest path algorithm in Java using PriorityQueue - GeeksforGeeks | 28 Jan, 2022
Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with a given source as a root. We maintain two sets, one set contains vertices included in the shortest-path tree, other set includes vertices not yet included in the shortest-path tree. At every step of the algorithm, we find a vertex that is in the other set (set of not yet included) and has a minimum distance from the source.
Here the only drawback with Dijkstra algorithms is that while finding the shortest path as listed as follows as we need to find the least cost path by going through the whole cost array. Not a big deal for small graphs and at the same time becomes an efficiency issue for large graphs because each time we need to run through an array while traversing. Now as we know queues can work for us so do we apply the concept of priority queues with this algorithm to erupt out some of the disadvantages and making complexity much better.
Let us now discuss the problem statement whereas in accordance with the title it seems like the sheer implementation of one of the data structures known as priority queue with involvement of algorithm analysis in it. So let us begin with the problem statement which is listed below prior to it do stress over note as the whole concept revolves around the adjacency matrix representation.
Note: Dijkstra’s shortest Path implementations like Dijkstra’s Algorithm for Adjacency Matrix Representation (With time complexity O(v2)
Problem statement
Given a graph with adjacency list representation of the edges between the nodes, the task is to implement Dijkstra’s Algorithm for single-source shortest path using Priority Queue in Java. Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph.
Illustration:
Input : Source = 0
Output :
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
Implementation:
Java
// Java Program to Implement Dijkstra's Algorithm// Using Priority Queue // Importing utility classesimport java.util.*; // Main class DPQpublic class GFG { // Member variables of this class private int dist[]; private Set<Integer> settled; private PriorityQueue<Node> pq; // Number of vertices private int V; List<List<Node> > adj; // Constructor of this class public GFG(int V) { // This keyword refers to current object itself this.V = V; dist = new int[V]; settled = new HashSet<Integer>(); pq = new PriorityQueue<Node>(V, new Node()); } // Method 1 // Dijkstra's Algorithm public void dijkstra(List<List<Node> > adj, int src) { this.adj = adj; for (int i = 0; i < V; i++) dist[i] = Integer.MAX_VALUE; // Add source node to the priority queue pq.add(new Node(src, 0)); // Distance to the source is 0 dist[src] = 0; while (settled.size() != V) { // Terminating condition check when // the priority queue is empty, return if (pq.isEmpty()) return; // Removing the minimum distance node // from the priority queue int u = pq.remove().node; // Adding the node whose distance is // finalized if (settled.contains(u)) // Continue keyword skips exwcution for // following check continue; // We don't have to call e_Neighbors(u) // if u is already present in the settled set. settled.add(u); e_Neighbours(u); } } // Method 2 // To process all the neighbours // of the passed node private void e_Neighbours(int u) { int edgeDistance = -1; int newDistance = -1; // All the neighbors of v for (int i = 0; i < adj.get(u).size(); i++) { Node v = adj.get(u).get(i); // If current node hasn't already been processed if (!settled.contains(v.node)) { edgeDistance = v.cost; newDistance = dist[u] + edgeDistance; // If new distance is cheaper in cost if (newDistance < dist[v.node]) dist[v.node] = newDistance; // Add the current node to the queue pq.add(new Node(v.node, dist[v.node])); } } } // Main driver method public static void main(String arg[]) { int V = 5; int source = 0; // Adjacency list representation of the // connected edges by declaring List class object // Declaring object of type List<Node> List<List<Node> > adj = new ArrayList<List<Node> >(); // Initialize list for every node for (int i = 0; i < V; i++) { List<Node> item = new ArrayList<Node>(); adj.add(item); } // Inputs for the GFG(dpq) graph adj.get(0).add(new Node(1, 9)); adj.get(0).add(new Node(2, 6)); adj.get(0).add(new Node(3, 5)); adj.get(0).add(new Node(4, 3)); adj.get(2).add(new Node(1, 2)); adj.get(2).add(new Node(3, 4)); // Calculating the single source shortest path GFG dpq = new GFG(V); dpq.dijkstra(adj, source); // Printing the shortest path to all the nodes // from the source node System.out.println("The shorted path from node :"); for (int i = 0; i < dpq.dist.length; i++) System.out.println(source + " to " + i + " is " + dpq.dist[i]); }} // Class 2// Helper class implementing Comparator interface// Representing a node in the graphclass Node implements Comparator<Node> { // Member variables of this class public int node; public int cost; // Constructors of this class // Constructor 1 public Node() {} // Constructor 2 public Node(int node, int cost) { // This keyword refers to current instance itself this.node = node; this.cost = cost; } // Method 1 @Override public int compare(Node node1, Node node2) { if (node1.cost < node2.cost) return -1; if (node1.cost > node2.cost) return 1; return 0; }}
The shorted path from node :
0 to 0 is 0
0 to 1 is 8
0 to 2 is 6
0 to 3 is 5
0 to 4 is 3
jyoti369
iramkhalid24
germanshephered48
Dijkstra
java-priority-queue
Picked
Shortest Path
Java Programs
Shortest Path
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Java Programming Examples
How to Iterate HashMap in Java?
Factory method design pattern in Java
Traverse Through a HashMap in Java
Iterate through List in Java
Java Program to Remove Duplicate Elements From the Array
Java program to count the occurrence of each character in a string using Hashmap
Iterate Over the Characters of a String in Java
Min Heap in Java
How to Get Elements By Index from HashSet in Java? | [
{
"code": null,
"e": 24959,
"s": 24931,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 25431,
"s": 24959,
"text": "Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with a given source as a root. We maintain two sets, one set contains vertices included in the shortest-path tree, other set includes vertices not yet included in the shortest-path tree. At every step of the algorithm, we find a vertex that is in the other set (set of not yet included) and has a minimum distance from the source. "
},
{
"code": null,
"e": 25962,
"s": 25431,
"text": "Here the only drawback with Dijkstra algorithms is that while finding the shortest path as listed as follows as we need to find the least cost path by going through the whole cost array. Not a big deal for small graphs and at the same time becomes an efficiency issue for large graphs because each time we need to run through an array while traversing. Now as we know queues can work for us so do we apply the concept of priority queues with this algorithm to erupt out some of the disadvantages and making complexity much better."
},
{
"code": null,
"e": 26350,
"s": 25962,
"text": "Let us now discuss the problem statement whereas in accordance with the title it seems like the sheer implementation of one of the data structures known as priority queue with involvement of algorithm analysis in it. So let us begin with the problem statement which is listed below prior to it do stress over note as the whole concept revolves around the adjacency matrix representation."
},
{
"code": null,
"e": 26487,
"s": 26350,
"text": "Note: Dijkstra’s shortest Path implementations like Dijkstra’s Algorithm for Adjacency Matrix Representation (With time complexity O(v2)"
},
{
"code": null,
"e": 26505,
"s": 26487,
"text": "Problem statement"
},
{
"code": null,
"e": 26818,
"s": 26505,
"text": "Given a graph with adjacency list representation of the edges between the nodes, the task is to implement Dijkstra’s Algorithm for single-source shortest path using Priority Queue in Java. Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph."
},
{
"code": null,
"e": 26832,
"s": 26818,
"text": "Illustration:"
},
{
"code": null,
"e": 27145,
"s": 26832,
"text": "Input : Source = 0\nOutput : \n Vertex Distance from Source\n 0 0\n 1 4\n 2 12\n 3 19\n 4 21\n 5 11\n 6 9\n 7 8\n 8 14"
},
{
"code": null,
"e": 27161,
"s": 27145,
"text": "Implementation:"
},
{
"code": null,
"e": 27166,
"s": 27161,
"text": "Java"
},
{
"code": "// Java Program to Implement Dijkstra's Algorithm// Using Priority Queue // Importing utility classesimport java.util.*; // Main class DPQpublic class GFG { // Member variables of this class private int dist[]; private Set<Integer> settled; private PriorityQueue<Node> pq; // Number of vertices private int V; List<List<Node> > adj; // Constructor of this class public GFG(int V) { // This keyword refers to current object itself this.V = V; dist = new int[V]; settled = new HashSet<Integer>(); pq = new PriorityQueue<Node>(V, new Node()); } // Method 1 // Dijkstra's Algorithm public void dijkstra(List<List<Node> > adj, int src) { this.adj = adj; for (int i = 0; i < V; i++) dist[i] = Integer.MAX_VALUE; // Add source node to the priority queue pq.add(new Node(src, 0)); // Distance to the source is 0 dist[src] = 0; while (settled.size() != V) { // Terminating condition check when // the priority queue is empty, return if (pq.isEmpty()) return; // Removing the minimum distance node // from the priority queue int u = pq.remove().node; // Adding the node whose distance is // finalized if (settled.contains(u)) // Continue keyword skips exwcution for // following check continue; // We don't have to call e_Neighbors(u) // if u is already present in the settled set. settled.add(u); e_Neighbours(u); } } // Method 2 // To process all the neighbours // of the passed node private void e_Neighbours(int u) { int edgeDistance = -1; int newDistance = -1; // All the neighbors of v for (int i = 0; i < adj.get(u).size(); i++) { Node v = adj.get(u).get(i); // If current node hasn't already been processed if (!settled.contains(v.node)) { edgeDistance = v.cost; newDistance = dist[u] + edgeDistance; // If new distance is cheaper in cost if (newDistance < dist[v.node]) dist[v.node] = newDistance; // Add the current node to the queue pq.add(new Node(v.node, dist[v.node])); } } } // Main driver method public static void main(String arg[]) { int V = 5; int source = 0; // Adjacency list representation of the // connected edges by declaring List class object // Declaring object of type List<Node> List<List<Node> > adj = new ArrayList<List<Node> >(); // Initialize list for every node for (int i = 0; i < V; i++) { List<Node> item = new ArrayList<Node>(); adj.add(item); } // Inputs for the GFG(dpq) graph adj.get(0).add(new Node(1, 9)); adj.get(0).add(new Node(2, 6)); adj.get(0).add(new Node(3, 5)); adj.get(0).add(new Node(4, 3)); adj.get(2).add(new Node(1, 2)); adj.get(2).add(new Node(3, 4)); // Calculating the single source shortest path GFG dpq = new GFG(V); dpq.dijkstra(adj, source); // Printing the shortest path to all the nodes // from the source node System.out.println(\"The shorted path from node :\"); for (int i = 0; i < dpq.dist.length; i++) System.out.println(source + \" to \" + i + \" is \" + dpq.dist[i]); }} // Class 2// Helper class implementing Comparator interface// Representing a node in the graphclass Node implements Comparator<Node> { // Member variables of this class public int node; public int cost; // Constructors of this class // Constructor 1 public Node() {} // Constructor 2 public Node(int node, int cost) { // This keyword refers to current instance itself this.node = node; this.cost = cost; } // Method 1 @Override public int compare(Node node1, Node node2) { if (node1.cost < node2.cost) return -1; if (node1.cost > node2.cost) return 1; return 0; }}",
"e": 31508,
"s": 27166,
"text": null
},
{
"code": null,
"e": 31600,
"s": 31511,
"text": "The shorted path from node :\n0 to 0 is 0\n0 to 1 is 8\n0 to 2 is 6\n0 to 3 is 5\n0 to 4 is 3"
},
{
"code": null,
"e": 31613,
"s": 31604,
"text": "jyoti369"
},
{
"code": null,
"e": 31626,
"s": 31613,
"text": "iramkhalid24"
},
{
"code": null,
"e": 31644,
"s": 31626,
"text": "germanshephered48"
},
{
"code": null,
"e": 31653,
"s": 31644,
"text": "Dijkstra"
},
{
"code": null,
"e": 31673,
"s": 31653,
"text": "java-priority-queue"
},
{
"code": null,
"e": 31680,
"s": 31673,
"text": "Picked"
},
{
"code": null,
"e": 31694,
"s": 31680,
"text": "Shortest Path"
},
{
"code": null,
"e": 31708,
"s": 31694,
"text": "Java Programs"
},
{
"code": null,
"e": 31722,
"s": 31708,
"text": "Shortest Path"
},
{
"code": null,
"e": 31820,
"s": 31722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31829,
"s": 31820,
"text": "Comments"
},
{
"code": null,
"e": 31842,
"s": 31829,
"text": "Old Comments"
},
{
"code": null,
"e": 31868,
"s": 31842,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31900,
"s": 31868,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 31938,
"s": 31900,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 31973,
"s": 31938,
"text": "Traverse Through a HashMap in Java"
},
{
"code": null,
"e": 32002,
"s": 31973,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 32059,
"s": 32002,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 32140,
"s": 32059,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 32188,
"s": 32140,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 32205,
"s": 32188,
"text": "Min Heap in Java"
}
] |
Count the number of ways to traverse a Matrix - GeeksforGeeks | 03 Jun, 2021
Given a two-dimensional matrix, in how way can someone traverse it from top-left to bottom-right? Condition- At any particular cell the possible moves are either down or right, no other steps possible.Stop when the end is reached.
Examples:
Input : 3 3
Output : 6
Input : 5 5
Output : 70
If we look closely, we will find that the number of ways a cell can be reached is = Number of ways it can reach the cell above it + number of ways it can reach the cell which is left of it.
So, start filling the 2D array according to it and return the last cell after completely filling the array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program using recursive solution to count// number of ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][]#include <bits/stdc++.h>using namespace std; // Returns The number of way from top-left// to mat[m-1][n-1]int countPaths(int m, int n){ // Return 1 if it is the first row or // first column if (m == 1 || n == 1) return 1; // Recursively find the no of way to // reach the last cell. return countPaths(m - 1, n) + countPaths(m, n - 1);} // Driver codeint main(){ int n = 5; int m = 5; cout << countPaths(n, m); return 0;}
// Java program using recursive// solution to count number of// ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][]import java.lang.*;import java.util.*; class GFG{// Returns The number of way// from top-left to mat[m-1][n-1]public int countPaths(int m, int n){ // Return 1 if it is the first // row or first column if (m == 1 || n == 1) return 1; // Recursively find the no of // way to reach the last cell. return countPaths(m - 1, n) + countPaths(m, n - 1);} // Driver Codepublic static void main(String args[]){ GFG g = new GFG(); int n = 5, m = 5; System.out.println(g.countPaths(n, m));}} // This code is contributed// by Akanksha Rai(Abby_akku)
# Python3 program using recursive solution to count# number of ways to reach mat[m-1][n-1] from# mat[0][0] in a matrix mat[][] # Returns The number of way from top-left# to mat[m-1][n-1]def countPaths(m, n) : # Return 1 if it is the first row or # first column if m == 1 or n == 1 : return 1 # Recursively find the no of way to # reach the last cell. return (countPaths(m - 1, n) + countPaths(m, n - 1)) # Driver code if __name__ == "__main__" : n = 5 m = 5 print(countPaths(n, m)) # This code is contributed by ANKITRAI1
// C# program using recursive// solution to count number of// ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][]using System; class GFG{// Returns The number of way// from top-left to mat[m-1][n-1]public int countPaths(int m, int n){ // Return 1 if it is the first // row or first column if (m == 1 || n == 1) return 1; // Recursively find the no of // way to reach the last cell. return countPaths(m - 1, n) + countPaths(m, n - 1);} // Driver Codepublic static void Main(){ GFG g = new GFG(); int n = 5, m = 5; Console.WriteLine(g.countPaths(n, m)); Console.Read();}} // This code is contributed// by SoumikMondal
<?php// PHP program using recursive// solution to count number of// ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][] // Returns The number of way// from top-left to mat[m-1][n-1] function countPaths($m, $n){ // Return 1 if it is the // first row or first column if ($m == 1 || $n == 1) return 1; // Recursively find the no of // way to reach the last cell. return countPaths($m - 1, $n) + countPaths($m, $n - 1);} // Driver code$n = 5;$m = 5;echo countPaths($n, $m); // This code is contributed by jit_t?>
<script> // Javascript program using recursive // solution to count number of // ways to reach mat[m-1][n-1] from // mat[0][0] in a matrix mat[][] // Returns The number of way // from top-left to mat[m-1][n-1] function countPaths(m, n) { // Return 1 if it is the first // row or first column if (m == 1 || n == 1) return 1; // Recursively find the no of // way to reach the last cell. return countPaths(m - 1, n) + countPaths(m, n - 1); } let n = 5, m = 5; document.write(countPaths(n, m)); // This code is contributed by suresh07.</script>
70
The above solution has exponential time complexity. It can be optimized using Dynamic Programming as there are overlapping subproblems (highlighted below in partial recursion tree for m=3, n=3)
CP(3, 3)
/ \
CP(2, 3) CP(3, 2)
/ \ / \
CP(1,3) CP(2,2) CP(2,2) CP(3,1)
C++
Java
Python3
C#
PHP
Javascript
// A simple recursive solution to count// number of ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][]#include <bits/stdc++.h>using namespace std; // Returns The number of way from top-left// to mat[m-1][n-1]int countPaths(int m, int n){ int dp[m+1][n+1]; for (int i=1; i<=m; i++) { for (int j=1; j<=n; j++) { if (i==1 || j == 1) dp[i][j] = 1; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m][n];} // Driver codeint main(){ int n = 5; int m = 5; cout << countPaths(n, m); return 0;}
// A simple recursive solution to count// number of ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][] class GFG{ // Returns The number of way from top-left // to mat[m-1][n-1] static int countPaths(int m, int n) { int [][]dp=new int[m+1][n+1]; for (int i=1; i<=m; i++) { for (int j=1; j<=n; j++) { if (i==1 || j == 1) dp[i][j] = 1; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m][n]; } // Driver code public static void main(String []args) { int n = 5; int m = 5; System.out.println(countPaths(n, m)); }} // This code is contributed// by ihritik (Hritik Raj)
# A simple recursive solution to# count number of ways to reach# mat[m-1][n-1] from mat[0][0]# in a matrix mat[][] # Returns The number of way# from top-left to mat[m-1][n-1]def countPaths(m, n): dp = [[0 for i in range(m + 1)] for j in range(n + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if (i == 1 or j == 1): dp[i][j] = 1 else: dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) return dp[m][n] # Driver codeif __name__ =="__main__": n = 5 m = 5 print(countPaths(n, m)) # This code is contributed# by ChitraNayal
// A simple recursive solution to count// number of ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][] using System;class GFG{ // Returns The number of way from top-left // to mat[m-1][n-1] static int countPaths(int m, int n) { int [,]dp=new int[m+1,n+1]; for (int i=1; i<=m; i++) { for (int j=1; j<=n; j++) { if (i==1 || j == 1) dp[i,j] = 1; else dp[i,j] = dp[i-1,j] + dp[i,j-1]; } } return dp[m,n]; } // Driver code public static void Main() { int n = 5; int m = 5; Console.WriteLine(countPaths(n, m)); }} // This code is contributed// by ihritik (Hritik Raj)
<?php// A simple recursive solution to count// number of ways to reach mat[m-1][n-1]// from mat[0][0] in a matrix mat[][] // Returns The number of way from top-left// to mat[m-1][n-1]function countPaths($m, $n){ $dp; for ($i = 1; $i <= $m; $i++) { for ($j = 1; $j <= $n; $j++) { if ($i == 1 || $j == 1) $dp[$i][$j] = 1; else $dp[$i][$j] = $dp[$i - 1][$j] + $dp[$i][$j - 1]; } } return $dp[$m][$n];} // Driver code$n = 5;$m = 5;echo countPaths($n, $m); // This code is contributed by Rajput-Ji?>
<script> // A simple recursive solution to count // number of ways to reach mat[m-1][n-1] from // mat[0][0] in a matrix mat[][] // Returns The number of way from top-left // to mat[m-1][n-1] function countPaths(m, n) { let dp = new Array(m+1); for (let i=0; i<=m; i++) { dp[i] = new Array(n + 1); for (let j=0; j<=n; j++) { dp[i][j] = 0; } } for (let i=1; i<=m; i++) { for (let j=1; j<=n; j++) { if (i==1 || j == 1) dp[i][j] = 1; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m][n]; } let n = 5; let m = 5; document.write(countPaths(n, m)); </script>
70
Time Complexity: O(m * n)
Another Method(Efficient):
There is one more efficient way of reaching the solution in O(m) or O(n) whichever is greater.
We can permute the number of right operations and down operations.
Explanation:
In the given figure, we can see that for a matrix of 3×3, we need 2 right operations and 2 down operations.
Thus, we can permute these operations in any order, still we can reach the bottom-right.
“RRDD”,”RDRD”,”RDDR”,”DRDR”,”DDRR”,”DRRD”
Let the number of columns be m, and the number of rows is n, then no of permutations = (m+n)!/ (m!*n!)
Below is the implementation of the above logic.
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include<bits/stdc++.h>using namespace std; // Find factorialint factorial(int n){ int res = 1, i; for(i = 2; i <= n; i++) res *= i; return res;} // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]] int countWays(int m, int n){ m = m - 1; n = n - 1; return factorial(m + n) / (factorial(m) * factorial(n));} // Driver Codeint main(){ int m = 5; int n = 5; // Function call int result = countWays(m, n); cout << result;} // This code is contributed by chahattekwani71
// Java Program for above approachimport java.io.*; class GFG { // Find factorial static int factorial(int n) { int res = 1, i; for (i = 2; i <= n; i++) res *= i; return res; } // Find number of ways to reach // mat[m-1][n-1] from mat[0][0] // in a matrix mat[][]] static int countWays(int m, int n) { m = m - 1; n = n - 1; return factorial(m + n) / (factorial(m) * factorial(n)); } // Driver Code public static void main(String[] args) { int m = 5; int n = 5; // Function Call int result = countWays(m, n); System.out.println(result); }}
# Python3 program for# the above approach # Find factorialdef factorial(n): res = 1 for i in range(2, n + 1): res *= i return res # Find number of ways to reach# mat[m-1][n-1] from mat[0][0]# in a matrix mat[][]]def countWays(m, n): m = m - 1 n = n - 1 return (factorial(m + n) // (factorial(m) * factorial(n))) # Driver code m = 5n = 5 # Function callresult = countWays(m, n) print(result) # This code is contributed by divyeshrabadiya07
// C# Program for above approachusing System; class GFG{ // Find factorialstatic int factorial(int n){ int res = 1, i; for(i = 2; i <= n; i++) res *= i; return res;} // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]]static int countWays(int m, int n){ m = m - 1; n = n - 1; return factorial(m + n) / (factorial(m) * factorial(n));} // Driver codestatic void Main(){ int m = 5; int n = 5; // Function Call int result = countWays(m, n); Console.WriteLine(result);}} // This code is contributed by divyesh072019
<script> // JavaScript Program for above approach // Find factorialfunction factorial( n){ var res = 1, i; for(i = 2; i <= n; i++) res *= i; return res;} // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]]function countWays( m, n){ m = m - 1; n = n - 1; return factorial(m + n) / (factorial(m) * factorial(n));} // Driver code var m = 5; var n = 5; // Function Call var result = countWays(m, n); document.write(result); </script>
70
Time Complexity: O(n)
SoumikMondal
ankthon
ukasp
jit_t
Akanksha_Rai
ihritik
Rajput-Ji
Shubham Agrawal 13
chahattekwani71
divyeshrabadiya07
divyesh072019
bunnyram19
suresh07
Technical Scripter 2018
Dynamic Programming
Matrix
Dynamic Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Sudoku | Backtracking-7 | [
{
"code": null,
"e": 25008,
"s": 24980,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 25239,
"s": 25008,
"text": "Given a two-dimensional matrix, in how way can someone traverse it from top-left to bottom-right? Condition- At any particular cell the possible moves are either down or right, no other steps possible.Stop when the end is reached."
},
{
"code": null,
"e": 25250,
"s": 25239,
"text": "Examples: "
},
{
"code": null,
"e": 25298,
"s": 25250,
"text": "Input : 3 3\nOutput : 6\n\nInput : 5 5\nOutput : 70"
},
{
"code": null,
"e": 25489,
"s": 25298,
"text": "If we look closely, we will find that the number of ways a cell can be reached is = Number of ways it can reach the cell above it + number of ways it can reach the cell which is left of it. "
},
{
"code": null,
"e": 25597,
"s": 25489,
"text": "So, start filling the 2D array according to it and return the last cell after completely filling the array."
},
{
"code": null,
"e": 25648,
"s": 25597,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25652,
"s": 25648,
"text": "C++"
},
{
"code": null,
"e": 25657,
"s": 25652,
"text": "Java"
},
{
"code": null,
"e": 25665,
"s": 25657,
"text": "Python3"
},
{
"code": null,
"e": 25668,
"s": 25665,
"text": "C#"
},
{
"code": null,
"e": 25672,
"s": 25668,
"text": "PHP"
},
{
"code": null,
"e": 25683,
"s": 25672,
"text": "Javascript"
},
{
"code": "// C++ program using recursive solution to count// number of ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][]#include <bits/stdc++.h>using namespace std; // Returns The number of way from top-left// to mat[m-1][n-1]int countPaths(int m, int n){ // Return 1 if it is the first row or // first column if (m == 1 || n == 1) return 1; // Recursively find the no of way to // reach the last cell. return countPaths(m - 1, n) + countPaths(m, n - 1);} // Driver codeint main(){ int n = 5; int m = 5; cout << countPaths(n, m); return 0;}",
"e": 26278,
"s": 25683,
"text": null
},
{
"code": "// Java program using recursive// solution to count number of// ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][]import java.lang.*;import java.util.*; class GFG{// Returns The number of way// from top-left to mat[m-1][n-1]public int countPaths(int m, int n){ // Return 1 if it is the first // row or first column if (m == 1 || n == 1) return 1; // Recursively find the no of // way to reach the last cell. return countPaths(m - 1, n) + countPaths(m, n - 1);} // Driver Codepublic static void main(String args[]){ GFG g = new GFG(); int n = 5, m = 5; System.out.println(g.countPaths(n, m));}} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 26989,
"s": 26278,
"text": null
},
{
"code": "# Python3 program using recursive solution to count# number of ways to reach mat[m-1][n-1] from# mat[0][0] in a matrix mat[][] # Returns The number of way from top-left# to mat[m-1][n-1]def countPaths(m, n) : # Return 1 if it is the first row or # first column if m == 1 or n == 1 : return 1 # Recursively find the no of way to # reach the last cell. return (countPaths(m - 1, n) + countPaths(m, n - 1)) # Driver code if __name__ == \"__main__\" : n = 5 m = 5 print(countPaths(n, m)) # This code is contributed by ANKITRAI1",
"e": 27563,
"s": 26989,
"text": null
},
{
"code": "// C# program using recursive// solution to count number of// ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][]using System; class GFG{// Returns The number of way// from top-left to mat[m-1][n-1]public int countPaths(int m, int n){ // Return 1 if it is the first // row or first column if (m == 1 || n == 1) return 1; // Recursively find the no of // way to reach the last cell. return countPaths(m - 1, n) + countPaths(m, n - 1);} // Driver Codepublic static void Main(){ GFG g = new GFG(); int n = 5, m = 5; Console.WriteLine(g.countPaths(n, m)); Console.Read();}} // This code is contributed// by SoumikMondal",
"e": 28238,
"s": 27563,
"text": null
},
{
"code": "<?php// PHP program using recursive// solution to count number of// ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][] // Returns The number of way// from top-left to mat[m-1][n-1] function countPaths($m, $n){ // Return 1 if it is the // first row or first column if ($m == 1 || $n == 1) return 1; // Recursively find the no of // way to reach the last cell. return countPaths($m - 1, $n) + countPaths($m, $n - 1);} // Driver code$n = 5;$m = 5;echo countPaths($n, $m); // This code is contributed by jit_t?>",
"e": 28796,
"s": 28238,
"text": null
},
{
"code": "<script> // Javascript program using recursive // solution to count number of // ways to reach mat[m-1][n-1] from // mat[0][0] in a matrix mat[][] // Returns The number of way // from top-left to mat[m-1][n-1] function countPaths(m, n) { // Return 1 if it is the first // row or first column if (m == 1 || n == 1) return 1; // Recursively find the no of // way to reach the last cell. return countPaths(m - 1, n) + countPaths(m, n - 1); } let n = 5, m = 5; document.write(countPaths(n, m)); // This code is contributed by suresh07.</script>",
"e": 29450,
"s": 28796,
"text": null
},
{
"code": null,
"e": 29453,
"s": 29450,
"text": "70"
},
{
"code": null,
"e": 29648,
"s": 29453,
"text": "The above solution has exponential time complexity. It can be optimized using Dynamic Programming as there are overlapping subproblems (highlighted below in partial recursion tree for m=3, n=3) "
},
{
"code": null,
"e": 29777,
"s": 29648,
"text": " CP(3, 3)\n / \\\n CP(2, 3) CP(3, 2)\n / \\ / \\\n CP(1,3) CP(2,2) CP(2,2) CP(3,1)"
},
{
"code": null,
"e": 29781,
"s": 29777,
"text": "C++"
},
{
"code": null,
"e": 29786,
"s": 29781,
"text": "Java"
},
{
"code": null,
"e": 29794,
"s": 29786,
"text": "Python3"
},
{
"code": null,
"e": 29797,
"s": 29794,
"text": "C#"
},
{
"code": null,
"e": 29801,
"s": 29797,
"text": "PHP"
},
{
"code": null,
"e": 29812,
"s": 29801,
"text": "Javascript"
},
{
"code": "// A simple recursive solution to count// number of ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][]#include <bits/stdc++.h>using namespace std; // Returns The number of way from top-left// to mat[m-1][n-1]int countPaths(int m, int n){ int dp[m+1][n+1]; for (int i=1; i<=m; i++) { for (int j=1; j<=n; j++) { if (i==1 || j == 1) dp[i][j] = 1; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m][n];} // Driver codeint main(){ int n = 5; int m = 5; cout << countPaths(n, m); return 0;}",
"e": 30434,
"s": 29812,
"text": null
},
{
"code": "// A simple recursive solution to count// number of ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][] class GFG{ // Returns The number of way from top-left // to mat[m-1][n-1] static int countPaths(int m, int n) { int [][]dp=new int[m+1][n+1]; for (int i=1; i<=m; i++) { for (int j=1; j<=n; j++) { if (i==1 || j == 1) dp[i][j] = 1; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m][n]; } // Driver code public static void main(String []args) { int n = 5; int m = 5; System.out.println(countPaths(n, m)); }} // This code is contributed// by ihritik (Hritik Raj)",
"e": 31230,
"s": 30434,
"text": null
},
{
"code": "# A simple recursive solution to# count number of ways to reach# mat[m-1][n-1] from mat[0][0]# in a matrix mat[][] # Returns The number of way# from top-left to mat[m-1][n-1]def countPaths(m, n): dp = [[0 for i in range(m + 1)] for j in range(n + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if (i == 1 or j == 1): dp[i][j] = 1 else: dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) return dp[m][n] # Driver codeif __name__ ==\"__main__\": n = 5 m = 5 print(countPaths(n, m)) # This code is contributed# by ChitraNayal",
"e": 31894,
"s": 31230,
"text": null
},
{
"code": "// A simple recursive solution to count// number of ways to reach mat[m-1][n-1] from// mat[0][0] in a matrix mat[][] using System;class GFG{ // Returns The number of way from top-left // to mat[m-1][n-1] static int countPaths(int m, int n) { int [,]dp=new int[m+1,n+1]; for (int i=1; i<=m; i++) { for (int j=1; j<=n; j++) { if (i==1 || j == 1) dp[i,j] = 1; else dp[i,j] = dp[i-1,j] + dp[i,j-1]; } } return dp[m,n]; } // Driver code public static void Main() { int n = 5; int m = 5; Console.WriteLine(countPaths(n, m)); }} // This code is contributed// by ihritik (Hritik Raj)",
"e": 32682,
"s": 31894,
"text": null
},
{
"code": "<?php// A simple recursive solution to count// number of ways to reach mat[m-1][n-1]// from mat[0][0] in a matrix mat[][] // Returns The number of way from top-left// to mat[m-1][n-1]function countPaths($m, $n){ $dp; for ($i = 1; $i <= $m; $i++) { for ($j = 1; $j <= $n; $j++) { if ($i == 1 || $j == 1) $dp[$i][$j] = 1; else $dp[$i][$j] = $dp[$i - 1][$j] + $dp[$i][$j - 1]; } } return $dp[$m][$n];} // Driver code$n = 5;$m = 5;echo countPaths($n, $m); // This code is contributed by Rajput-Ji?>",
"e": 33312,
"s": 32682,
"text": null
},
{
"code": "<script> // A simple recursive solution to count // number of ways to reach mat[m-1][n-1] from // mat[0][0] in a matrix mat[][] // Returns The number of way from top-left // to mat[m-1][n-1] function countPaths(m, n) { let dp = new Array(m+1); for (let i=0; i<=m; i++) { dp[i] = new Array(n + 1); for (let j=0; j<=n; j++) { dp[i][j] = 0; } } for (let i=1; i<=m; i++) { for (let j=1; j<=n; j++) { if (i==1 || j == 1) dp[i][j] = 1; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m][n]; } let n = 5; let m = 5; document.write(countPaths(n, m)); </script>",
"e": 34150,
"s": 33312,
"text": null
},
{
"code": null,
"e": 34153,
"s": 34150,
"text": "70"
},
{
"code": null,
"e": 34179,
"s": 34153,
"text": "Time Complexity: O(m * n)"
},
{
"code": null,
"e": 34206,
"s": 34179,
"text": "Another Method(Efficient):"
},
{
"code": null,
"e": 34301,
"s": 34206,
"text": "There is one more efficient way of reaching the solution in O(m) or O(n) whichever is greater."
},
{
"code": null,
"e": 34368,
"s": 34301,
"text": "We can permute the number of right operations and down operations."
},
{
"code": null,
"e": 34381,
"s": 34368,
"text": "Explanation:"
},
{
"code": null,
"e": 34489,
"s": 34381,
"text": "In the given figure, we can see that for a matrix of 3×3, we need 2 right operations and 2 down operations."
},
{
"code": null,
"e": 34578,
"s": 34489,
"text": "Thus, we can permute these operations in any order, still we can reach the bottom-right."
},
{
"code": null,
"e": 34620,
"s": 34578,
"text": "“RRDD”,”RDRD”,”RDDR”,”DRDR”,”DDRR”,”DRRD”"
},
{
"code": null,
"e": 34723,
"s": 34620,
"text": "Let the number of columns be m, and the number of rows is n, then no of permutations = (m+n)!/ (m!*n!)"
},
{
"code": null,
"e": 34771,
"s": 34723,
"text": "Below is the implementation of the above logic."
},
{
"code": null,
"e": 34775,
"s": 34771,
"text": "C++"
},
{
"code": null,
"e": 34780,
"s": 34775,
"text": "Java"
},
{
"code": null,
"e": 34788,
"s": 34780,
"text": "Python3"
},
{
"code": null,
"e": 34791,
"s": 34788,
"text": "C#"
},
{
"code": null,
"e": 34802,
"s": 34791,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include<bits/stdc++.h>using namespace std; // Find factorialint factorial(int n){ int res = 1, i; for(i = 2; i <= n; i++) res *= i; return res;} // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]] int countWays(int m, int n){ m = m - 1; n = n - 1; return factorial(m + n) / (factorial(m) * factorial(n));} // Driver Codeint main(){ int m = 5; int n = 5; // Function call int result = countWays(m, n); cout << result;} // This code is contributed by chahattekwani71",
"e": 35422,
"s": 34802,
"text": null
},
{
"code": "// Java Program for above approachimport java.io.*; class GFG { // Find factorial static int factorial(int n) { int res = 1, i; for (i = 2; i <= n; i++) res *= i; return res; } // Find number of ways to reach // mat[m-1][n-1] from mat[0][0] // in a matrix mat[][]] static int countWays(int m, int n) { m = m - 1; n = n - 1; return factorial(m + n) / (factorial(m) * factorial(n)); } // Driver Code public static void main(String[] args) { int m = 5; int n = 5; // Function Call int result = countWays(m, n); System.out.println(result); }}",
"e": 36111,
"s": 35422,
"text": null
},
{
"code": "# Python3 program for# the above approach # Find factorialdef factorial(n): res = 1 for i in range(2, n + 1): res *= i return res # Find number of ways to reach# mat[m-1][n-1] from mat[0][0]# in a matrix mat[][]]def countWays(m, n): m = m - 1 n = n - 1 return (factorial(m + n) // (factorial(m) * factorial(n))) # Driver code m = 5n = 5 # Function callresult = countWays(m, n) print(result) # This code is contributed by divyeshrabadiya07",
"e": 36616,
"s": 36111,
"text": null
},
{
"code": "// C# Program for above approachusing System; class GFG{ // Find factorialstatic int factorial(int n){ int res = 1, i; for(i = 2; i <= n; i++) res *= i; return res;} // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]]static int countWays(int m, int n){ m = m - 1; n = n - 1; return factorial(m + n) / (factorial(m) * factorial(n));} // Driver codestatic void Main(){ int m = 5; int n = 5; // Function Call int result = countWays(m, n); Console.WriteLine(result);}} // This code is contributed by divyesh072019",
"e": 37236,
"s": 36616,
"text": null
},
{
"code": "<script> // JavaScript Program for above approach // Find factorialfunction factorial( n){ var res = 1, i; for(i = 2; i <= n; i++) res *= i; return res;} // Find number of ways to reach// mat[m-1][n-1] from mat[0][0]// in a matrix mat[][]]function countWays( m, n){ m = m - 1; n = n - 1; return factorial(m + n) / (factorial(m) * factorial(n));} // Driver code var m = 5; var n = 5; // Function Call var result = countWays(m, n); document.write(result); </script>",
"e": 37789,
"s": 37236,
"text": null
},
{
"code": null,
"e": 37792,
"s": 37789,
"text": "70"
},
{
"code": null,
"e": 37814,
"s": 37792,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 37827,
"s": 37814,
"text": "SoumikMondal"
},
{
"code": null,
"e": 37835,
"s": 37827,
"text": "ankthon"
},
{
"code": null,
"e": 37841,
"s": 37835,
"text": "ukasp"
},
{
"code": null,
"e": 37847,
"s": 37841,
"text": "jit_t"
},
{
"code": null,
"e": 37860,
"s": 37847,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 37868,
"s": 37860,
"text": "ihritik"
},
{
"code": null,
"e": 37878,
"s": 37868,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37897,
"s": 37878,
"text": "Shubham Agrawal 13"
},
{
"code": null,
"e": 37913,
"s": 37897,
"text": "chahattekwani71"
},
{
"code": null,
"e": 37931,
"s": 37913,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 37945,
"s": 37931,
"text": "divyesh072019"
},
{
"code": null,
"e": 37956,
"s": 37945,
"text": "bunnyram19"
},
{
"code": null,
"e": 37965,
"s": 37956,
"text": "suresh07"
},
{
"code": null,
"e": 37989,
"s": 37965,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 38009,
"s": 37989,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38016,
"s": 38009,
"text": "Matrix"
},
{
"code": null,
"e": 38036,
"s": 38016,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38043,
"s": 38036,
"text": "Matrix"
},
{
"code": null,
"e": 38141,
"s": 38043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38172,
"s": 38141,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 38205,
"s": 38172,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 38240,
"s": 38205,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 38308,
"s": 38240,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 38335,
"s": 38308,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 38370,
"s": 38335,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 38414,
"s": 38370,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 38445,
"s": 38414,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 38507,
"s": 38445,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
}
] |
Get the sum of columns for duplicate records in MySQL | For this, use GROUP BY clause along with aggregate function SUM(). Let us first create a table −
mysql> create table DemoTable(
Name varchar(100),
Score int
);
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Adam',50);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob',80);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Adam',70);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Adam',10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Carol',98);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Bob',10);
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+-------+
| Name | Score |
+-------+-------+
| Adam | 50 |
| Bob | 80 |
| Adam | 70 |
| Adam | 10 |
| Carol | 98 |
| Bob | 10 |
+-------+-------+
6 rows in set (0.00 sec)
Following is the query to get the sum of columns for duplicate records in MySQL −
mysql> select Name,sum(Score) from DemoTable group by Name;
This will produce the following output −
+-------+------------+
| Name | sum(Score) |
+-------+------------+
| Adam | 130 |
| Bob | 90 |
| Carol | 98 |
+-------+------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "For this, use GROUP BY clause along with aggregate function SUM(). Let us first create a table −"
},
{
"code": null,
"e": 1265,
"s": 1159,
"text": "mysql> create table DemoTable(\n Name varchar(100),\n Score int\n);\nQuery OK, 0 rows affected (0.70 sec)"
},
{
"code": null,
"e": 1321,
"s": 1265,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1824,
"s": 1321,
"text": "mysql> insert into DemoTable values('Adam',50);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Bob',80);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('Adam',70);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Adam',10);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Carol',98);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values('Bob',10);\nQuery OK, 1 row affected (0.08 sec)"
},
{
"code": null,
"e": 1884,
"s": 1824,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1915,
"s": 1884,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1956,
"s": 1915,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2161,
"s": 1956,
"text": "+-------+-------+\n| Name | Score |\n+-------+-------+\n| Adam | 50 |\n| Bob | 80 |\n| Adam | 70 |\n| Adam | 10 |\n| Carol | 98 |\n| Bob | 10 |\n+-------+-------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2243,
"s": 2161,
"text": "Following is the query to get the sum of columns for duplicate records in MySQL −"
},
{
"code": null,
"e": 2303,
"s": 2243,
"text": "mysql> select Name,sum(Score) from DemoTable group by Name;"
},
{
"code": null,
"e": 2344,
"s": 2303,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2530,
"s": 2344,
"text": "+-------+------------+\n| Name | sum(Score) |\n+-------+------------+\n| Adam | 130 |\n| Bob | 90 |\n| Carol | 98 |\n+-------+------------+\n3 rows in set (0.00 sec)"
}
] |
Handling Click events in Button | Android - GeeksforGeeks | 14 Sep, 2018
There are 2 ways to handle the click event in button
Onclick in xml layout
Using an OnClickListener
Onclick in XML layout
When the user clicks a button, the Button object receives an on-click event.
To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
NOTE:If you use this event handler in your code, make sure that you are having that button in your MainActivity. It won’t work if you use this event handler in fragment because onClick attribute only works in Activity or MainActivity.
Example:
<Button xmlns:android="http:// schemas.android.com/apk/res/android" android:id="@+id/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" android:onClick="sendMessage" />
In MainActivity class
/** Called when the user touches the button */public void sendMessage(View view){ // Do something in response to button click}
Make sure that your sendMessage method should have the following :
Be public
Return void
Define a View as its only parameter (this will be the View that was clicked)Using an OnClickListenerYou can also declare the click event handler programmatically rather than in an XML layout. This event handler code is mostly preferred because it can be used in both Activities and Fragments.There are two ways to do this event handler programmatically :Implementing View.OnClickListener in your Activity or fragment.Creating new anonymous View.OnClickListener.Implementing View.OnClickListener in your Activity or fragmentTo implement View.OnClickListener in your Activity or Fragment, you have to override onClick method on your class.Firstly, link the button in xml layout to java by calling findViewById() method.R.id.button_send refers the button in XML.mButton.setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface.<RelativeLayout xmlns:android="http:// schemas.android.com/apk/res/android" xmlns:app="http:// schemas.android.com/apk/res-auto" xmlns:tools="http:// schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.sample.MainActivity" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button_send" /></RelativeLayout>MainActivity code:public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button_send); mButton.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.button_send: // Do something } }}If you have more than one button click event, you can use switch case to identify which button is clicked.Creating Anonymous View.OnClickListenerLink the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method.MainActivity code:public class MainActivity extends AppCompatActivity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button_send); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Do something } }); }}setOnClickListener takes an OnClickListener object as the parameter. Basically it’s creating an anonymous subclass OnClickListener in the parameter.It’s like the same in java when you can create a new thread with an anonymous subclass.My Personal Notes
arrow_drop_upSave
Using an OnClickListener
You can also declare the click event handler programmatically rather than in an XML layout. This event handler code is mostly preferred because it can be used in both Activities and Fragments.
There are two ways to do this event handler programmatically :
Implementing View.OnClickListener in your Activity or fragment.
Creating new anonymous View.OnClickListener.
Implementing View.OnClickListener in your Activity or fragment
To implement View.OnClickListener in your Activity or Fragment, you have to override onClick method on your class.
Firstly, link the button in xml layout to java by calling findViewById() method.R.id.button_send refers the button in XML.
mButton.setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface.
<RelativeLayout xmlns:android="http:// schemas.android.com/apk/res/android" xmlns:app="http:// schemas.android.com/apk/res-auto" xmlns:tools="http:// schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.sample.MainActivity" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button_send" /></RelativeLayout>
MainActivity code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button_send); mButton.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.button_send: // Do something } }}
If you have more than one button click event, you can use switch case to identify which button is clicked.
Creating Anonymous View.OnClickListener
Link the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method.
MainActivity code:
public class MainActivity extends AppCompatActivity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button_send); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Do something } }); }}
setOnClickListener takes an OnClickListener object as the parameter. Basically it’s creating an anonymous subclass OnClickListener in the parameter.
It’s like the same in java when you can create a new thread with an anonymous subclass.
Vijayaraghavan
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
10 Best IDE For Web Developers in 2022
A Freshers Guide To Programming
Top 5 Python Libraries For Big Data
Top 10 Programming Languages to Learn in 2022
ML | Underfitting and Overfitting
Top 10 Python Books for Beginners and Advanced Programmers
Virtualization In Cloud Computing and Types
How to Install and Run Apache Kafka on Windows? | [
{
"code": null,
"e": 25008,
"s": 24980,
"text": "\n14 Sep, 2018"
},
{
"code": null,
"e": 25061,
"s": 25008,
"text": "There are 2 ways to handle the click event in button"
},
{
"code": null,
"e": 25083,
"s": 25061,
"text": "Onclick in xml layout"
},
{
"code": null,
"e": 25108,
"s": 25083,
"text": "Using an OnClickListener"
},
{
"code": null,
"e": 25130,
"s": 25108,
"text": "Onclick in XML layout"
},
{
"code": null,
"e": 25207,
"s": 25130,
"text": "When the user clicks a button, the Button object receives an on-click event."
},
{
"code": null,
"e": 25489,
"s": 25207,
"text": "To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method."
},
{
"code": null,
"e": 25724,
"s": 25489,
"text": "NOTE:If you use this event handler in your code, make sure that you are having that button in your MainActivity. It won’t work if you use this event handler in fragment because onClick attribute only works in Activity or MainActivity."
},
{
"code": null,
"e": 25733,
"s": 25724,
"text": "Example:"
},
{
"code": "<Button xmlns:android=\"http:// schemas.android.com/apk/res/android\" android:id=\"@+id/button_send\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"@string/button_send\" android:onClick=\"sendMessage\" />",
"e": 25987,
"s": 25733,
"text": null
},
{
"code": null,
"e": 26009,
"s": 25987,
"text": "In MainActivity class"
},
{
"code": "/** Called when the user touches the button */public void sendMessage(View view){ // Do something in response to button click}",
"e": 26139,
"s": 26009,
"text": null
},
{
"code": null,
"e": 26206,
"s": 26139,
"text": "Make sure that your sendMessage method should have the following :"
},
{
"code": null,
"e": 26216,
"s": 26206,
"text": "Be public"
},
{
"code": null,
"e": 26228,
"s": 26216,
"text": "Return void"
},
{
"code": null,
"e": 29284,
"s": 26228,
"text": "Define a View as its only parameter (this will be the View that was clicked)Using an OnClickListenerYou can also declare the click event handler programmatically rather than in an XML layout. This event handler code is mostly preferred because it can be used in both Activities and Fragments.There are two ways to do this event handler programmatically :Implementing View.OnClickListener in your Activity or fragment.Creating new anonymous View.OnClickListener.Implementing View.OnClickListener in your Activity or fragmentTo implement View.OnClickListener in your Activity or Fragment, you have to override onClick method on your class.Firstly, link the button in xml layout to java by calling findViewById() method.R.id.button_send refers the button in XML.mButton.setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface.<RelativeLayout xmlns:android=\"http:// schemas.android.com/apk/res/android\" xmlns:app=\"http:// schemas.android.com/apk/res-auto\" xmlns:tools=\"http:// schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.example.sample.MainActivity\" > <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/button_send\" /></RelativeLayout>MainActivity code:public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button_send); mButton.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.button_send: // Do something } }}If you have more than one button click event, you can use switch case to identify which button is clicked.Creating Anonymous View.OnClickListenerLink the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method.MainActivity code:public class MainActivity extends AppCompatActivity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button_send); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Do something } }); }}setOnClickListener takes an OnClickListener object as the parameter. Basically it’s creating an anonymous subclass OnClickListener in the parameter.It’s like the same in java when you can create a new thread with an anonymous subclass.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29309,
"s": 29284,
"text": "Using an OnClickListener"
},
{
"code": null,
"e": 29502,
"s": 29309,
"text": "You can also declare the click event handler programmatically rather than in an XML layout. This event handler code is mostly preferred because it can be used in both Activities and Fragments."
},
{
"code": null,
"e": 29565,
"s": 29502,
"text": "There are two ways to do this event handler programmatically :"
},
{
"code": null,
"e": 29629,
"s": 29565,
"text": "Implementing View.OnClickListener in your Activity or fragment."
},
{
"code": null,
"e": 29674,
"s": 29629,
"text": "Creating new anonymous View.OnClickListener."
},
{
"code": null,
"e": 29737,
"s": 29674,
"text": "Implementing View.OnClickListener in your Activity or fragment"
},
{
"code": null,
"e": 29852,
"s": 29737,
"text": "To implement View.OnClickListener in your Activity or Fragment, you have to override onClick method on your class."
},
{
"code": null,
"e": 29975,
"s": 29852,
"text": "Firstly, link the button in xml layout to java by calling findViewById() method.R.id.button_send refers the button in XML."
},
{
"code": null,
"e": 30189,
"s": 29975,
"text": "mButton.setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface."
},
{
"code": "<RelativeLayout xmlns:android=\"http:// schemas.android.com/apk/res/android\" xmlns:app=\"http:// schemas.android.com/apk/res-auto\" xmlns:tools=\"http:// schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.example.sample.MainActivity\" > <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:id=\"@+id/button_send\" /></RelativeLayout>",
"e": 30664,
"s": 30189,
"text": null
},
{
"code": null,
"e": 30683,
"s": 30664,
"text": "MainActivity code:"
},
{
"code": "public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button_send); mButton.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.button_send: // Do something } }}",
"e": 31217,
"s": 30683,
"text": null
},
{
"code": null,
"e": 31324,
"s": 31217,
"text": "If you have more than one button click event, you can use switch case to identify which button is clicked."
},
{
"code": null,
"e": 31364,
"s": 31324,
"text": "Creating Anonymous View.OnClickListener"
},
{
"code": null,
"e": 31493,
"s": 31364,
"text": "Link the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method."
},
{
"code": null,
"e": 31512,
"s": 31493,
"text": "MainActivity code:"
},
{
"code": "public class MainActivity extends AppCompatActivity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = findViewById(R.id.button_send); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Do something } }); }}",
"e": 32010,
"s": 31512,
"text": null
},
{
"code": null,
"e": 32159,
"s": 32010,
"text": "setOnClickListener takes an OnClickListener object as the parameter. Basically it’s creating an anonymous subclass OnClickListener in the parameter."
},
{
"code": null,
"e": 32247,
"s": 32159,
"text": "It’s like the same in java when you can create a new thread with an anonymous subclass."
},
{
"code": null,
"e": 32262,
"s": 32247,
"text": "Vijayaraghavan"
},
{
"code": null,
"e": 32268,
"s": 32262,
"text": "GBlog"
},
{
"code": null,
"e": 32366,
"s": 32268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32408,
"s": 32366,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 32433,
"s": 32408,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32472,
"s": 32433,
"text": "10 Best IDE For Web Developers in 2022"
},
{
"code": null,
"e": 32504,
"s": 32472,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 32540,
"s": 32504,
"text": "Top 5 Python Libraries For Big Data"
},
{
"code": null,
"e": 32586,
"s": 32540,
"text": "Top 10 Programming Languages to Learn in 2022"
},
{
"code": null,
"e": 32620,
"s": 32586,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 32679,
"s": 32620,
"text": "Top 10 Python Books for Beginners and Advanced Programmers"
},
{
"code": null,
"e": 32723,
"s": 32679,
"text": "Virtualization In Cloud Computing and Types"
}
] |
Difference between ++*p, *p++ and *++p in C | In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions. * is dereference operator. Precedence of prefix ++ and * is same and both are right to left associative. Precedence of postfix ++ is higher than both prefix ++ and * and is left to right associative. See the below example to understand the difference between ++*p, *p++ and *++p.
Live Demo
#include <stdio.h>
int main() {
int arr[] = {20, 30, 40};
int *p = arr;
int q;
//value of p (20) incremented by 1
//and returned
q = ++*p;
printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d \n",
arr[0], arr[1], *p, q);
//value of p (20) is returned
//pointer incremented by 1
q = *p++;
printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d \n",
arr[0], arr[1], *p, q);
//pointer incremented by 1
//value returned
q = *++p;
printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d \n",
arr[0], arr[1], *p, q);
return 0;
}
arr[0] = 21, arr[1] = 30, *p = 21, q = 21
arr[0] = 21, arr[1] = 30, *p = 30, q = 21
arr[0] = 21, arr[1] = 30, *p = 40, q = 40 | [
{
"code": null,
"e": 1479,
"s": 1062,
"text": "In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions. * is dereference operator. Precedence of prefix ++ and * is same and both are right to left associative. Precedence of postfix ++ is higher than both prefix ++ and * and is left to right associative. See the below example to understand the difference between ++*p, *p++ and *++p."
},
{
"code": null,
"e": 1490,
"s": 1479,
"text": " Live Demo"
},
{
"code": null,
"e": 2056,
"s": 1490,
"text": "#include <stdio.h>\nint main() {\n int arr[] = {20, 30, 40};\n int *p = arr;\n int q;\n //value of p (20) incremented by 1\n //and returned\n q = ++*p;\n printf(\"arr[0] = %d, arr[1] = %d, *p = %d, q = %d \\n\",\n arr[0], arr[1], *p, q);\n //value of p (20) is returned\n //pointer incremented by 1\n q = *p++;\n printf(\"arr[0] = %d, arr[1] = %d, *p = %d, q = %d \\n\",\n arr[0], arr[1], *p, q);\n //pointer incremented by 1\n //value returned\n q = *++p;\n printf(\"arr[0] = %d, arr[1] = %d, *p = %d, q = %d \\n\",\n arr[0], arr[1], *p, q);\n return 0;\n}"
},
{
"code": null,
"e": 2182,
"s": 2056,
"text": "arr[0] = 21, arr[1] = 30, *p = 21, q = 21\narr[0] = 21, arr[1] = 30, *p = 30, q = 21\narr[0] = 21, arr[1] = 30, *p = 40, q = 40"
}
] |
Virtual base class in C++ | In this tutorial, we will be discussing a program to understand virtual base class in C++.
Virtual classes are primarily used during multiple inheritance. To avoid, multiple instances of the same class being taken to the same class which later causes ambiguity, virtual classes are used.
Live Demo
#include <iostream>
using namespace std;
class A {
public:
int a;
A(){
a = 10;
}
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main(){
//creating class D object
D object;
cout << "a = " << object.a << endl;
return 0;
}
a = 10 | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to understand virtual base class in C++."
},
{
"code": null,
"e": 1350,
"s": 1153,
"text": "Virtual classes are primarily used during multiple inheritance. To avoid, multiple instances of the same class being taken to the same class which later causes ambiguity, virtual classes are used."
},
{
"code": null,
"e": 1361,
"s": 1350,
"text": " Live Demo"
},
{
"code": null,
"e": 1669,
"s": 1361,
"text": "#include <iostream>\nusing namespace std;\nclass A {\n public:\n int a;\n A(){\n a = 10;\n }\n};\nclass B : public virtual A {\n};\nclass C : public virtual A {\n};\nclass D : public B, public C {\n};\nint main(){\n //creating class D object\n D object;\n cout << \"a = \" << object.a << endl;\n return 0;\n}"
},
{
"code": null,
"e": 1676,
"s": 1669,
"text": "a = 10"
}
] |
Flutter - AnimatedContainer Widget - GeeksforGeeks | 21 Feb, 2022
In Flutter a container is a simple widget with well-defined properties like height, width, and color, etc. The AnimatedContainer widget is a simple container widget with animations. These types of widgets can be animated by altering the values of their properties which are the same as the Container widget. These types of animation in Flutter is known as ‘Implicit Animation. We will discuss then in detail in this article by building a simple app with AnimatedContainer widget.
Constructor of AnimatedContainer class:
AnimatedContainer(
{Key key,
AlignmentGeometry alignment,
EdgeInsetsGeometry padding,
Color color,
Decoration decoration,
Decoration foregroundDecoration,
double width,
double height,
BoxConstraints constraints,
EdgeInsetsGeometry margin,
Matrix4 transform,
Widget child,
Curve curve: Curves.linear,
@required Duration duration,
VoidCallback onEnd}
)
Properties of AnimatedContainer Widget:
alignment: This property takes AlignmentGeometry class as the object. It controls the alignment of the child widget with the container.
child: This property holds a widget as the object to show inside the AnimatedContainer.
constraints: BoxConstraints class is the object to this property. It applies some extra constraints to the child widget in the AnimatedContainer.
decoration: This property takes in Decoration class as the object to apply color behind the child widget.
foregroundDecoration: This property controls the default color of the text inside the AnimatedContainer.
margin: The margin property holds EdgeInsetsGeometry class as the object. It adds empty space around the widget.
padding: This property also takes EdgeInsetsGeometry class as the object to add empty space inside the AnimatedConatainer and the child widget.
transform: This property takes Matrix4 as the object to apply matrix transformation before painting the AnimatedContainer.
Follow the below steps to build an application with AnimatedContainer widget:
Create a StatefulWidget and define its properties.
Add an AnimatedContainer widget and define its properties.
Create animation by altering those properties.
Let’s discuss them in detail.
Use the custom State class to create a StatefulWidget and define its properties as shown below:
Dart
class AnimatedContainerApp extends StatefulWidget { @override _AnimatedContainerAppState createState() => _AnimatedContainerAppState();} class _AnimatedContainerAppState extends State<AnimatedContainerApp> { double _width = 55; double _height = 55; Color _color = Colors.green; BorderRadiusGeometry _borderRadius = BorderRadius.circular(9); @override Widget build(BuildContext context) { }}
Add an AnimatedContainer widget with its duration property defined that determines how long the container is going to animate as shown below:
Dart
AnimatedContainer( width: _width, height: _height, decoration: BoxDecoration( color: _color, borderRadius: _borderRadius, ), duration: Duration(seconds: 1), curve: Curves.fastOutSlowIn,);
Rebuilding and changing the properties after the end of duration specified property is done as shown below:
Dart
FloatingActionButton( child: Icon(Icons.play_arrow), onPressed: () { setState(() { final random = Random(); // random dimension generator _width = random.nextInt(300).toDouble(); _height = random.nextInt(300).toDouble(); // random color generator _color = Color.fromRGBO( random.nextInt(256), random.nextInt(256), random.nextInt(256), 1, ); _borderRadius = BorderRadius.circular(random.nextInt(100).toDouble()); }); },);
Complete Source Code:
Dart
import 'dart:math'; import 'package:flutter/material.dart'; void main() => runApp(AnimatedContainerApp()); class AnimatedContainerApp extends StatefulWidget { @override _AnimatedContainerAppState createState() => _AnimatedContainerAppState();} class _AnimatedContainerAppState extends State<AnimatedContainerApp> { double _width = 70; double _height = 70; Color _color = Colors.green; BorderRadiusGeometry _borderRadius = BorderRadius.circular(10); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: AnimatedContainer( width: _width, height: _height, decoration: BoxDecoration( color: _color, borderRadius: _borderRadius, ), duration: Duration(seconds: 1), curve: Curves.fastOutSlowIn, ), ), floatingActionButton: FloatingActionButton( child: Icon(Icons.play_arrow), backgroundColor: Colors.green, onPressed: () { setState(() { // random generator final random = Random(); // random dimension generator _width = random.nextInt(500).toDouble(); _height = random.nextInt(500).toDouble(); // random color generator _color = Color.fromRGBO( random.nextInt(300), random.nextInt(300), random.nextInt(300), 1, ); // random radius generator _borderRadius = BorderRadius.circular(random.nextInt(100).toDouble()); }); }, ), ), ); }}
Output:
Media error: Format(s) not supported or source(s) not found
ankit_kumar_
varshagumber28
android
Flutter
Flutter-widgets
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
What is widgets in Flutter?
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - BorderRadius Widget | [
{
"code": null,
"e": 24036,
"s": 24008,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 24516,
"s": 24036,
"text": "In Flutter a container is a simple widget with well-defined properties like height, width, and color, etc. The AnimatedContainer widget is a simple container widget with animations. These types of widgets can be animated by altering the values of their properties which are the same as the Container widget. These types of animation in Flutter is known as ‘Implicit Animation. We will discuss then in detail in this article by building a simple app with AnimatedContainer widget."
},
{
"code": null,
"e": 24556,
"s": 24516,
"text": "Constructor of AnimatedContainer class:"
},
{
"code": null,
"e": 24907,
"s": 24556,
"text": "AnimatedContainer(\n{Key key,\nAlignmentGeometry alignment,\nEdgeInsetsGeometry padding,\nColor color,\nDecoration decoration,\nDecoration foregroundDecoration,\ndouble width,\ndouble height,\nBoxConstraints constraints,\nEdgeInsetsGeometry margin,\nMatrix4 transform,\nWidget child,\nCurve curve: Curves.linear,\n@required Duration duration,\nVoidCallback onEnd}\n)"
},
{
"code": null,
"e": 24947,
"s": 24907,
"text": "Properties of AnimatedContainer Widget:"
},
{
"code": null,
"e": 25084,
"s": 24947,
"text": "alignment: This property takes AlignmentGeometry class as the object. It controls the alignment of the child widget with the container."
},
{
"code": null,
"e": 25172,
"s": 25084,
"text": "child: This property holds a widget as the object to show inside the AnimatedContainer."
},
{
"code": null,
"e": 25318,
"s": 25172,
"text": "constraints: BoxConstraints class is the object to this property. It applies some extra constraints to the child widget in the AnimatedContainer."
},
{
"code": null,
"e": 25424,
"s": 25318,
"text": "decoration: This property takes in Decoration class as the object to apply color behind the child widget."
},
{
"code": null,
"e": 25529,
"s": 25424,
"text": "foregroundDecoration: This property controls the default color of the text inside the AnimatedContainer."
},
{
"code": null,
"e": 25642,
"s": 25529,
"text": "margin: The margin property holds EdgeInsetsGeometry class as the object. It adds empty space around the widget."
},
{
"code": null,
"e": 25786,
"s": 25642,
"text": "padding: This property also takes EdgeInsetsGeometry class as the object to add empty space inside the AnimatedConatainer and the child widget."
},
{
"code": null,
"e": 25909,
"s": 25786,
"text": "transform: This property takes Matrix4 as the object to apply matrix transformation before painting the AnimatedContainer."
},
{
"code": null,
"e": 25987,
"s": 25909,
"text": "Follow the below steps to build an application with AnimatedContainer widget:"
},
{
"code": null,
"e": 26038,
"s": 25987,
"text": "Create a StatefulWidget and define its properties."
},
{
"code": null,
"e": 26097,
"s": 26038,
"text": "Add an AnimatedContainer widget and define its properties."
},
{
"code": null,
"e": 26144,
"s": 26097,
"text": "Create animation by altering those properties."
},
{
"code": null,
"e": 26174,
"s": 26144,
"text": "Let’s discuss them in detail."
},
{
"code": null,
"e": 26270,
"s": 26174,
"text": "Use the custom State class to create a StatefulWidget and define its properties as shown below:"
},
{
"code": null,
"e": 26275,
"s": 26270,
"text": "Dart"
},
{
"code": "class AnimatedContainerApp extends StatefulWidget { @override _AnimatedContainerAppState createState() => _AnimatedContainerAppState();} class _AnimatedContainerAppState extends State<AnimatedContainerApp> { double _width = 55; double _height = 55; Color _color = Colors.green; BorderRadiusGeometry _borderRadius = BorderRadius.circular(9); @override Widget build(BuildContext context) { }}",
"e": 26676,
"s": 26275,
"text": null
},
{
"code": null,
"e": 26818,
"s": 26676,
"text": "Add an AnimatedContainer widget with its duration property defined that determines how long the container is going to animate as shown below:"
},
{
"code": null,
"e": 26823,
"s": 26818,
"text": "Dart"
},
{
"code": "AnimatedContainer( width: _width, height: _height, decoration: BoxDecoration( color: _color, borderRadius: _borderRadius, ), duration: Duration(seconds: 1), curve: Curves.fastOutSlowIn,);",
"e": 27025,
"s": 26823,
"text": null
},
{
"code": null,
"e": 27134,
"s": 27025,
"text": "Rebuilding and changing the properties after the end of duration specified property is done as shown below:"
},
{
"code": null,
"e": 27139,
"s": 27134,
"text": "Dart"
},
{
"code": "FloatingActionButton( child: Icon(Icons.play_arrow), onPressed: () { setState(() { final random = Random(); // random dimension generator _width = random.nextInt(300).toDouble(); _height = random.nextInt(300).toDouble(); // random color generator _color = Color.fromRGBO( random.nextInt(256), random.nextInt(256), random.nextInt(256), 1, ); _borderRadius = BorderRadius.circular(random.nextInt(100).toDouble()); }); },);",
"e": 27649,
"s": 27139,
"text": null
},
{
"code": null,
"e": 27671,
"s": 27649,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 27676,
"s": 27671,
"text": "Dart"
},
{
"code": "import 'dart:math'; import 'package:flutter/material.dart'; void main() => runApp(AnimatedContainerApp()); class AnimatedContainerApp extends StatefulWidget { @override _AnimatedContainerAppState createState() => _AnimatedContainerAppState();} class _AnimatedContainerAppState extends State<AnimatedContainerApp> { double _width = 70; double _height = 70; Color _color = Colors.green; BorderRadiusGeometry _borderRadius = BorderRadius.circular(10); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center( child: AnimatedContainer( width: _width, height: _height, decoration: BoxDecoration( color: _color, borderRadius: _borderRadius, ), duration: Duration(seconds: 1), curve: Curves.fastOutSlowIn, ), ), floatingActionButton: FloatingActionButton( child: Icon(Icons.play_arrow), backgroundColor: Colors.green, onPressed: () { setState(() { // random generator final random = Random(); // random dimension generator _width = random.nextInt(500).toDouble(); _height = random.nextInt(500).toDouble(); // random color generator _color = Color.fromRGBO( random.nextInt(300), random.nextInt(300), random.nextInt(300), 1, ); // random radius generator _borderRadius = BorderRadius.circular(random.nextInt(100).toDouble()); }); }, ), ), ); }}",
"e": 29497,
"s": 27676,
"text": null
},
{
"code": null,
"e": 29508,
"s": 29500,
"text": "Output:"
},
{
"code": null,
"e": 29570,
"s": 29510,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 29585,
"s": 29572,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 29600,
"s": 29585,
"text": "varshagumber28"
},
{
"code": null,
"e": 29608,
"s": 29600,
"text": "android"
},
{
"code": null,
"e": 29616,
"s": 29608,
"text": "Flutter"
},
{
"code": null,
"e": 29632,
"s": 29616,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 29637,
"s": 29632,
"text": "Dart"
},
{
"code": null,
"e": 29645,
"s": 29637,
"text": "Flutter"
},
{
"code": null,
"e": 29743,
"s": 29645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29782,
"s": 29743,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29808,
"s": 29782,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 29834,
"s": 29808,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 29857,
"s": 29834,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 29885,
"s": 29857,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 29924,
"s": 29885,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29941,
"s": 29924,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 29967,
"s": 29941,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 29990,
"s": 29967,
"text": "Flutter - Stack Widget"
}
] |
Predicting Real GDP Growth. How well do economic leading indicators... | by Joohi Rana | Towards Data Science | If you follow financial news, you may have heard words like “consumer sentiment” or “ISM new orders” being thrown around. These are data points or economic indicators that economists use to gauge where the economy is heading in the future. But how well do they predict economic growth? To find out, I developed a prediction model in Python to see the predictive powers of these economic metrics.
Before, we get to the model, let’s first establish a firm understanding of business cycles. Four phases of the cycle are peak, contraction, trough, and expansion. The peak and trough are turning points in the cycle. During contraction, economic activity or GDP is declining, which may lead to a recession or depression. During expansion, economic activity is accelerating. Peak is when the economy is over-heating, with high inflation and GDP slowing down.
US GDP or gross domestic product is the value of final goods and services produced in US in a certain time frame. It is the sum of consumer spending, domestic investments, government spending, and the difference in export and imports.
GDP = C + I+G+(X-M)
Economists and financial analysts use leading indicators to help understand the future state of the economy. It helps pinpoint where we will be on the business cycle curve. Below are the leading indicators I used in my model:
Average Weekly Initial Claims for unemployment insurance: good measure of initial layoffs and rehiring
Manufacturing Average Hours Worked (Quarterly % Change): businesses are more likely to cut overtime before layoffs and increase overtime before rehiring; therefore, this metric moves first before the business cycle turns
ISM Manufacturers’ New Orders: Nondefense Capital Goods Excluding Aircraft: Monthly new orders offer first signal of movement in industrial sector and good proxy for business expectations
Building permits for private housing units: foretells new construction activity
S&P 500 Index: provides early indications of movement in the economic business cycles
Interest Rate Spread between 10 year Treasury yield and federal funds rate: wider spreads anticipate economic upswings and narrower spreads anticipate downturns
Average Consumer Expectations/Confidence: if consumers are confident, spending will increase. Consumption makes of 66% of the U.S economy
All data points are quarterly aggregates retrieved from St. Louis FRED website. The data is from 1947 to 2020 Q1 with 293 records.
New variables created:
Quarter: created from DateS&P 500_pct: Replaced actual values with percent change of S&P 500, because over time S&P 500 values increase
Quarter: created from Date
S&P 500_pct: Replaced actual values with percent change of S&P 500, because over time S&P 500 values increase
The target variable is the annualized real GDP growth. I calculated this variable using the change in quarterly real GDP as follows: ([Q2/Q1 * 4 ]-1). Real GDP is used because it is adjusted to inflation.
Few of the variables had nulls values because I could not find data dating back to 1947 as I did for the GDP data. To fill up the missing data, I used the k-nearest neighbor algorithm.
from sklearn.impute import KNNImputerimputer = KNNImputer(n_neighbors=2)df_filled = imputer.fit_transform(df2)dataframe=pd.DataFrame(df_filled, columns = cols)
I decided to use an Elastic Net Regression model because it does a better job dealing with highly correlated independent variables. I split the data 30/70 (test/train). Then, I found the best alpha for the model using ElasticNetCV which is a cross validation class.
#Separate Features and targetX_Target = dataframe3[‘GDP_Change’] # the feature_df= dataframe3.loc[:, dataframe3.columns != ‘GDP_Change’]#Split the dataX_train, X_test, y_train, y_test = train_test_split(feature_df, X_Target, test_size=0.3, random_state=0)alphas = [0.0001, 0.001, 0.01, 0.1, 0.3, 0.5, 0.7, 1]elastic_cv=ElasticNetCV(alphas=alphas, cv=5)model = elastic_cv.fit(X_train, y_train)ypred = model.predict(X_test)score = model.score(X_test, y_test)mse = mean_squared_error(y_test, ypred)print("R2:{0:.4f}, MSE:{1:.4f}, RMSE:{2:.4f}" .format(score, mse, np.sqrt(mse)))
Output:
R2:0.4323, MSE:0.0008, RMSE:0.0275
I then visualized the model’s predicted values with the actual values
x_ax = range(len(X_test))plt.scatter(x_ax, y_test, s=5, color=”blue”, label=”original”)plt.plot(x_ax, ypred, lw=0.8, color=”red”, label=”predicted”)plt.legend()plt.show()
Mean squared error was quite low but root mean squared error was larger because it penalizes the larger errors. These large errors may be due to the volatility in the market resulting from unforeseen events. The R-squared of 0.4323 reveals that the leading indicators only explain 43% of variance in GDP growth. Thus, using only the leading indicators is not enough to forecast GDP growth. To have a better idea of where the economy is heading, we need to look at more metrics such coincident indicators.
Coincident indicators measure the current state of the economy. So, by knowing where we are on the business cycle, we can foretell where we are heading.
I added the following metrics:
Change in monthly unemployment (quarterly average)
Personal Consumption Expenditures Excluding Food and Energy (Chain-Type Price Index), price change from a year ago
Monthly supply of house: ratio of houses for sale to houses sold
Mortgage Debt Service Payments as a Percent of Disposable Personal Income,price change from a year ago
The new Elastic Net Regression model had slightly lower errors and a increased in R-squared. This model explains about 65% of variability in GDP growth. Using both coincident and leading indicators paints a better picture of where we’re headed.
R2:0.6477, MSE:0.0006, RMSE:0.0235
The model’s strong predictors were ISM New Orders, consumer confidence, and unemployment rate changes.
The ISM New order Index is strongly correlated to GDP growth with a correlation of .60. Thus, as new manufacturing orders increases, it contributes to GDP growth. Second strong predictor is consumer confidence (0.34). A large part of the GDP calculation is spending. As consumers are more confident in the state of the economy, they are likely to spend more, increasing GDP. There is also a strong negative correlation between changes in unemployment and GDP growth (-0.65).
From the above correlation matrix, you can see that the independent variables are correlated as well (that is why I used the Elastic Net Regression model). For example, there is a strong negative correlation between consumer confidence and weekly unemployment claims, which makes sense because if one does not have a job to pay the bills, consumers will have less confidence about the economy.
The graph below illustrates the trend between the top two predictors (ISM New Orders and consumer sentiment). For example, in the fourth quarter of 2008, the economy contracted about 8% with new orders and consumer confident dropping as well. In the first quarter of 2020, we experienced another economic contraction (-4.8%). During this time due to growing concerns about the coronavirus, both new order index and consumer confident dropped about 10%.
Using latest data from April to predict GDP growth in quarter 2 of 2020, my model projects a sharp decline of 24.2%. At first, this was eye-dropping. So I compared my results to what other leading organizations projected.
US Congressional Budget Office (CBO) estimates a 12% decline in GDP for the next quarter and an annualized decline of 40%1.
The Federal Reserve Bank of Atlanta estimates a whopping 40% decline in GDP. Blue Chip consensus projections range from -6% to 40%2.
The Conference Board forecasts the US economy to contract by 45% next quarter3. According to Pacific Investment Management Co (PIMCO), one of the world’s largest investment firms, GDP will contract by 30%4. My shocking projection of 24% contraction is actually in range with many of the other’s outlook.
Two consecutive negative GDP growths is a recession. Regardless of the actual GDP growth number, the consensus agrees that second quarter of 2020 will experience a large drop. This indicates that we will be in a recession since first quarter of 2020 contracted as well.
[1]: Phill Swagel. (April 24 2020). CBO’s Current Projections of Output. https://www.cbo.gov/publication/56335
[2]: Federal Reserve bank of Atlanta. GDPNow. www.frbatlanta.org
[3]: The Conference Board. Economic Forecast for the US Economy. https://www.conference-board.org/publications/Economic-Forecast-US
[4]: Kate Duguid (April 8 2020). U.S. GDP will contract 30% in second quarter, 5% in 2020: PIMCO. https://www.reuters.com/article/us-usa-gdp-pimco/us-gdp-will-contract-30-in-second-quarter-5-in-2020-pimco-idUSKCN21Q2VL | [
{
"code": null,
"e": 568,
"s": 172,
"text": "If you follow financial news, you may have heard words like “consumer sentiment” or “ISM new orders” being thrown around. These are data points or economic indicators that economists use to gauge where the economy is heading in the future. But how well do they predict economic growth? To find out, I developed a prediction model in Python to see the predictive powers of these economic metrics."
},
{
"code": null,
"e": 1025,
"s": 568,
"text": "Before, we get to the model, let’s first establish a firm understanding of business cycles. Four phases of the cycle are peak, contraction, trough, and expansion. The peak and trough are turning points in the cycle. During contraction, economic activity or GDP is declining, which may lead to a recession or depression. During expansion, economic activity is accelerating. Peak is when the economy is over-heating, with high inflation and GDP slowing down."
},
{
"code": null,
"e": 1260,
"s": 1025,
"text": "US GDP or gross domestic product is the value of final goods and services produced in US in a certain time frame. It is the sum of consumer spending, domestic investments, government spending, and the difference in export and imports."
},
{
"code": null,
"e": 1280,
"s": 1260,
"text": "GDP = C + I+G+(X-M)"
},
{
"code": null,
"e": 1506,
"s": 1280,
"text": "Economists and financial analysts use leading indicators to help understand the future state of the economy. It helps pinpoint where we will be on the business cycle curve. Below are the leading indicators I used in my model:"
},
{
"code": null,
"e": 1609,
"s": 1506,
"text": "Average Weekly Initial Claims for unemployment insurance: good measure of initial layoffs and rehiring"
},
{
"code": null,
"e": 1830,
"s": 1609,
"text": "Manufacturing Average Hours Worked (Quarterly % Change): businesses are more likely to cut overtime before layoffs and increase overtime before rehiring; therefore, this metric moves first before the business cycle turns"
},
{
"code": null,
"e": 2018,
"s": 1830,
"text": "ISM Manufacturers’ New Orders: Nondefense Capital Goods Excluding Aircraft: Monthly new orders offer first signal of movement in industrial sector and good proxy for business expectations"
},
{
"code": null,
"e": 2098,
"s": 2018,
"text": "Building permits for private housing units: foretells new construction activity"
},
{
"code": null,
"e": 2184,
"s": 2098,
"text": "S&P 500 Index: provides early indications of movement in the economic business cycles"
},
{
"code": null,
"e": 2345,
"s": 2184,
"text": "Interest Rate Spread between 10 year Treasury yield and federal funds rate: wider spreads anticipate economic upswings and narrower spreads anticipate downturns"
},
{
"code": null,
"e": 2483,
"s": 2345,
"text": "Average Consumer Expectations/Confidence: if consumers are confident, spending will increase. Consumption makes of 66% of the U.S economy"
},
{
"code": null,
"e": 2614,
"s": 2483,
"text": "All data points are quarterly aggregates retrieved from St. Louis FRED website. The data is from 1947 to 2020 Q1 with 293 records."
},
{
"code": null,
"e": 2637,
"s": 2614,
"text": "New variables created:"
},
{
"code": null,
"e": 2773,
"s": 2637,
"text": "Quarter: created from DateS&P 500_pct: Replaced actual values with percent change of S&P 500, because over time S&P 500 values increase"
},
{
"code": null,
"e": 2800,
"s": 2773,
"text": "Quarter: created from Date"
},
{
"code": null,
"e": 2910,
"s": 2800,
"text": "S&P 500_pct: Replaced actual values with percent change of S&P 500, because over time S&P 500 values increase"
},
{
"code": null,
"e": 3115,
"s": 2910,
"text": "The target variable is the annualized real GDP growth. I calculated this variable using the change in quarterly real GDP as follows: ([Q2/Q1 * 4 ]-1). Real GDP is used because it is adjusted to inflation."
},
{
"code": null,
"e": 3300,
"s": 3115,
"text": "Few of the variables had nulls values because I could not find data dating back to 1947 as I did for the GDP data. To fill up the missing data, I used the k-nearest neighbor algorithm."
},
{
"code": null,
"e": 3460,
"s": 3300,
"text": "from sklearn.impute import KNNImputerimputer = KNNImputer(n_neighbors=2)df_filled = imputer.fit_transform(df2)dataframe=pd.DataFrame(df_filled, columns = cols)"
},
{
"code": null,
"e": 3726,
"s": 3460,
"text": "I decided to use an Elastic Net Regression model because it does a better job dealing with highly correlated independent variables. I split the data 30/70 (test/train). Then, I found the best alpha for the model using ElasticNetCV which is a cross validation class."
},
{
"code": null,
"e": 4307,
"s": 3726,
"text": "#Separate Features and targetX_Target = dataframe3[‘GDP_Change’] # the feature_df= dataframe3.loc[:, dataframe3.columns != ‘GDP_Change’]#Split the dataX_train, X_test, y_train, y_test = train_test_split(feature_df, X_Target, test_size=0.3, random_state=0)alphas = [0.0001, 0.001, 0.01, 0.1, 0.3, 0.5, 0.7, 1]elastic_cv=ElasticNetCV(alphas=alphas, cv=5)model = elastic_cv.fit(X_train, y_train)ypred = model.predict(X_test)score = model.score(X_test, y_test)mse = mean_squared_error(y_test, ypred)print(\"R2:{0:.4f}, MSE:{1:.4f}, RMSE:{2:.4f}\" .format(score, mse, np.sqrt(mse)))"
},
{
"code": null,
"e": 4315,
"s": 4307,
"text": "Output:"
},
{
"code": null,
"e": 4350,
"s": 4315,
"text": "R2:0.4323, MSE:0.0008, RMSE:0.0275"
},
{
"code": null,
"e": 4420,
"s": 4350,
"text": "I then visualized the model’s predicted values with the actual values"
},
{
"code": null,
"e": 4591,
"s": 4420,
"text": "x_ax = range(len(X_test))plt.scatter(x_ax, y_test, s=5, color=”blue”, label=”original”)plt.plot(x_ax, ypred, lw=0.8, color=”red”, label=”predicted”)plt.legend()plt.show()"
},
{
"code": null,
"e": 5096,
"s": 4591,
"text": "Mean squared error was quite low but root mean squared error was larger because it penalizes the larger errors. These large errors may be due to the volatility in the market resulting from unforeseen events. The R-squared of 0.4323 reveals that the leading indicators only explain 43% of variance in GDP growth. Thus, using only the leading indicators is not enough to forecast GDP growth. To have a better idea of where the economy is heading, we need to look at more metrics such coincident indicators."
},
{
"code": null,
"e": 5249,
"s": 5096,
"text": "Coincident indicators measure the current state of the economy. So, by knowing where we are on the business cycle, we can foretell where we are heading."
},
{
"code": null,
"e": 5280,
"s": 5249,
"text": "I added the following metrics:"
},
{
"code": null,
"e": 5331,
"s": 5280,
"text": "Change in monthly unemployment (quarterly average)"
},
{
"code": null,
"e": 5446,
"s": 5331,
"text": "Personal Consumption Expenditures Excluding Food and Energy (Chain-Type Price Index), price change from a year ago"
},
{
"code": null,
"e": 5511,
"s": 5446,
"text": "Monthly supply of house: ratio of houses for sale to houses sold"
},
{
"code": null,
"e": 5614,
"s": 5511,
"text": "Mortgage Debt Service Payments as a Percent of Disposable Personal Income,price change from a year ago"
},
{
"code": null,
"e": 5859,
"s": 5614,
"text": "The new Elastic Net Regression model had slightly lower errors and a increased in R-squared. This model explains about 65% of variability in GDP growth. Using both coincident and leading indicators paints a better picture of where we’re headed."
},
{
"code": null,
"e": 5894,
"s": 5859,
"text": "R2:0.6477, MSE:0.0006, RMSE:0.0235"
},
{
"code": null,
"e": 5997,
"s": 5894,
"text": "The model’s strong predictors were ISM New Orders, consumer confidence, and unemployment rate changes."
},
{
"code": null,
"e": 6472,
"s": 5997,
"text": "The ISM New order Index is strongly correlated to GDP growth with a correlation of .60. Thus, as new manufacturing orders increases, it contributes to GDP growth. Second strong predictor is consumer confidence (0.34). A large part of the GDP calculation is spending. As consumers are more confident in the state of the economy, they are likely to spend more, increasing GDP. There is also a strong negative correlation between changes in unemployment and GDP growth (-0.65)."
},
{
"code": null,
"e": 6866,
"s": 6472,
"text": "From the above correlation matrix, you can see that the independent variables are correlated as well (that is why I used the Elastic Net Regression model). For example, there is a strong negative correlation between consumer confidence and weekly unemployment claims, which makes sense because if one does not have a job to pay the bills, consumers will have less confidence about the economy."
},
{
"code": null,
"e": 7319,
"s": 6866,
"text": "The graph below illustrates the trend between the top two predictors (ISM New Orders and consumer sentiment). For example, in the fourth quarter of 2008, the economy contracted about 8% with new orders and consumer confident dropping as well. In the first quarter of 2020, we experienced another economic contraction (-4.8%). During this time due to growing concerns about the coronavirus, both new order index and consumer confident dropped about 10%."
},
{
"code": null,
"e": 7541,
"s": 7319,
"text": "Using latest data from April to predict GDP growth in quarter 2 of 2020, my model projects a sharp decline of 24.2%. At first, this was eye-dropping. So I compared my results to what other leading organizations projected."
},
{
"code": null,
"e": 7665,
"s": 7541,
"text": "US Congressional Budget Office (CBO) estimates a 12% decline in GDP for the next quarter and an annualized decline of 40%1."
},
{
"code": null,
"e": 7798,
"s": 7665,
"text": "The Federal Reserve Bank of Atlanta estimates a whopping 40% decline in GDP. Blue Chip consensus projections range from -6% to 40%2."
},
{
"code": null,
"e": 8102,
"s": 7798,
"text": "The Conference Board forecasts the US economy to contract by 45% next quarter3. According to Pacific Investment Management Co (PIMCO), one of the world’s largest investment firms, GDP will contract by 30%4. My shocking projection of 24% contraction is actually in range with many of the other’s outlook."
},
{
"code": null,
"e": 8372,
"s": 8102,
"text": "Two consecutive negative GDP growths is a recession. Regardless of the actual GDP growth number, the consensus agrees that second quarter of 2020 will experience a large drop. This indicates that we will be in a recession since first quarter of 2020 contracted as well."
},
{
"code": null,
"e": 8483,
"s": 8372,
"text": "[1]: Phill Swagel. (April 24 2020). CBO’s Current Projections of Output. https://www.cbo.gov/publication/56335"
},
{
"code": null,
"e": 8548,
"s": 8483,
"text": "[2]: Federal Reserve bank of Atlanta. GDPNow. www.frbatlanta.org"
},
{
"code": null,
"e": 8680,
"s": 8548,
"text": "[3]: The Conference Board. Economic Forecast for the US Economy. https://www.conference-board.org/publications/Economic-Forecast-US"
}
] |
A quick intro to Intel’s OpenVINO toolkit for faster deep learning inference | by Abhishek Dubey | Towards Data Science | Deep learning models are becoming heavier day by day, and apart from training them faster, a lot of focus is also around faster inference for real time use-cases on IOT/ Edge devices. So around 2 years back Intel released OpenVINO toolkit for optimizing inference of Deep Learning models on Intel’s hardware.
To know all basics around OpenVINO, Ihave divided this post into 3 sections and depending on your interest you can switch to any one of the below:
What is OpenVINOWhy/ When OpenVINOHow to Build & Run a toy NN on OpenVINO
What is OpenVINO
Why/ When OpenVINO
How to Build & Run a toy NN on OpenVINO
Intel’s Open Visual Inference and Neural network Optimization (OpenVINO) toolkit enables the vision application (or any other DNN) to run faster on Intel’s Processors/ Hardware.
The OpenVINOTM toolkit is a comprehensive toolkit for quickly developing applications and solutions that emulate human vision. Based on Convolutional Neural Networks (CNNs), the toolkit extends CV workloads across Intel® hardware, maximizing performance.- https://docs.openvinotoolkit.org/
To put it straight, an attempt by Intel to sell their underlying processors (CPUs, iGPUs, VPUs, Gaussian & Neural Accelerators, and FPGAs) for making your AI (vision) Applications run faster.
This is not a toolkit for faster training of your Deep Learning task, but for faster inference of your already trained Deep Neural model.
The tool main components of OpenVINO toolkit are
Model OptimizerInference Engine
Model Optimizer
Inference Engine
For complete details on the toolkit, check this.
The task of the Model optimizer (a .py file for individual frameworks) is to take a already trained DL model and adjust it for optimal execution for the target device. The output of Model Optimizer is the Intermediate Representation (IR) of your DL Model.
The IR is set of 2 file which describes the Optimized version of your DL model
*.xml - Describes the network topology*.bin - Contains the weights (& biases) binary data
*.xml - Describes the network topology
*.bin - Contains the weights (& biases) binary data
The output of Model Optimizer (IR files), is what we must pass to Inference Engine, which runs it on your hardware.
So to make best use of your Intel Hardware for your ML (Edge, cloud ...) applications running in production, all you need to do is, generate the IR files of your DL model and run it on the Inference Engine rather than directly running it over the hardware.
As mentioned above a lot of Edge/ Cloud applications are already using more advanced Intel hardware/ processors/ architectures.
So one of the most important reason why one would want to shift to OpenVINO is to make best use of the underlying Intel Hardware.
Apart from this I have seen a lot of Application Development teams shifting to OpenVINO just for Intel’s already optimized Pretrained models for their Edge Applications
software.intel.com
github.com
So all you are required to do is, download the IR files for one of the pretrained model and just use it with Inference engine for your end application.
The main disadvantage for such pretrained models is when required, re-training these models with your costume data is not always easy, as not everything is well documented around re-training/ fine-tunning for all provided models.
And if you are thinking to use one of the TF model Zoo (or similar for other DL frameworks) or building/ train your own custom Tensorflow (or PyTorch etc..) models and expect that it would be easy (or even possible every time) to convert it to the required IR files, that would not be the case always.
Check the Open Issues/ bugs like [1], [2].
So it becomes really important while deciding to port any of your applications to OpenVINO to do a quick check of below points:
If you start with the IR files, you also have proper understanding/ documentation for re-training the model behind the provided IR filesIf you are building your own DNN model, you can convert your model architecture (though not trained yet) to IR using Model Optimizer
If you start with the IR files, you also have proper understanding/ documentation for re-training the model behind the provided IR files
If you are building your own DNN model, you can convert your model architecture (though not trained yet) to IR using Model Optimizer
As you long as you are good with both the points above, you should be fine choosing OpenVINO for your DL Application, but if not, you might want to reassess your decision.
The best way to understand how OpenVINO works is to build, train & Infer your own toy Deep Learning model onto the same. Remember OpenVINO would come in the picture only after we have saved our DL model.
So lets build a toy Linear regression problem we want to solve, decide an DL framework we want to try, I am picking PyTorch for this post but feel free to get the TensorFlow version of the same.
Let’s generate sample data for the same
Let’s build a quick neural network for the solving the above Regression problem.
Let’s train our neural network model
Check the prediction outputs of your PyTorch model before saving and using it with OpenVINO
predicted = model.forward(torch.torch.FloatTensor(normed_test_data.values)).data.numpy()print(model.state_dict())
Now let’s first save your pyTorch model so that we can get IR files for the model using model optimizer later.
Now this is where we would need OpenVINO
So before we go to next step, we would need to install the OpenVINO toolkit.
software.intel.com
Once you have installed the toolKit, let’s convert the saved PyTorch model to the IR files
Now once we have the IR files, the final step is to RUN our NN model on OpenVINO Inference Engine
Note: Though the demo below was run on my laptop with Intel CPU, you could update the device as per your target hardware.
If you need to look at the sample code, check the repo below: | [
{
"code": null,
"e": 481,
"s": 172,
"text": "Deep learning models are becoming heavier day by day, and apart from training them faster, a lot of focus is also around faster inference for real time use-cases on IOT/ Edge devices. So around 2 years back Intel released OpenVINO toolkit for optimizing inference of Deep Learning models on Intel’s hardware."
},
{
"code": null,
"e": 628,
"s": 481,
"text": "To know all basics around OpenVINO, Ihave divided this post into 3 sections and depending on your interest you can switch to any one of the below:"
},
{
"code": null,
"e": 702,
"s": 628,
"text": "What is OpenVINOWhy/ When OpenVINOHow to Build & Run a toy NN on OpenVINO"
},
{
"code": null,
"e": 719,
"s": 702,
"text": "What is OpenVINO"
},
{
"code": null,
"e": 738,
"s": 719,
"text": "Why/ When OpenVINO"
},
{
"code": null,
"e": 778,
"s": 738,
"text": "How to Build & Run a toy NN on OpenVINO"
},
{
"code": null,
"e": 956,
"s": 778,
"text": "Intel’s Open Visual Inference and Neural network Optimization (OpenVINO) toolkit enables the vision application (or any other DNN) to run faster on Intel’s Processors/ Hardware."
},
{
"code": null,
"e": 1246,
"s": 956,
"text": "The OpenVINOTM toolkit is a comprehensive toolkit for quickly developing applications and solutions that emulate human vision. Based on Convolutional Neural Networks (CNNs), the toolkit extends CV workloads across Intel® hardware, maximizing performance.- https://docs.openvinotoolkit.org/"
},
{
"code": null,
"e": 1438,
"s": 1246,
"text": "To put it straight, an attempt by Intel to sell their underlying processors (CPUs, iGPUs, VPUs, Gaussian & Neural Accelerators, and FPGAs) for making your AI (vision) Applications run faster."
},
{
"code": null,
"e": 1576,
"s": 1438,
"text": "This is not a toolkit for faster training of your Deep Learning task, but for faster inference of your already trained Deep Neural model."
},
{
"code": null,
"e": 1625,
"s": 1576,
"text": "The tool main components of OpenVINO toolkit are"
},
{
"code": null,
"e": 1657,
"s": 1625,
"text": "Model OptimizerInference Engine"
},
{
"code": null,
"e": 1673,
"s": 1657,
"text": "Model Optimizer"
},
{
"code": null,
"e": 1690,
"s": 1673,
"text": "Inference Engine"
},
{
"code": null,
"e": 1739,
"s": 1690,
"text": "For complete details on the toolkit, check this."
},
{
"code": null,
"e": 1995,
"s": 1739,
"text": "The task of the Model optimizer (a .py file for individual frameworks) is to take a already trained DL model and adjust it for optimal execution for the target device. The output of Model Optimizer is the Intermediate Representation (IR) of your DL Model."
},
{
"code": null,
"e": 2074,
"s": 1995,
"text": "The IR is set of 2 file which describes the Optimized version of your DL model"
},
{
"code": null,
"e": 2164,
"s": 2074,
"text": "*.xml - Describes the network topology*.bin - Contains the weights (& biases) binary data"
},
{
"code": null,
"e": 2203,
"s": 2164,
"text": "*.xml - Describes the network topology"
},
{
"code": null,
"e": 2255,
"s": 2203,
"text": "*.bin - Contains the weights (& biases) binary data"
},
{
"code": null,
"e": 2371,
"s": 2255,
"text": "The output of Model Optimizer (IR files), is what we must pass to Inference Engine, which runs it on your hardware."
},
{
"code": null,
"e": 2628,
"s": 2371,
"text": "So to make best use of your Intel Hardware for your ML (Edge, cloud ...) applications running in production, all you need to do is, generate the IR files of your DL model and run it on the Inference Engine rather than directly running it over the hardware."
},
{
"code": null,
"e": 2756,
"s": 2628,
"text": "As mentioned above a lot of Edge/ Cloud applications are already using more advanced Intel hardware/ processors/ architectures."
},
{
"code": null,
"e": 2886,
"s": 2756,
"text": "So one of the most important reason why one would want to shift to OpenVINO is to make best use of the underlying Intel Hardware."
},
{
"code": null,
"e": 3055,
"s": 2886,
"text": "Apart from this I have seen a lot of Application Development teams shifting to OpenVINO just for Intel’s already optimized Pretrained models for their Edge Applications"
},
{
"code": null,
"e": 3074,
"s": 3055,
"text": "software.intel.com"
},
{
"code": null,
"e": 3085,
"s": 3074,
"text": "github.com"
},
{
"code": null,
"e": 3237,
"s": 3085,
"text": "So all you are required to do is, download the IR files for one of the pretrained model and just use it with Inference engine for your end application."
},
{
"code": null,
"e": 3467,
"s": 3237,
"text": "The main disadvantage for such pretrained models is when required, re-training these models with your costume data is not always easy, as not everything is well documented around re-training/ fine-tunning for all provided models."
},
{
"code": null,
"e": 3769,
"s": 3467,
"text": "And if you are thinking to use one of the TF model Zoo (or similar for other DL frameworks) or building/ train your own custom Tensorflow (or PyTorch etc..) models and expect that it would be easy (or even possible every time) to convert it to the required IR files, that would not be the case always."
},
{
"code": null,
"e": 3812,
"s": 3769,
"text": "Check the Open Issues/ bugs like [1], [2]."
},
{
"code": null,
"e": 3940,
"s": 3812,
"text": "So it becomes really important while deciding to port any of your applications to OpenVINO to do a quick check of below points:"
},
{
"code": null,
"e": 4209,
"s": 3940,
"text": "If you start with the IR files, you also have proper understanding/ documentation for re-training the model behind the provided IR filesIf you are building your own DNN model, you can convert your model architecture (though not trained yet) to IR using Model Optimizer"
},
{
"code": null,
"e": 4346,
"s": 4209,
"text": "If you start with the IR files, you also have proper understanding/ documentation for re-training the model behind the provided IR files"
},
{
"code": null,
"e": 4479,
"s": 4346,
"text": "If you are building your own DNN model, you can convert your model architecture (though not trained yet) to IR using Model Optimizer"
},
{
"code": null,
"e": 4651,
"s": 4479,
"text": "As you long as you are good with both the points above, you should be fine choosing OpenVINO for your DL Application, but if not, you might want to reassess your decision."
},
{
"code": null,
"e": 4855,
"s": 4651,
"text": "The best way to understand how OpenVINO works is to build, train & Infer your own toy Deep Learning model onto the same. Remember OpenVINO would come in the picture only after we have saved our DL model."
},
{
"code": null,
"e": 5050,
"s": 4855,
"text": "So lets build a toy Linear regression problem we want to solve, decide an DL framework we want to try, I am picking PyTorch for this post but feel free to get the TensorFlow version of the same."
},
{
"code": null,
"e": 5090,
"s": 5050,
"text": "Let’s generate sample data for the same"
},
{
"code": null,
"e": 5171,
"s": 5090,
"text": "Let’s build a quick neural network for the solving the above Regression problem."
},
{
"code": null,
"e": 5208,
"s": 5171,
"text": "Let’s train our neural network model"
},
{
"code": null,
"e": 5300,
"s": 5208,
"text": "Check the prediction outputs of your PyTorch model before saving and using it with OpenVINO"
},
{
"code": null,
"e": 5414,
"s": 5300,
"text": "predicted = model.forward(torch.torch.FloatTensor(normed_test_data.values)).data.numpy()print(model.state_dict())"
},
{
"code": null,
"e": 5525,
"s": 5414,
"text": "Now let’s first save your pyTorch model so that we can get IR files for the model using model optimizer later."
},
{
"code": null,
"e": 5566,
"s": 5525,
"text": "Now this is where we would need OpenVINO"
},
{
"code": null,
"e": 5643,
"s": 5566,
"text": "So before we go to next step, we would need to install the OpenVINO toolkit."
},
{
"code": null,
"e": 5662,
"s": 5643,
"text": "software.intel.com"
},
{
"code": null,
"e": 5753,
"s": 5662,
"text": "Once you have installed the toolKit, let’s convert the saved PyTorch model to the IR files"
},
{
"code": null,
"e": 5851,
"s": 5753,
"text": "Now once we have the IR files, the final step is to RUN our NN model on OpenVINO Inference Engine"
},
{
"code": null,
"e": 5973,
"s": 5851,
"text": "Note: Though the demo below was run on my laptop with Intel CPU, you could update the device as per your target hardware."
}
] |
What does input() function do in python? | The function input() presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user. In Python 2.x, it returns the data input by the user in a format that is interpreted by python. For example, if the user inputs "Hello", it is stored as string while if a user enters 5, it is interpreted as an int. In Python 3.x, it returns the data input by the user in string format.
name = raw_input("What is your name? ")
print "Hello, %s." % name | [
{
"code": null,
"e": 1465,
"s": 1062,
"text": "The function input() presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user. In Python 2.x, it returns the data input by the user in a format that is interpreted by python. For example, if the user inputs \"Hello\", it is stored as string while if a user enters 5, it is interpreted as an int. In Python 3.x, it returns the data input by the user in string format."
},
{
"code": null,
"e": 1531,
"s": 1465,
"text": "name = raw_input(\"What is your name? \")\nprint \"Hello, %s.\" % name"
}
] |
Accessing element at a specific index in Julia - getindex() Method - GeeksforGeeks | 07 Sep, 2021
The getindex() is an inbuilt function in julia which is used to construct array of the specified type. This function is also used to get the element of the array at a specific index.
Syntax: getindex(type, elements...])Parameters:
type: Specified type.
elements: Specified list of elements.
Returns: It returns the constructed array of the specified type and also the element of the array at a specific index.
Example 1:
Python
# Julia program to illustrate# the use of Array getindex() method # Constructing array of the different typesprintln(getindex(Int8, 1, 2, 3))println(getindex(Int16, 5, 10, 15, 20))println(getindex(Int32, 2, 4, 6, 8, 10))
Output:
Example 2:
Python
# Julia program to illustrate# the use of Array getindex() method # Getting an element of the 2D array# A at some specific indexs of (2, 3)# and (2, 2)A = [1 2 3; 4 5 6]println(getindex(A, 2, 2))println(getindex(A, 2, 3))
Output:
Example 3:
Python
# Julia program to illustrate# the use of Array getindex() method # Getting an element of the 3D array# A at some specific indexs of (1, 2, 2)# and (1, :, 2)A = cat([1 2; 3 4], ["hello" "Geeks"; "Welcome" "GFG"], [5 6; 7 8], dims = 3)getindex(A, 1, 2, 2)getindex(A, 1, :, 2)
Output:
rajeev0719singh
kk9826225
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Get number of elements of array in Julia - length() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Getting the maximum value from a list in Julia - max() Method
Find maximum element along with its index in Julia - findmax() Method
Exception handling in Julia
Getting the absolute value of a number in Julia - abs() Method
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Working with Date and Time in Julia | [
{
"code": null,
"e": 24544,
"s": 24516,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 24728,
"s": 24544,
"text": "The getindex() is an inbuilt function in julia which is used to construct array of the specified type. This function is also used to get the element of the array at a specific index. "
},
{
"code": null,
"e": 24778,
"s": 24728,
"text": "Syntax: getindex(type, elements...])Parameters: "
},
{
"code": null,
"e": 24800,
"s": 24778,
"text": "type: Specified type."
},
{
"code": null,
"e": 24838,
"s": 24800,
"text": "elements: Specified list of elements."
},
{
"code": null,
"e": 24959,
"s": 24838,
"text": "Returns: It returns the constructed array of the specified type and also the element of the array at a specific index. "
},
{
"code": null,
"e": 24972,
"s": 24959,
"text": "Example 1: "
},
{
"code": null,
"e": 24979,
"s": 24972,
"text": "Python"
},
{
"code": "# Julia program to illustrate# the use of Array getindex() method # Constructing array of the different typesprintln(getindex(Int8, 1, 2, 3))println(getindex(Int16, 5, 10, 15, 20))println(getindex(Int32, 2, 4, 6, 8, 10))",
"e": 25200,
"s": 24979,
"text": null
},
{
"code": null,
"e": 25210,
"s": 25200,
"text": "Output: "
},
{
"code": null,
"e": 25223,
"s": 25210,
"text": "Example 2: "
},
{
"code": null,
"e": 25230,
"s": 25223,
"text": "Python"
},
{
"code": "# Julia program to illustrate# the use of Array getindex() method # Getting an element of the 2D array# A at some specific indexs of (2, 3)# and (2, 2)A = [1 2 3; 4 5 6]println(getindex(A, 2, 2))println(getindex(A, 2, 3))",
"e": 25452,
"s": 25230,
"text": null
},
{
"code": null,
"e": 25462,
"s": 25452,
"text": "Output: "
},
{
"code": null,
"e": 25475,
"s": 25462,
"text": "Example 3: "
},
{
"code": null,
"e": 25482,
"s": 25475,
"text": "Python"
},
{
"code": "# Julia program to illustrate# the use of Array getindex() method # Getting an element of the 3D array# A at some specific indexs of (1, 2, 2)# and (1, :, 2)A = cat([1 2; 3 4], [\"hello\" \"Geeks\"; \"Welcome\" \"GFG\"], [5 6; 7 8], dims = 3)getindex(A, 1, 2, 2)getindex(A, 1, :, 2)",
"e": 25774,
"s": 25482,
"text": null
},
{
"code": null,
"e": 25784,
"s": 25774,
"text": "Output: "
},
{
"code": null,
"e": 25802,
"s": 25786,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 25812,
"s": 25802,
"text": "kk9826225"
},
{
"code": null,
"e": 25818,
"s": 25812,
"text": "Julia"
},
{
"code": null,
"e": 25916,
"s": 25818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25964,
"s": 25916,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 26034,
"s": 25964,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 26093,
"s": 26034,
"text": "Get number of elements of array in Julia - length() Method"
},
{
"code": null,
"e": 26166,
"s": 26093,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 26228,
"s": 26166,
"text": "Getting the maximum value from a list in Julia - max() Method"
},
{
"code": null,
"e": 26298,
"s": 26228,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 26326,
"s": 26298,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 26389,
"s": 26326,
"text": "Getting the absolute value of a number in Julia - abs() Method"
},
{
"code": null,
"e": 26470,
"s": 26389,
"text": "Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods"
}
] |
K-Means Clustering: Unsupervised Learning for Recommender Systems | by Luciano Strika | Towards Data Science | Unsupervised Learning has been called the closest thing we have to “actual” Artificial Intelligence, in the sense of General AI, with K-Means Clustering one of its simplest, but most powerful applications.
I am not here to discuss whether those claims are true or not, as I am not an expert nor a philosopher. I will however state, that I am often amazed by how well unsupervised learning techniques, even the most rudimentary, capture patterns in the data that I would expect only people to find.
Today we’ll apply unsupervised learning on a Dataset I gathered myself. It’s a database of professional Magic: The Gathering decks that I crawled from mtgtop8.com, an awesome website if you’re into Magic: the Gathering.
I scraped the MtgTop8 data from a few years of tournaments, and they’re all available to be consumed in this GitHub repository.
If you’re not into the game, or even if you’ve never even played it, don’t worry: it won’t get in the way too much, as I will just explain the theoretical side of K-means Clustering and show you how to apply it using Dask. If you are into the game, then you’re gonna love the examples.
The algorithm we will look into today is called ‘K-means clustering’. It provides a way to characterize and categorize data if we don’t really know how to separate it before hand.
What do I mean by Unsupervised Learning? Suppose you had a set of pictures of cats and dogs. You could train a supervised Machine Learning model to classify the pictures into either category.
However, imagine you have a big, complex dataset of things you don’t know a lot about. For instance, you could have data about the light spectrum produced by different planets, and be looking for a way to group them into categories.
For another example, you could have loads of genetic data from many different organisms, and wish to define which ones belong to the same genus or families in an intuitive way.
Or, in our case, we could have 777 different Magic: The Gathering decks, using over 600 different cards (yeah, the professional meta is not that diverse), and want to train a machine learning model so that it understands which cards work well together and which ones don’t.
Now imagine you had to do this task, and you had no idea how to play this game. Wouldn’t it be nice if someone had invented an algorithm to cluster data together if they look similar, without you having to provide a definition for ‘similar’? That’s what clustering, and k-means clustering in particular, are all about.
Now that’s done, I hope you’re motivated, because it’s time to get our hands dirty with some theory.
K-Means Clustering receives a single hyperparameter: k, which specifies how many clusters we want to categorize our data into.
The clusters won’t necessarily have all the same quantity of instances. However, they should each characterize a specific subset of our data. How will we achieve this? Let’s find out!
First of all, the input for this algorithm needs to be a set of vectors. That is, all your features should be numerical, and in the same order. If you had any categorical features, my advice would be to use one-hot encode: convert each categorical variable into a vector of n-elements: one for each possible category, all set to 0 except the one for the given category.
What the algorithm will do is initiate k random ‘centroids’ -points in the space defined by the dimensions of the dataset’s elements-, and then it will:
Assign each element to the centroid closest to it.Remap the centroid to the point lying on the average of all the elements assigned to it.Repeat steps 1 and 2, until convergence (or a stopping condition, such as doing N iterations for a given N) is met.
Assign each element to the centroid closest to it.
Remap the centroid to the point lying on the average of all the elements assigned to it.
Repeat steps 1 and 2, until convergence (or a stopping condition, such as doing N iterations for a given N) is met.
In the end, each element will have been assigned to one of k clusters, such that the elements in the same cluster all lie closest to it.
Like many other unsupervised learning algorithms, K-means clustering can work wonders if used as a way to generate inputs for a supervised Machine Learning algorithm (for instance, a classifier).
The inputs could be a one-hot encode of which cluster a given instance falls into, or the k distances to each cluster’s centroid.
For this project however, what we’ll be developing will be a (somewhat rudimentary) recommender system which will, given an instance, return elements appearing on the same cluster.
Having defined the concepts for this project, let’s now begin the practical part. The code is available in the Jupyter Notebook on this repository.
I stored the MtgTop8 decks following this format:
N card nameM another card name
in 777 different .txt files, where each line refers to a card, and the digits before the first space are the number of apparitions for that card in the deck.
In order to transform them into a more manageable format -I’ll be using a list of tuples (Int, String) for each deck, each tuple a card-, this is what we’ll do:
This is what a deck looks like now.
[(4, 'Ancient Ziggurat'), (4, 'Cavern of Souls'), (4, 'Horizon Canopy'), (1, 'Plains'), (2, 'Seachrome Coast'), (4, 'Unclaimed Territory'), (4, 'Champion of the Parish'), (1, 'Dark Confidant') ...]
Where each tuple represents a card (yes, those are real card names), and how many times it appears.
Since we want to map each deck to a vector, it seems intuitive to just
Turn them into a list, with one element for each different card in the whole dataset.
Set each component to the number of apparitions for the corresponding card (with all the components corresponding to cards that do not appear in the deck set to 0).
To do that, let’s get all the different cards that appear in all the decks.
And now let’s use our newfound knowledge about card names to turn all decks into beautiful, consumable vectors.
Now all our decks can be easily fed into Dask’s K-Means Clustering algorithm, and we can play with the output.
We could have just used ‘binary’ vectors, and set the components to 1 if the card appears in the deck, and 0 if it doesn’t. We could also try that later and see if we get good results too.
Now that our data is all neatly mapped to the vector space, actually using Dask’s K-means Clustering is pretty simple.
Where the most important part is the n_clusters argument, which I kind of arbitrarily set to 8.
In real life, you may want to experiment with different values. For this particular case, I know MtG has 5 different ‘colors’ for cards. To prevent the algorithm from just clustering the cards for their colors (which it didn’t do at all anyway), I chose a number bigger than 5.
The algorithm returns the labels as a Dask Array. I may do an article on how to use those later, but right now I didn’t want to deal with all that. Also, the MtgTop8 dataset is small enough for that to not matter that much, so I decided to convert it back to a list of integers. Sue me.
At first I wanted to check if the results made any sense. This was my first time using K-means Clustering on this dataset, and I wanted to make sure it had learned something valuable. So I just checked which cards were most frequent in the decks from each cluster. The results were, at least to me, astounding. Here’s what I did to check.
If you’re interested in the results, I strongly encourage you to download the notebook from the GitHub project and play with it, it’s honest fun! I just didn’t want to mix my M:tG findings with this tutorial so that readers who are into Data Science but not into the game won’t be bored.
Now we made that sanity check, we can proceed with the actual application for all the labels we generated.
There are many ways we could have approached the recommendation problem: given a card, suggest other cards that go well with it, without using any data about the cards except which decks they appear in (that is, no cheating and asking for more data about the cards like color, price, or an expert’s opinion).
Think for a moment, how would you use the clusters data to generate the recommendations? I’m sure you could come up with a few ideas.
If what you came up with is not what I’m about to do, please tell me in the comments! Creativity is more fun if it’s a team effort, and I really want to see what my dear readers come up with.
Finally, here’s what I did:
As you can see, I omit how many times a card appears on a given deck for this part, and just look at the relative number of apparitions for a card on a given cluster.
I then return the cards with the most similar relative apparitions (defined by Euclidian distance).
If you’re a Magic: The Gathering player, try out this code and see the results, it makes pretty good (though kinda conservative) recommendations!
K-Means clustering allowed us to approach a domain without really knowing a whole lot about it, and draw conclusions and even design a useful application around it.
It let us do that by learning the underlying patterns in the data for us, only asking that we gave it the data in the correct format.
I encourage you to play with the code here, and try making your own recommendation’s system with a different Dataset, or solving some other problem. If you do, please show me your results! I wanna see what you come up with.
In the future, I’d like to do this same analysis using non-professional decks. That way, I could make a recommendations engine for casual players (like me). I think it would be cool if it worked with almost any card, and not just 642.
If you want to delve deeper into Unsupervised Learning, I can’t recommend Introduction to Statistical Learning enough. That’s the book I learned about K-Means Clustering from. It’s also the book thanks to which I finally understood Boosted Trees, though that’s a tale for another article.
If you liked this article, please follow me on Medium, and consider helping me maintain my website’s hosting. Let me know if you found the article helpful, or if any of it sounds wrong or doesn’t work!
Happy coding.
Originally published at www.datastuff.tech on April 3, 2019. | [
{
"code": null,
"e": 377,
"s": 171,
"text": "Unsupervised Learning has been called the closest thing we have to “actual” Artificial Intelligence, in the sense of General AI, with K-Means Clustering one of its simplest, but most powerful applications."
},
{
"code": null,
"e": 669,
"s": 377,
"text": "I am not here to discuss whether those claims are true or not, as I am not an expert nor a philosopher. I will however state, that I am often amazed by how well unsupervised learning techniques, even the most rudimentary, capture patterns in the data that I would expect only people to find."
},
{
"code": null,
"e": 889,
"s": 669,
"text": "Today we’ll apply unsupervised learning on a Dataset I gathered myself. It’s a database of professional Magic: The Gathering decks that I crawled from mtgtop8.com, an awesome website if you’re into Magic: the Gathering."
},
{
"code": null,
"e": 1017,
"s": 889,
"text": "I scraped the MtgTop8 data from a few years of tournaments, and they’re all available to be consumed in this GitHub repository."
},
{
"code": null,
"e": 1303,
"s": 1017,
"text": "If you’re not into the game, or even if you’ve never even played it, don’t worry: it won’t get in the way too much, as I will just explain the theoretical side of K-means Clustering and show you how to apply it using Dask. If you are into the game, then you’re gonna love the examples."
},
{
"code": null,
"e": 1483,
"s": 1303,
"text": "The algorithm we will look into today is called ‘K-means clustering’. It provides a way to characterize and categorize data if we don’t really know how to separate it before hand."
},
{
"code": null,
"e": 1675,
"s": 1483,
"text": "What do I mean by Unsupervised Learning? Suppose you had a set of pictures of cats and dogs. You could train a supervised Machine Learning model to classify the pictures into either category."
},
{
"code": null,
"e": 1908,
"s": 1675,
"text": "However, imagine you have a big, complex dataset of things you don’t know a lot about. For instance, you could have data about the light spectrum produced by different planets, and be looking for a way to group them into categories."
},
{
"code": null,
"e": 2085,
"s": 1908,
"text": "For another example, you could have loads of genetic data from many different organisms, and wish to define which ones belong to the same genus or families in an intuitive way."
},
{
"code": null,
"e": 2359,
"s": 2085,
"text": "Or, in our case, we could have 777 different Magic: The Gathering decks, using over 600 different cards (yeah, the professional meta is not that diverse), and want to train a machine learning model so that it understands which cards work well together and which ones don’t."
},
{
"code": null,
"e": 2678,
"s": 2359,
"text": "Now imagine you had to do this task, and you had no idea how to play this game. Wouldn’t it be nice if someone had invented an algorithm to cluster data together if they look similar, without you having to provide a definition for ‘similar’? That’s what clustering, and k-means clustering in particular, are all about."
},
{
"code": null,
"e": 2779,
"s": 2678,
"text": "Now that’s done, I hope you’re motivated, because it’s time to get our hands dirty with some theory."
},
{
"code": null,
"e": 2906,
"s": 2779,
"text": "K-Means Clustering receives a single hyperparameter: k, which specifies how many clusters we want to categorize our data into."
},
{
"code": null,
"e": 3090,
"s": 2906,
"text": "The clusters won’t necessarily have all the same quantity of instances. However, they should each characterize a specific subset of our data. How will we achieve this? Let’s find out!"
},
{
"code": null,
"e": 3460,
"s": 3090,
"text": "First of all, the input for this algorithm needs to be a set of vectors. That is, all your features should be numerical, and in the same order. If you had any categorical features, my advice would be to use one-hot encode: convert each categorical variable into a vector of n-elements: one for each possible category, all set to 0 except the one for the given category."
},
{
"code": null,
"e": 3613,
"s": 3460,
"text": "What the algorithm will do is initiate k random ‘centroids’ -points in the space defined by the dimensions of the dataset’s elements-, and then it will:"
},
{
"code": null,
"e": 3867,
"s": 3613,
"text": "Assign each element to the centroid closest to it.Remap the centroid to the point lying on the average of all the elements assigned to it.Repeat steps 1 and 2, until convergence (or a stopping condition, such as doing N iterations for a given N) is met."
},
{
"code": null,
"e": 3918,
"s": 3867,
"text": "Assign each element to the centroid closest to it."
},
{
"code": null,
"e": 4007,
"s": 3918,
"text": "Remap the centroid to the point lying on the average of all the elements assigned to it."
},
{
"code": null,
"e": 4123,
"s": 4007,
"text": "Repeat steps 1 and 2, until convergence (or a stopping condition, such as doing N iterations for a given N) is met."
},
{
"code": null,
"e": 4260,
"s": 4123,
"text": "In the end, each element will have been assigned to one of k clusters, such that the elements in the same cluster all lie closest to it."
},
{
"code": null,
"e": 4456,
"s": 4260,
"text": "Like many other unsupervised learning algorithms, K-means clustering can work wonders if used as a way to generate inputs for a supervised Machine Learning algorithm (for instance, a classifier)."
},
{
"code": null,
"e": 4586,
"s": 4456,
"text": "The inputs could be a one-hot encode of which cluster a given instance falls into, or the k distances to each cluster’s centroid."
},
{
"code": null,
"e": 4767,
"s": 4586,
"text": "For this project however, what we’ll be developing will be a (somewhat rudimentary) recommender system which will, given an instance, return elements appearing on the same cluster."
},
{
"code": null,
"e": 4915,
"s": 4767,
"text": "Having defined the concepts for this project, let’s now begin the practical part. The code is available in the Jupyter Notebook on this repository."
},
{
"code": null,
"e": 4965,
"s": 4915,
"text": "I stored the MtgTop8 decks following this format:"
},
{
"code": null,
"e": 4996,
"s": 4965,
"text": "N card nameM another card name"
},
{
"code": null,
"e": 5154,
"s": 4996,
"text": "in 777 different .txt files, where each line refers to a card, and the digits before the first space are the number of apparitions for that card in the deck."
},
{
"code": null,
"e": 5315,
"s": 5154,
"text": "In order to transform them into a more manageable format -I’ll be using a list of tuples (Int, String) for each deck, each tuple a card-, this is what we’ll do:"
},
{
"code": null,
"e": 5351,
"s": 5315,
"text": "This is what a deck looks like now."
},
{
"code": null,
"e": 5563,
"s": 5351,
"text": "[(4, 'Ancient Ziggurat'), (4, 'Cavern of Souls'), (4, 'Horizon Canopy'), (1, 'Plains'), (2, 'Seachrome Coast'), (4, 'Unclaimed Territory'), (4, 'Champion of the Parish'), (1, 'Dark Confidant') ...]"
},
{
"code": null,
"e": 5663,
"s": 5563,
"text": "Where each tuple represents a card (yes, those are real card names), and how many times it appears."
},
{
"code": null,
"e": 5734,
"s": 5663,
"text": "Since we want to map each deck to a vector, it seems intuitive to just"
},
{
"code": null,
"e": 5820,
"s": 5734,
"text": "Turn them into a list, with one element for each different card in the whole dataset."
},
{
"code": null,
"e": 5985,
"s": 5820,
"text": "Set each component to the number of apparitions for the corresponding card (with all the components corresponding to cards that do not appear in the deck set to 0)."
},
{
"code": null,
"e": 6061,
"s": 5985,
"text": "To do that, let’s get all the different cards that appear in all the decks."
},
{
"code": null,
"e": 6173,
"s": 6061,
"text": "And now let’s use our newfound knowledge about card names to turn all decks into beautiful, consumable vectors."
},
{
"code": null,
"e": 6284,
"s": 6173,
"text": "Now all our decks can be easily fed into Dask’s K-Means Clustering algorithm, and we can play with the output."
},
{
"code": null,
"e": 6473,
"s": 6284,
"text": "We could have just used ‘binary’ vectors, and set the components to 1 if the card appears in the deck, and 0 if it doesn’t. We could also try that later and see if we get good results too."
},
{
"code": null,
"e": 6592,
"s": 6473,
"text": "Now that our data is all neatly mapped to the vector space, actually using Dask’s K-means Clustering is pretty simple."
},
{
"code": null,
"e": 6688,
"s": 6592,
"text": "Where the most important part is the n_clusters argument, which I kind of arbitrarily set to 8."
},
{
"code": null,
"e": 6966,
"s": 6688,
"text": "In real life, you may want to experiment with different values. For this particular case, I know MtG has 5 different ‘colors’ for cards. To prevent the algorithm from just clustering the cards for their colors (which it didn’t do at all anyway), I chose a number bigger than 5."
},
{
"code": null,
"e": 7253,
"s": 6966,
"text": "The algorithm returns the labels as a Dask Array. I may do an article on how to use those later, but right now I didn’t want to deal with all that. Also, the MtgTop8 dataset is small enough for that to not matter that much, so I decided to convert it back to a list of integers. Sue me."
},
{
"code": null,
"e": 7592,
"s": 7253,
"text": "At first I wanted to check if the results made any sense. This was my first time using K-means Clustering on this dataset, and I wanted to make sure it had learned something valuable. So I just checked which cards were most frequent in the decks from each cluster. The results were, at least to me, astounding. Here’s what I did to check."
},
{
"code": null,
"e": 7880,
"s": 7592,
"text": "If you’re interested in the results, I strongly encourage you to download the notebook from the GitHub project and play with it, it’s honest fun! I just didn’t want to mix my M:tG findings with this tutorial so that readers who are into Data Science but not into the game won’t be bored."
},
{
"code": null,
"e": 7987,
"s": 7880,
"text": "Now we made that sanity check, we can proceed with the actual application for all the labels we generated."
},
{
"code": null,
"e": 8296,
"s": 7987,
"text": "There are many ways we could have approached the recommendation problem: given a card, suggest other cards that go well with it, without using any data about the cards except which decks they appear in (that is, no cheating and asking for more data about the cards like color, price, or an expert’s opinion)."
},
{
"code": null,
"e": 8430,
"s": 8296,
"text": "Think for a moment, how would you use the clusters data to generate the recommendations? I’m sure you could come up with a few ideas."
},
{
"code": null,
"e": 8622,
"s": 8430,
"text": "If what you came up with is not what I’m about to do, please tell me in the comments! Creativity is more fun if it’s a team effort, and I really want to see what my dear readers come up with."
},
{
"code": null,
"e": 8650,
"s": 8622,
"text": "Finally, here’s what I did:"
},
{
"code": null,
"e": 8817,
"s": 8650,
"text": "As you can see, I omit how many times a card appears on a given deck for this part, and just look at the relative number of apparitions for a card on a given cluster."
},
{
"code": null,
"e": 8917,
"s": 8817,
"text": "I then return the cards with the most similar relative apparitions (defined by Euclidian distance)."
},
{
"code": null,
"e": 9063,
"s": 8917,
"text": "If you’re a Magic: The Gathering player, try out this code and see the results, it makes pretty good (though kinda conservative) recommendations!"
},
{
"code": null,
"e": 9228,
"s": 9063,
"text": "K-Means clustering allowed us to approach a domain without really knowing a whole lot about it, and draw conclusions and even design a useful application around it."
},
{
"code": null,
"e": 9362,
"s": 9228,
"text": "It let us do that by learning the underlying patterns in the data for us, only asking that we gave it the data in the correct format."
},
{
"code": null,
"e": 9586,
"s": 9362,
"text": "I encourage you to play with the code here, and try making your own recommendation’s system with a different Dataset, or solving some other problem. If you do, please show me your results! I wanna see what you come up with."
},
{
"code": null,
"e": 9821,
"s": 9586,
"text": "In the future, I’d like to do this same analysis using non-professional decks. That way, I could make a recommendations engine for casual players (like me). I think it would be cool if it worked with almost any card, and not just 642."
},
{
"code": null,
"e": 10110,
"s": 9821,
"text": "If you want to delve deeper into Unsupervised Learning, I can’t recommend Introduction to Statistical Learning enough. That’s the book I learned about K-Means Clustering from. It’s also the book thanks to which I finally understood Boosted Trees, though that’s a tale for another article."
},
{
"code": null,
"e": 10312,
"s": 10110,
"text": "If you liked this article, please follow me on Medium, and consider helping me maintain my website’s hosting. Let me know if you found the article helpful, or if any of it sounds wrong or doesn’t work!"
},
{
"code": null,
"e": 10326,
"s": 10312,
"text": "Happy coding."
}
] |
How to set Bullet colors in HTML Lists using only CSS? - GeeksforGeeks | 12 Feb, 2019
Given an unordered lists (UL) of bullets, we need to change the color of the bullets in the list using CSS.
Note: It is not allowed to use any images or span tags.
First of all, there is not direct way in CSS by which we can change the color of the bullets in an unordered list. However, to change the color of the bullets in an unordered list using CSS, we will have to first discard the default list-style and manually define the content that comes before each list item of the list.
This content is the Unicode of the kind of bullet that you want to use for your list. The Unicode characters for different bullet styles are as follows:
Square: "\25AA"
Circle: "\2022"
Disc: "\2022"
Below is a sample CSS code that removes the default style from an Unordered List in HTML and use unicodes:
ul{ /* Remove default bullets */ list-style: none; } ul li::before { /* Add Unicode of the bullet */ content: ; /* Color of the content -- bullet here */ color: green; /* Required to add space between the bullet and the text */ display: inline-block; /* Required to add space between the bullet and the text */ width: 1em; /* Required to add space between the bullet and the text */ margin-left: -0.9em; }
Below programs illustrate the above approach of changing colours of list item bullets:
Example 1:
<html> <head> <title>Changing Bullet Colors</title> <style> h3{ color:green; } ul{ list-style: none; } ul li::before { /* \2022 is the CSS Code/unicode for a disc */ content: "\2022"; color: green; display: inline-block; width: 1em; margin-left: -0.9em; font-weight: bold; font-size:1.1rem; } </style> </head> <body> <h3>Geek Movies</h3> <!-- Create an Unordered List --> <ul> <li>Star Wars</li> <li>Back to the future</li> <li>Ghostbusters</li> <li>The princess bride</li> <li>Shaun of the dead</li> </ul> </body> </html>
Output:
Example 2:
<html> <head> <title>Changing Bullet Colors</title> <style> h3{ color:green; } ul{ list-style: none; } ul li::before { /*\25E6 is the CSS Code/unicode for a circle */ content: "\25E6"; color: green; display: inline-block; width: 1em; margin-left: -0.9em; font-weight: bold; font-size:1.1rem; } </style> </head> <body> <h3>Geek Movies</h3> <!-- Create an Unordered List --> <ul> <li>Star Wars</li> <li>Back to the future</li> <li>Ghostbusters</li> <li>The princess bride</li> <li>Shaun of the dead</li> </ul> </body> </html>
Output:
Example 3:
<html> <head> <title>Changing Bullet Colors</title> <style> h3{ color:green; } ul{ list-style: none; } ul li::before { /* \25AA is the CSS Code/unicode for a square */ content: "\25AA"; color: green; display: inline-block; width: 1em; margin-left: -0.9em; font-weight: bold; font-size:1.1rem; } </style> </head> <body> <h3>Geek Movies</h3> <!-- Create an Unordered List --> <ul> <li>Star Wars</li> <li>Back to the future</li> <li>Ghostbusters</li> <li>The princess bride</li> <li>Shaun of the dead</li> </ul> </body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Archana choudhary
Picked
CSS
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 create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 23601,
"s": 23573,
"text": "\n12 Feb, 2019"
},
{
"code": null,
"e": 23709,
"s": 23601,
"text": "Given an unordered lists (UL) of bullets, we need to change the color of the bullets in the list using CSS."
},
{
"code": null,
"e": 23765,
"s": 23709,
"text": "Note: It is not allowed to use any images or span tags."
},
{
"code": null,
"e": 24087,
"s": 23765,
"text": "First of all, there is not direct way in CSS by which we can change the color of the bullets in an unordered list. However, to change the color of the bullets in an unordered list using CSS, we will have to first discard the default list-style and manually define the content that comes before each list item of the list."
},
{
"code": null,
"e": 24240,
"s": 24087,
"text": "This content is the Unicode of the kind of bullet that you want to use for your list. The Unicode characters for different bullet styles are as follows:"
},
{
"code": null,
"e": 24256,
"s": 24240,
"text": "Square: \"\\25AA\""
},
{
"code": null,
"e": 24272,
"s": 24256,
"text": "Circle: \"\\2022\""
},
{
"code": null,
"e": 24286,
"s": 24272,
"text": "Disc: \"\\2022\""
},
{
"code": null,
"e": 24393,
"s": 24286,
"text": "Below is a sample CSS code that removes the default style from an Unordered List in HTML and use unicodes:"
},
{
"code": "ul{ /* Remove default bullets */ list-style: none; } ul li::before { /* Add Unicode of the bullet */ content: ; /* Color of the content -- bullet here */ color: green; /* Required to add space between the bullet and the text */ display: inline-block; /* Required to add space between the bullet and the text */ width: 1em; /* Required to add space between the bullet and the text */ margin-left: -0.9em; }",
"e": 24882,
"s": 24393,
"text": null
},
{
"code": null,
"e": 24969,
"s": 24882,
"text": "Below programs illustrate the above approach of changing colours of list item bullets:"
},
{
"code": null,
"e": 24980,
"s": 24969,
"text": "Example 1:"
},
{
"code": "<html> <head> <title>Changing Bullet Colors</title> <style> h3{ color:green; } ul{ list-style: none; } ul li::before { /* \\2022 is the CSS Code/unicode for a disc */ content: \"\\2022\"; color: green; display: inline-block; width: 1em; margin-left: -0.9em; font-weight: bold; font-size:1.1rem; } </style> </head> <body> <h3>Geek Movies</h3> <!-- Create an Unordered List --> <ul> <li>Star Wars</li> <li>Back to the future</li> <li>Ghostbusters</li> <li>The princess bride</li> <li>Shaun of the dead</li> </ul> </body> </html>",
"e": 25875,
"s": 24980,
"text": null
},
{
"code": null,
"e": 25883,
"s": 25875,
"text": "Output:"
},
{
"code": null,
"e": 25894,
"s": 25883,
"text": "Example 2:"
},
{
"code": "<html> <head> <title>Changing Bullet Colors</title> <style> h3{ color:green; } ul{ list-style: none; } ul li::before { /*\\25E6 is the CSS Code/unicode for a circle */ content: \"\\25E6\"; color: green; display: inline-block; width: 1em; margin-left: -0.9em; font-weight: bold; font-size:1.1rem; } </style> </head> <body> <h3>Geek Movies</h3> <!-- Create an Unordered List --> <ul> <li>Star Wars</li> <li>Back to the future</li> <li>Ghostbusters</li> <li>The princess bride</li> <li>Shaun of the dead</li> </ul> </body> </html>",
"e": 26790,
"s": 25894,
"text": null
},
{
"code": null,
"e": 26798,
"s": 26790,
"text": "Output:"
},
{
"code": null,
"e": 26809,
"s": 26798,
"text": "Example 3:"
},
{
"code": "<html> <head> <title>Changing Bullet Colors</title> <style> h3{ color:green; } ul{ list-style: none; } ul li::before { /* \\25AA is the CSS Code/unicode for a square */ content: \"\\25AA\"; color: green; display: inline-block; width: 1em; margin-left: -0.9em; font-weight: bold; font-size:1.1rem; } </style> </head> <body> <h3>Geek Movies</h3> <!-- Create an Unordered List --> <ul> <li>Star Wars</li> <li>Back to the future</li> <li>Ghostbusters</li> <li>The princess bride</li> <li>Shaun of the dead</li> </ul> </body> </html>",
"e": 27706,
"s": 26809,
"text": null
},
{
"code": null,
"e": 27714,
"s": 27706,
"text": "Output:"
},
{
"code": null,
"e": 27851,
"s": 27714,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 27869,
"s": 27851,
"text": "Archana choudhary"
},
{
"code": null,
"e": 27876,
"s": 27869,
"text": "Picked"
},
{
"code": null,
"e": 27880,
"s": 27876,
"text": "CSS"
},
{
"code": null,
"e": 27885,
"s": 27880,
"text": "HTML"
},
{
"code": null,
"e": 27902,
"s": 27885,
"text": "Web Technologies"
},
{
"code": null,
"e": 27907,
"s": 27902,
"text": "HTML"
},
{
"code": null,
"e": 28005,
"s": 27907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28014,
"s": 28005,
"text": "Comments"
},
{
"code": null,
"e": 28027,
"s": 28014,
"text": "Old Comments"
},
{
"code": null,
"e": 28085,
"s": 28027,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28122,
"s": 28085,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28163,
"s": 28122,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 28200,
"s": 28163,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28264,
"s": 28200,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 28324,
"s": 28264,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28385,
"s": 28324,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28422,
"s": 28385,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28475,
"s": 28422,
"text": "Hide or show elements in HTML using display property"
}
] |
D3.js area() Method - GeeksforGeeks | 31 Aug, 2020
The d3.area() method in D3.js is used to return an area generator with default settings that can be further used to create areas.
Syntax:
d3.area()
Parameters: This method does not accept parameters.
Return Value: This method returns no value.
Below examples illustrate the d3.area() method in D3.js:
Example 1:
HTML
<!DOCTYPE html><html> <head> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <h1 style="text-align: center; color: green;"> GeeksforGeeks </h1> <center> <svg id="gfg" width="200" height="200"> </svg> </center> <script> var data = [ { x: 0, y: 10 }, { x: 10, y: 30 }, { x: 20, y: 150 }, { x: 50, y: 10 }, { x: 60, y: 150 }, { x: 70, y: 50 }, { x: 80, y: 190 }]; data.sort((a, b) => a.y - b.y); var xScale = d3.scaleLinear() .domain([0, 8]) .range([25, 200]); var yScale = d3.scaleLinear() .domain([0, 20]) .range([200, 25]); // Using area() function to // generate area var Gen = d3.area() .x((p) => p.x) .y0((p) => 0) .y1((p) => p.y); d3.select("#gfg") .append("path") .attr("d", Gen(data)) .attr("fill", "green") .attr("stroke", "black"); </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <head> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <h1 style="text-align: center; color: green;"> GeeksforGeeks </h1> <center> <svg id="gfg" width="250" height="200"> </svg> </center> <script> var points = [ { xpoint: 25, ypoint: 150 }, { xpoint: 75, ypoint: 50 }, { xpoint: 100, ypoint: 150 }, { xpoint: 100, ypoint: 50 }, { xpoint: 200, ypoint: 150 }]; // Using area() function to generate area var Gen = d3.area() .x((p) => p.xpoint) .y0((p) => 0) .y1((p) => p.ypoint); d3.select("#gfg") .append("path") .attr("d", Gen(points)) .attr("fill", "green") .attr("stroke", "black"); </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
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need 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": 24909,
"s": 24881,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 25039,
"s": 24909,
"text": "The d3.area() method in D3.js is used to return an area generator with default settings that can be further used to create areas."
},
{
"code": null,
"e": 25047,
"s": 25039,
"text": "Syntax:"
},
{
"code": null,
"e": 25057,
"s": 25047,
"text": "d3.area()"
},
{
"code": null,
"e": 25109,
"s": 25057,
"text": "Parameters: This method does not accept parameters."
},
{
"code": null,
"e": 25153,
"s": 25109,
"text": "Return Value: This method returns no value."
},
{
"code": null,
"e": 25210,
"s": 25153,
"text": "Below examples illustrate the d3.area() method in D3.js:"
},
{
"code": null,
"e": 25221,
"s": 25210,
"text": "Example 1:"
},
{
"code": null,
"e": 25226,
"s": 25221,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <h1 style=\"text-align: center; color: green;\"> GeeksforGeeks </h1> <center> <svg id=\"gfg\" width=\"200\" height=\"200\"> </svg> </center> <script> var data = [ { x: 0, y: 10 }, { x: 10, y: 30 }, { x: 20, y: 150 }, { x: 50, y: 10 }, { x: 60, y: 150 }, { x: 70, y: 50 }, { x: 80, y: 190 }]; data.sort((a, b) => a.y - b.y); var xScale = d3.scaleLinear() .domain([0, 8]) .range([25, 200]); var yScale = d3.scaleLinear() .domain([0, 20]) .range([200, 25]); // Using area() function to // generate area var Gen = d3.area() .x((p) => p.x) .y0((p) => 0) .y1((p) => p.y); d3.select(\"#gfg\") .append(\"path\") .attr(\"d\", Gen(data)) .attr(\"fill\", \"green\") .attr(\"stroke\", \"black\"); </script></body> </html>",
"e": 26342,
"s": 25226,
"text": null
},
{
"code": null,
"e": 26350,
"s": 26342,
"text": "Output:"
},
{
"code": null,
"e": 26361,
"s": 26350,
"text": "Example 2:"
},
{
"code": null,
"e": 26366,
"s": 26361,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <h1 style=\"text-align: center; color: green;\"> GeeksforGeeks </h1> <center> <svg id=\"gfg\" width=\"250\" height=\"200\"> </svg> </center> <script> var points = [ { xpoint: 25, ypoint: 150 }, { xpoint: 75, ypoint: 50 }, { xpoint: 100, ypoint: 150 }, { xpoint: 100, ypoint: 50 }, { xpoint: 200, ypoint: 150 }]; // Using area() function to generate area var Gen = d3.area() .x((p) => p.xpoint) .y0((p) => 0) .y1((p) => p.ypoint); d3.select(\"#gfg\") .append(\"path\") .attr(\"d\", Gen(points)) .attr(\"fill\", \"green\") .attr(\"stroke\", \"black\"); </script></body> </html>",
"e": 27253,
"s": 26366,
"text": null
},
{
"code": null,
"e": 27261,
"s": 27253,
"text": "Output:"
},
{
"code": null,
"e": 27267,
"s": 27261,
"text": "D3.js"
},
{
"code": null,
"e": 27278,
"s": 27267,
"text": "JavaScript"
},
{
"code": null,
"e": 27295,
"s": 27278,
"text": "Web Technologies"
},
{
"code": null,
"e": 27393,
"s": 27295,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27402,
"s": 27393,
"text": "Comments"
},
{
"code": null,
"e": 27415,
"s": 27402,
"text": "Old Comments"
},
{
"code": null,
"e": 27476,
"s": 27415,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27517,
"s": 27476,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27571,
"s": 27517,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27611,
"s": 27571,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27673,
"s": 27611,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27729,
"s": 27673,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27762,
"s": 27729,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27824,
"s": 27762,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27867,
"s": 27824,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Final local variables in C# | To set final for a local variable, use the read-only keyword in C#, since the implementation of the final keyword is not possible.
The readonly would allow the variables to be assigned a value only once. A field marked "read-only", can only be set once during the construction of an object. It cannot be changed.
Let us see an example. Below, we have set the empCount field as read-only, which once assigned cannot be changed.
class Department {
readonly int empCount;
Employee(int empCount) {
this. empCount = empCount;
}
void ChangeCount() {
//empCount = 150; // Compile error
}
} | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "To set final for a local variable, use the read-only keyword in C#, since the implementation of the final keyword is not possible."
},
{
"code": null,
"e": 1375,
"s": 1193,
"text": "The readonly would allow the variables to be assigned a value only once. A field marked \"read-only\", can only be set once during the construction of an object. It cannot be changed."
},
{
"code": null,
"e": 1489,
"s": 1375,
"text": "Let us see an example. Below, we have set the empCount field as read-only, which once assigned cannot be changed."
},
{
"code": null,
"e": 1674,
"s": 1489,
"text": "class Department {\n readonly int empCount;\n\n Employee(int empCount) {\n this. empCount = empCount;\n }\n\n void ChangeCount() {\n //empCount = 150; // Compile error\n }\n}"
}
] |
How to calculate mean of a CSV file in R? - GeeksforGeeks | 26 Mar, 2021
Mean or average is a method to study central tendency of any given numeric data. It can be found using the formula.
In this article, we will be discussing two different ways to calculate the mean of a CSV file in R.
Data in use:
Method 1: Using mean function
In this method to calculate the mean of the column of a CSV file we simply use the mean() function with the column name as its parameter and this function will be returning the mean of the provided column of the CSV file.
Syntax:
mean(name of the column)
Approach
Read file
Select column
Pass the column to mean function
Display result
Example:
R
gfg=read.csv('values.csv') result<- mean(gfg$V1) print(result)
Output:
[1] 5.266667
Method 2: Using nrow() and sum()
In this method we will be using the sum and the nrow functions separately to calculate the total number of entity in the whole csv file and there respected sum and then divide the total sum by the number of rows to get the mean.
sum() function:-Returns the sum of the respected parameter
Syntax:
sum(column_name)
nrow() function:-Returns the number of entity in the CSV file
Syntax:
nrow(name of the file)
Approach
Import file
Find sum
Find frequency
Divide sum by frequency
Store this value as mean
Display result
Example:
R
gfg=read.csv('values.csv') mean<-sum(gfg$V1)/nrow(gfg) mean
Output:
[1] 5.266667
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement | [
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 25358,
"s": 25242,
"text": "Mean or average is a method to study central tendency of any given numeric data. It can be found using the formula."
},
{
"code": null,
"e": 25458,
"s": 25358,
"text": "In this article, we will be discussing two different ways to calculate the mean of a CSV file in R."
},
{
"code": null,
"e": 25471,
"s": 25458,
"text": "Data in use:"
},
{
"code": null,
"e": 25501,
"s": 25471,
"text": "Method 1: Using mean function"
},
{
"code": null,
"e": 25723,
"s": 25501,
"text": "In this method to calculate the mean of the column of a CSV file we simply use the mean() function with the column name as its parameter and this function will be returning the mean of the provided column of the CSV file."
},
{
"code": null,
"e": 25731,
"s": 25723,
"text": "Syntax:"
},
{
"code": null,
"e": 25756,
"s": 25731,
"text": "mean(name of the column)"
},
{
"code": null,
"e": 25765,
"s": 25756,
"text": "Approach"
},
{
"code": null,
"e": 25775,
"s": 25765,
"text": "Read file"
},
{
"code": null,
"e": 25789,
"s": 25775,
"text": "Select column"
},
{
"code": null,
"e": 25822,
"s": 25789,
"text": "Pass the column to mean function"
},
{
"code": null,
"e": 25837,
"s": 25822,
"text": "Display result"
},
{
"code": null,
"e": 25847,
"s": 25837,
"text": " Example:"
},
{
"code": null,
"e": 25849,
"s": 25847,
"text": "R"
},
{
"code": "gfg=read.csv('values.csv') result<- mean(gfg$V1) print(result)",
"e": 25914,
"s": 25849,
"text": null
},
{
"code": null,
"e": 25922,
"s": 25914,
"text": "Output:"
},
{
"code": null,
"e": 25935,
"s": 25922,
"text": "[1] 5.266667"
},
{
"code": null,
"e": 25970,
"s": 25935,
"text": "Method 2: Using nrow() and sum() "
},
{
"code": null,
"e": 26199,
"s": 25970,
"text": "In this method we will be using the sum and the nrow functions separately to calculate the total number of entity in the whole csv file and there respected sum and then divide the total sum by the number of rows to get the mean."
},
{
"code": null,
"e": 26258,
"s": 26199,
"text": "sum() function:-Returns the sum of the respected parameter"
},
{
"code": null,
"e": 26266,
"s": 26258,
"text": "Syntax:"
},
{
"code": null,
"e": 26283,
"s": 26266,
"text": "sum(column_name)"
},
{
"code": null,
"e": 26345,
"s": 26283,
"text": "nrow() function:-Returns the number of entity in the CSV file"
},
{
"code": null,
"e": 26353,
"s": 26345,
"text": "Syntax:"
},
{
"code": null,
"e": 26376,
"s": 26353,
"text": "nrow(name of the file)"
},
{
"code": null,
"e": 26385,
"s": 26376,
"text": "Approach"
},
{
"code": null,
"e": 26397,
"s": 26385,
"text": "Import file"
},
{
"code": null,
"e": 26406,
"s": 26397,
"text": "Find sum"
},
{
"code": null,
"e": 26421,
"s": 26406,
"text": "Find frequency"
},
{
"code": null,
"e": 26445,
"s": 26421,
"text": "Divide sum by frequency"
},
{
"code": null,
"e": 26470,
"s": 26445,
"text": "Store this value as mean"
},
{
"code": null,
"e": 26485,
"s": 26470,
"text": "Display result"
},
{
"code": null,
"e": 26494,
"s": 26485,
"text": "Example:"
},
{
"code": null,
"e": 26496,
"s": 26494,
"text": "R"
},
{
"code": "gfg=read.csv('values.csv') mean<-sum(gfg$V1)/nrow(gfg) mean",
"e": 26558,
"s": 26496,
"text": null
},
{
"code": null,
"e": 26566,
"s": 26558,
"text": "Output:"
},
{
"code": null,
"e": 26579,
"s": 26566,
"text": "[1] 5.266667"
},
{
"code": null,
"e": 26586,
"s": 26579,
"text": "Picked"
},
{
"code": null,
"e": 26592,
"s": 26586,
"text": "R-CSV"
},
{
"code": null,
"e": 26603,
"s": 26592,
"text": "R Language"
},
{
"code": null,
"e": 26701,
"s": 26603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26753,
"s": 26701,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26791,
"s": 26753,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26826,
"s": 26791,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26884,
"s": 26826,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26933,
"s": 26884,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26970,
"s": 26933,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 27020,
"s": 26970,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27063,
"s": 27020,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27089,
"s": 27063,
"text": "Time Series Analysis in R"
}
] |
Get time in milliseconds using Java Calendar | Create a Calendar object.
Calendar cal = Calendar.getInstance();
For using above Calendar class, do not forget to import the following package.
import java.util.Calendar;
Now, use the getTimeInMillis() method to get the time in milliseconds.
cal.getTimeInMillis()
The following is the final example.
Live Demo
import java.util.Calendar;
public class Demo {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
System.out.println("Milliseconds =" + cal.getTimeInMillis());
}
}
Milliseconds =1542636999896 | [
{
"code": null,
"e": 1088,
"s": 1062,
"text": "Create a Calendar object."
},
{
"code": null,
"e": 1127,
"s": 1088,
"text": "Calendar cal = Calendar.getInstance();"
},
{
"code": null,
"e": 1206,
"s": 1127,
"text": "For using above Calendar class, do not forget to import the following package."
},
{
"code": null,
"e": 1233,
"s": 1206,
"text": "import java.util.Calendar;"
},
{
"code": null,
"e": 1304,
"s": 1233,
"text": "Now, use the getTimeInMillis() method to get the time in milliseconds."
},
{
"code": null,
"e": 1326,
"s": 1304,
"text": "cal.getTimeInMillis()"
},
{
"code": null,
"e": 1362,
"s": 1326,
"text": "The following is the final example."
},
{
"code": null,
"e": 1373,
"s": 1362,
"text": " Live Demo"
},
{
"code": null,
"e": 1584,
"s": 1373,
"text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar cal = Calendar.getInstance();\n System.out.println(\"Milliseconds =\" + cal.getTimeInMillis());\n }\n}"
},
{
"code": null,
"e": 1612,
"s": 1584,
"text": "Milliseconds =1542636999896"
}
] |
Consecutive elements pairing in list in Python | During data analysis using python, we may come across a need to pair-up the consecutive elements of a list. In this article we will see the various ways to achieve this.
We will design an expression to put the consecutive indexes of the list elements together. And then apply the range function to determine the maximum number of times this pairing of consecutive elements will go on.
Live Demo
listA = [51,23,11,45]
# Given list
print("Given list A: ", listA)
# Use
res = [[listA[i], listA[i + 1]]
for i in range(len(listA) - 1)]
# Result
print("The list with paired elements: \n",res)
Running the above code gives us the following result −
Given list A: [51, 23, 11, 45]
The list with paired elements:
[[51, 23], [23, 11], [11, 45]]
We can also take help of map and zip functions and slicing. We slice the element at position 1 and combine it with elements at position 0. We repeat this for each pair of elements using the zip and map functions.
Live Demo
listA = [51,23,11,45]
# Given list
print("Given list A: ", listA)
# Use zip
res = list(map(list, zip(listA, listA[1:])))
# Result
print("The list with paired elements: \n",res)
Running the above code gives us the following result −
Given list A: [51, 23, 11, 45]
The list with paired elements:
[[51, 23], [23, 11], [11, 45]] | [
{
"code": null,
"e": 1232,
"s": 1062,
"text": "During data analysis using python, we may come across a need to pair-up the consecutive elements of a list. In this article we will see the various ways to achieve this."
},
{
"code": null,
"e": 1447,
"s": 1232,
"text": "We will design an expression to put the consecutive indexes of the list elements together. And then apply the range function to determine the maximum number of times this pairing of consecutive elements will go on."
},
{
"code": null,
"e": 1458,
"s": 1447,
"text": " Live Demo"
},
{
"code": null,
"e": 1653,
"s": 1458,
"text": "listA = [51,23,11,45]\n# Given list\nprint(\"Given list A: \", listA)\n# Use\nres = [[listA[i], listA[i + 1]]\n for i in range(len(listA) - 1)]\n# Result\nprint(\"The list with paired elements: \\n\",res)"
},
{
"code": null,
"e": 1708,
"s": 1653,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1801,
"s": 1708,
"text": "Given list A: [51, 23, 11, 45]\nThe list with paired elements:\n[[51, 23], [23, 11], [11, 45]]"
},
{
"code": null,
"e": 2014,
"s": 1801,
"text": "We can also take help of map and zip functions and slicing. We slice the element at position 1 and combine it with elements at position 0. We repeat this for each pair of elements using the zip and map functions."
},
{
"code": null,
"e": 2025,
"s": 2014,
"text": " Live Demo"
},
{
"code": null,
"e": 2202,
"s": 2025,
"text": "listA = [51,23,11,45]\n# Given list\nprint(\"Given list A: \", listA)\n# Use zip\nres = list(map(list, zip(listA, listA[1:])))\n# Result\nprint(\"The list with paired elements: \\n\",res)"
},
{
"code": null,
"e": 2257,
"s": 2202,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2350,
"s": 2257,
"text": "Given list A: [51, 23, 11, 45]\nThe list with paired elements:\n[[51, 23], [23, 11], [11, 45]]"
}
] |
Analysis of Boston Crime Incident Open Data Using Pandas | by Riley Huang | Towards Data Science | While I was learning Data Analysis using Pandas in Python, I was interested in analyzing the open data about the city I am currently living in.
Open data provides people myriad opportunities to use and analyze the data as they wish without restrictions. By looking at a city’s Crime Incident open data, you can learn about if this city or a specific neighborhood is safe. Hence, I used the open data of Boston Crime Incident Reports to analyze and visualize them by using Pandas. Hopefully, you can have a better understanding of obtaining, analyzing and visualizing open data after reading my experience.
Firstly, I went to Analyze Boston: a Boston open data website. Search “crime” and go to Crime Incident Reports
To get the data, I copied the link for downloading the data in csv format:
url = “https://data.boston.gov/dataset/6220d948-eae2-4e4b-8723-2dc8e67722a3/resource/12cb3883-56f5-47de-afa5-3b1cf61b257b/download/tmppj4rb047.csv”
Use wget command to download the data.
Import pandas
import pandas as pd
Use read_csv in pandas to read data and save them into a data frame
df = pd.read_csv('tmppj4rb047.csv')
Check if data is successfully obtained.
df.head()
After obtaining the data, I want to know how many types of crimes are there in Boston.
Use value_counts in Pandas.
value_counts helps count the number of appearances of different types of crimes and sort them in orders.
df.OFFENSE_CODE_GROUP.value_counts().iloc[:10]
To make it easy to show, I only asked to return the first ten results.
Here, we can see the crime incident that has happened the most frequently in Boston is “Motor Vehicle Accident Response,” and “Larceny” has also been taking place very frequently.
Then, I plotted the result for better visualization.
df.OFFENSE_CODE_GROUP.value_counts().iloc[:10].sort_values().plot(kind= “barh”)
I want to specifically analyze larceny in Boston. Hence I put the part of the data frame that contains larceny into another data frame and called it “larceny.”
larceny = df[df.OFFENSE_CODE_GROUP.str.contains(“Larceny”)]larceny.head()
Check the size of the data “Larceny”
larceny.shape()
There are 17961 records of Larceny incidents, and each record has 17 columns.
I want to know the data of crime incidents in different locations of Boston and, more specifically, what places in Boston are more dangerous.
I used groupby function in Pandas to group the types of criminal locations, and used size function to check the number of entries.
larceny.groupby(“STREET”).size().sort_values(ascending = False)
Looking at the result, we can see the locations in Boston where larceny is more likely to happen are Washington St, Boylston St, and Newbury St.
I also want to know about the trend of larceny incidents that has been taking place in Boston.
larceny.groupby(“MONTH”).size().plot(kind = “bar”)
Based on the bar graph that I computed, larceny happened the most during May, June, and December, whereas September, October, and August appear to be safer.
Let’s also look at how the number of larceny incidents changes within a day.
larceny.groupby(“HOUR”).size().plot(kind= “bar”)
Here, we can tell the safest time of the day when larceny is the least possible to happen in Boston is 5 am. However, people need to be more careful from 4 to 6 pm.
Now, I want to have an overall look at the data about larceny incidents in Boston in each month and 24 hours. Let’s specifically look at the data in 2018 since 2019 has not ended yet and the data is incomplete.
If we group MONTH and HOUR using groupby in Pandas, we get the following results.
larceny[larceny.YEAR == 2019].groupby([‘MONTH’, ‘HOUR’]).size()
However, this is not helpful for us to read the data easily. To make it better, I used unstack, and this will turn the result in a more readable form.
larceny[larceny.YEAR==2018].groupby([‘MONTH’,’HOUR’]).size().unstack(0)
Now, I want to visualize the result.
Since I am visualizing 12 months of data into 12 pieces of graphs, I want to use the facet plot. In Pandas, there is a parameter in plot called subplots. Initialize it to be True. I can also adjust the length and width of the graph by using figsize.
larceny[larceny.YEAR==2018].groupby([‘MONTH’,’HOUR’]).size().unstack(0).plot(subplots=True, kind = “bar”, figsize = (5, 30)
Now, we have a complete visualization of the larceny incidents happened in Boston in 2018.
By using Pandas, I analyzed and visualized the open data of Boston Crime Incident Reports. Turns out Pandas is indeed a very powerful Python package in terms of extracting, grouping, sorting, analyzing, and plotting the data. If you are interested in data analysis, using Pandas to analyze some real datasets is a good way to start. | [
{
"code": null,
"e": 316,
"s": 172,
"text": "While I was learning Data Analysis using Pandas in Python, I was interested in analyzing the open data about the city I am currently living in."
},
{
"code": null,
"e": 778,
"s": 316,
"text": "Open data provides people myriad opportunities to use and analyze the data as they wish without restrictions. By looking at a city’s Crime Incident open data, you can learn about if this city or a specific neighborhood is safe. Hence, I used the open data of Boston Crime Incident Reports to analyze and visualize them by using Pandas. Hopefully, you can have a better understanding of obtaining, analyzing and visualizing open data after reading my experience."
},
{
"code": null,
"e": 889,
"s": 778,
"text": "Firstly, I went to Analyze Boston: a Boston open data website. Search “crime” and go to Crime Incident Reports"
},
{
"code": null,
"e": 964,
"s": 889,
"text": "To get the data, I copied the link for downloading the data in csv format:"
},
{
"code": null,
"e": 1112,
"s": 964,
"text": "url = “https://data.boston.gov/dataset/6220d948-eae2-4e4b-8723-2dc8e67722a3/resource/12cb3883-56f5-47de-afa5-3b1cf61b257b/download/tmppj4rb047.csv”"
},
{
"code": null,
"e": 1151,
"s": 1112,
"text": "Use wget command to download the data."
},
{
"code": null,
"e": 1165,
"s": 1151,
"text": "Import pandas"
},
{
"code": null,
"e": 1185,
"s": 1165,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1253,
"s": 1185,
"text": "Use read_csv in pandas to read data and save them into a data frame"
},
{
"code": null,
"e": 1289,
"s": 1253,
"text": "df = pd.read_csv('tmppj4rb047.csv')"
},
{
"code": null,
"e": 1329,
"s": 1289,
"text": "Check if data is successfully obtained."
},
{
"code": null,
"e": 1339,
"s": 1329,
"text": "df.head()"
},
{
"code": null,
"e": 1426,
"s": 1339,
"text": "After obtaining the data, I want to know how many types of crimes are there in Boston."
},
{
"code": null,
"e": 1454,
"s": 1426,
"text": "Use value_counts in Pandas."
},
{
"code": null,
"e": 1559,
"s": 1454,
"text": "value_counts helps count the number of appearances of different types of crimes and sort them in orders."
},
{
"code": null,
"e": 1606,
"s": 1559,
"text": "df.OFFENSE_CODE_GROUP.value_counts().iloc[:10]"
},
{
"code": null,
"e": 1677,
"s": 1606,
"text": "To make it easy to show, I only asked to return the first ten results."
},
{
"code": null,
"e": 1857,
"s": 1677,
"text": "Here, we can see the crime incident that has happened the most frequently in Boston is “Motor Vehicle Accident Response,” and “Larceny” has also been taking place very frequently."
},
{
"code": null,
"e": 1910,
"s": 1857,
"text": "Then, I plotted the result for better visualization."
},
{
"code": null,
"e": 1990,
"s": 1910,
"text": "df.OFFENSE_CODE_GROUP.value_counts().iloc[:10].sort_values().plot(kind= “barh”)"
},
{
"code": null,
"e": 2150,
"s": 1990,
"text": "I want to specifically analyze larceny in Boston. Hence I put the part of the data frame that contains larceny into another data frame and called it “larceny.”"
},
{
"code": null,
"e": 2224,
"s": 2150,
"text": "larceny = df[df.OFFENSE_CODE_GROUP.str.contains(“Larceny”)]larceny.head()"
},
{
"code": null,
"e": 2261,
"s": 2224,
"text": "Check the size of the data “Larceny”"
},
{
"code": null,
"e": 2278,
"s": 2261,
"text": "larceny.shape() "
},
{
"code": null,
"e": 2356,
"s": 2278,
"text": "There are 17961 records of Larceny incidents, and each record has 17 columns."
},
{
"code": null,
"e": 2498,
"s": 2356,
"text": "I want to know the data of crime incidents in different locations of Boston and, more specifically, what places in Boston are more dangerous."
},
{
"code": null,
"e": 2629,
"s": 2498,
"text": "I used groupby function in Pandas to group the types of criminal locations, and used size function to check the number of entries."
},
{
"code": null,
"e": 2693,
"s": 2629,
"text": "larceny.groupby(“STREET”).size().sort_values(ascending = False)"
},
{
"code": null,
"e": 2838,
"s": 2693,
"text": "Looking at the result, we can see the locations in Boston where larceny is more likely to happen are Washington St, Boylston St, and Newbury St."
},
{
"code": null,
"e": 2933,
"s": 2838,
"text": "I also want to know about the trend of larceny incidents that has been taking place in Boston."
},
{
"code": null,
"e": 2984,
"s": 2933,
"text": "larceny.groupby(“MONTH”).size().plot(kind = “bar”)"
},
{
"code": null,
"e": 3141,
"s": 2984,
"text": "Based on the bar graph that I computed, larceny happened the most during May, June, and December, whereas September, October, and August appear to be safer."
},
{
"code": null,
"e": 3218,
"s": 3141,
"text": "Let’s also look at how the number of larceny incidents changes within a day."
},
{
"code": null,
"e": 3268,
"s": 3218,
"text": "larceny.groupby(“HOUR”).size().plot(kind= “bar”) "
},
{
"code": null,
"e": 3433,
"s": 3268,
"text": "Here, we can tell the safest time of the day when larceny is the least possible to happen in Boston is 5 am. However, people need to be more careful from 4 to 6 pm."
},
{
"code": null,
"e": 3644,
"s": 3433,
"text": "Now, I want to have an overall look at the data about larceny incidents in Boston in each month and 24 hours. Let’s specifically look at the data in 2018 since 2019 has not ended yet and the data is incomplete."
},
{
"code": null,
"e": 3726,
"s": 3644,
"text": "If we group MONTH and HOUR using groupby in Pandas, we get the following results."
},
{
"code": null,
"e": 3790,
"s": 3726,
"text": "larceny[larceny.YEAR == 2019].groupby([‘MONTH’, ‘HOUR’]).size()"
},
{
"code": null,
"e": 3941,
"s": 3790,
"text": "However, this is not helpful for us to read the data easily. To make it better, I used unstack, and this will turn the result in a more readable form."
},
{
"code": null,
"e": 4013,
"s": 3941,
"text": "larceny[larceny.YEAR==2018].groupby([‘MONTH’,’HOUR’]).size().unstack(0)"
},
{
"code": null,
"e": 4050,
"s": 4013,
"text": "Now, I want to visualize the result."
},
{
"code": null,
"e": 4300,
"s": 4050,
"text": "Since I am visualizing 12 months of data into 12 pieces of graphs, I want to use the facet plot. In Pandas, there is a parameter in plot called subplots. Initialize it to be True. I can also adjust the length and width of the graph by using figsize."
},
{
"code": null,
"e": 4424,
"s": 4300,
"text": "larceny[larceny.YEAR==2018].groupby([‘MONTH’,’HOUR’]).size().unstack(0).plot(subplots=True, kind = “bar”, figsize = (5, 30)"
},
{
"code": null,
"e": 4515,
"s": 4424,
"text": "Now, we have a complete visualization of the larceny incidents happened in Boston in 2018."
}
] |
How can I create MySQL stored procedure with OUT parameter? | To make it understand we are using the table named ‘student_info’ which have the following values −
mysql> Select * from student_info;
+------+---------+------------+------------+
| id | Name | Address | Subject |
+------+---------+------------+------------+
| 101 | YashPal | Amritsar | History |
| 105 | Gaurav | Jaipur | Literature |
| 110 | Rahul | Chandigarh | History |
| 125 | Raman | Shimla | Computers |
+------+---------+------------+------------+
4 rows in set (0.00 sec)
Now, with the help of the following query, we will create a stored procedure with OUT parameter which will count the total of a particular subject by providing the subject name as the parameter.
mysql> DELIMITER // ;
mysql> Create Procedure subjects (IN S_Subject VARCHAR(25), OUT total INT)
-> BEGIN
-> SELECT count(subject)
-> INTO total
-> FROM student_info
-> WHERE subject = S_subject;
-> END //
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
‘S-Subject’ is the IN parameter that is the number of subjects we want to count and ‘total’ is the OUT parameter that stores the number of subjects for a particular subject.
mysql> CALL subjects('Computers', @total);
Query OK, 1 row affected (0.02 sec)
mysql> Select @total;
+--------+
| @total |
+--------+
| 1 |
+--------+
1 row in set (0.01 sec)
mysql> CALL subjects('History', @total);
Query OK, 1 row affected (0.00 sec)
mysql> Select @total;
+--------+
| @total |
+--------+
| 2 |
+--------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "To make it understand we are using the table named ‘student_info’ which have the following values −"
},
{
"code": null,
"e": 1582,
"s": 1162,
"text": "mysql> Select * from student_info;\n+------+---------+------------+------------+\n| id | Name | Address | Subject |\n+------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 110 | Rahul | Chandigarh | History |\n| 125 | Raman | Shimla | Computers |\n+------+---------+------------+------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1777,
"s": 1582,
"text": "Now, with the help of the following query, we will create a stored procedure with OUT parameter which will count the total of a particular subject by providing the subject name as the parameter."
},
{
"code": null,
"e": 2058,
"s": 1777,
"text": "mysql> DELIMITER // ;\nmysql> Create Procedure subjects (IN S_Subject VARCHAR(25), OUT total INT)\n -> BEGIN\n -> SELECT count(subject)\n -> INTO total\n -> FROM student_info\n -> WHERE subject = S_subject;\n -> END //\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> DELIMITER ;"
},
{
"code": null,
"e": 2232,
"s": 2058,
"text": "‘S-Subject’ is the IN parameter that is the number of subjects we want to count and ‘total’ is the OUT parameter that stores the number of subjects for a particular subject."
},
{
"code": null,
"e": 2593,
"s": 2232,
"text": "mysql> CALL subjects('Computers', @total);\nQuery OK, 1 row affected (0.02 sec)\n\nmysql> Select @total;\n+--------+\n| @total |\n+--------+\n| 1 |\n+--------+\n1 row in set (0.01 sec)\n\nmysql> CALL subjects('History', @total);\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> Select @total;\n+--------+\n| @total |\n+--------+\n| 2 |\n+--------+\n1 row in set (0.00 sec)"
}
] |
JSTL - Core <fmt:setLocale> Tag | The <fmt:setLocale> tag is used to store the given locale in the locale configuration variable.
The <fmt:setLocale> tag has the following attributes −
Resource bundles contain locale-specific objects. Resource bundles contain key/value pairs. When your program needs a locale-specific resource, you keep all the keys common to all the locale but you can have translated values specific to locale. Resource bundles helps in providing content specific to locale.
A Java resource bundle file contains a series of key-to-string mappings. The method that we focus on involves creating compiled Java classes that extend the java.util.ListResourceBundle class. You must compile these class files and make them available to the classpath of your Web application.
Let us define a default resource bundle as follows −
package com.tutorialspoint;
import java.util.ListResourceBundle;
public class Example_En extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"count.one", "One"},
{"count.two", "Two"},
{"count.three", "Three"},
};
}
Let us now define one more resource bundle which we will use for Spanish Locale −
package com.tutorialspoint;
import java.util.ListResourceBundle;
public class Example_es_ES extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"count.one", "Uno"},
{"count.two", "Dos"},
{"count.three", "Tres"},
};
}
Let us compile the above classes Example.class and Example_es_ES.class and make them available in the CLASSPATH of your Web application. You can now use the following JSTL tags to display the three numbers as follows −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/fmt" prefix = "fmt" %>
<html>
<head>
<title>JSTL fmt:setLocale Tag</title>
</head>
<body>
<fmt:bundle basename = "com.tutorialspoint.Example">
<fmt:message key = "count.one"/><br/>
<fmt:message key = "count.two"/><br/>
<fmt:message key = "count.three"/><br/>
</fmt:bundle>
<!-- Change the Locale -->
<fmt:setLocale value = "es_ES"/>
<fmt:bundle basename = "com.tutorialspoint.Example">
<fmt:message key = "count.one"/><br/>
<fmt:message key = "count.two"/><br/>
<fmt:message key = "count.three"/><br/>
</fmt:bundle>
</body>
</html>
The above code will generate the following result −
One
Two
Three
Uno
Dos
Tres
Check <fmt:bundle> and <setBundle> tags to understand the complete concept.
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2335,
"s": 2239,
"text": "The <fmt:setLocale> tag is used to store the given locale in the locale configuration variable."
},
{
"code": null,
"e": 2390,
"s": 2335,
"text": "The <fmt:setLocale> tag has the following attributes −"
},
{
"code": null,
"e": 2700,
"s": 2390,
"text": "Resource bundles contain locale-specific objects. Resource bundles contain key/value pairs. When your program needs a locale-specific resource, you keep all the keys common to all the locale but you can have translated values specific to locale. Resource bundles helps in providing content specific to locale."
},
{
"code": null,
"e": 2994,
"s": 2700,
"text": "A Java resource bundle file contains a series of key-to-string mappings. The method that we focus on involves creating compiled Java classes that extend the java.util.ListResourceBundle class. You must compile these class files and make them available to the classpath of your Web application."
},
{
"code": null,
"e": 3047,
"s": 2994,
"text": "Let us define a default resource bundle as follows −"
},
{
"code": null,
"e": 3368,
"s": 3047,
"text": "package com.tutorialspoint;\n\nimport java.util.ListResourceBundle;\n\npublic class Example_En extends ListResourceBundle {\n public Object[][] getContents() {\n return contents;\n }\n static final Object[][] contents = {\n {\"count.one\", \"One\"},\n {\"count.two\", \"Two\"},\n {\"count.three\", \"Three\"},\n };\n}"
},
{
"code": null,
"e": 3450,
"s": 3368,
"text": "Let us now define one more resource bundle which we will use for Spanish Locale −"
},
{
"code": null,
"e": 3773,
"s": 3450,
"text": "package com.tutorialspoint;\n\nimport java.util.ListResourceBundle;\n\npublic class Example_es_ES extends ListResourceBundle {\n public Object[][] getContents() {\n return contents;\n }\n static final Object[][] contents = {\n {\"count.one\", \"Uno\"},\n {\"count.two\", \"Dos\"},\n {\"count.three\", \"Tres\"},\n };\n}"
},
{
"code": null,
"e": 3992,
"s": 3773,
"text": "Let us compile the above classes Example.class and Example_es_ES.class and make them available in the CLASSPATH of your Web application. You can now use the following JSTL tags to display the three numbers as follows −"
},
{
"code": null,
"e": 4752,
"s": 3992,
"text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/fmt\" prefix = \"fmt\" %>\n\n<html>\n <head>\n <title>JSTL fmt:setLocale Tag</title>\n </head>\n\n <body>\n <fmt:bundle basename = \"com.tutorialspoint.Example\">\n <fmt:message key = \"count.one\"/><br/>\n <fmt:message key = \"count.two\"/><br/>\n <fmt:message key = \"count.three\"/><br/>\n </fmt:bundle>\n\n <!-- Change the Locale -->\n <fmt:setLocale value = \"es_ES\"/>\n <fmt:bundle basename = \"com.tutorialspoint.Example\">\n <fmt:message key = \"count.one\"/><br/>\n <fmt:message key = \"count.two\"/><br/>\n <fmt:message key = \"count.three\"/><br/>\n </fmt:bundle>\n\n </body>\n</html>"
},
{
"code": null,
"e": 4804,
"s": 4752,
"text": "The above code will generate the following result −"
},
{
"code": null,
"e": 4834,
"s": 4804,
"text": "One \nTwo \nThree\nUno\nDos\nTres\n"
},
{
"code": null,
"e": 4910,
"s": 4834,
"text": "Check <fmt:bundle> and <setBundle> tags to understand the complete concept."
},
{
"code": null,
"e": 4945,
"s": 4910,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4960,
"s": 4945,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 4995,
"s": 4960,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 5010,
"s": 4995,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5045,
"s": 5010,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5059,
"s": 5045,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5094,
"s": 5059,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5110,
"s": 5094,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5143,
"s": 5110,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5159,
"s": 5143,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5193,
"s": 5159,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 5201,
"s": 5193,
"text": " Uplatz"
},
{
"code": null,
"e": 5208,
"s": 5201,
"text": " Print"
},
{
"code": null,
"e": 5219,
"s": 5208,
"text": " Add Notes"
}
] |
Comments in C/C++ - GeeksforGeeks | 23 Mar, 2021
A well-documented program is a good practice as a programmer. It makes a program more readable and error finding become easier. One important part of good documentation is Comments.
In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program
Comments are statements that are not executed by the compiler and interpreter.
In C/C++ there are two types of comments :
Single line commentMulti-line comment
Single line comment
Multi-line comment
Single line Comment
Represented as // double forward slash It is used to denote a single line comment. It applies comment to a single line only. It is referred to as C++-style comments as it is originally part of C++ programming. for example:
// single line comment
Example: This example goes same for C and C++ as the style of commenting remains same for both the language.
C
// C program to illustrate// use of multi-line comment#include <stdio.h>int main(void){ // Single line Welcome user comment printf("Welcome to GeeksforGeeks"); return 0;}
Welcome to GeeksforGeeks
Multi-line comment
Represented as /* any_text */ start with forward slash and asterisk (/*) and end with asterisk and forward slash (*/). It is used to denote multi-line comment. It can apply comment to more than a single line. It is referred to as C-Style comment as it was introduced in C programming.
/*Comment starts
continues
continues
.
.
.
Comment ends*/
Example: This example goes same for C and C++ as the style of commenting remains same for both the language.
C
/* C program to illustrateuse ofmulti-line comment */#include <stdio.h>int main(void){ /* Multi-line Welcome user comment written to demonstrate comments in C/C++ */ printf("Welcome to GeeksforGeeks"); return 0;}
Welcome to GeeksforGeeks
Comment at End of Code Line
You can also create a comment that displays at the end of a line of code. But generally its a better practice to put the comment before the line of code. Example: This example goes same for C and C++ as the style of commenting remains same for both the language.
int age; // age of the person
When and Why to use Comments in programming?
A person reading a large code will be bemused if comments are not provided about details of the program.Comments are a way to make a code more readable by providing more description.Comments can include a description of an algorithm to make code understandable.Comments can be helpful for one’s own self too if code is to be reused after a long gap.
A person reading a large code will be bemused if comments are not provided about details of the program.
Comments are a way to make a code more readable by providing more description.
Comments can include a description of an algorithm to make code understandable.
Comments can be helpful for one’s own self too if code is to be reused after a long gap.
sangai260
CBSE - Class 11
Picked
school-programming
C Language
School Programming
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
Python Dictionary
Reverse a string in Java
Inheritance in C++
C++ Classes and Objects
Constructors in C++ | [
{
"code": null,
"e": 24104,
"s": 24076,
"text": "\n23 Mar, 2021"
},
{
"code": null,
"e": 24288,
"s": 24104,
"text": "A well-documented program is a good practice as a programmer. It makes a program more readable and error finding become easier. One important part of good documentation is Comments. "
},
{
"code": null,
"e": 24415,
"s": 24288,
"text": "In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program"
},
{
"code": null,
"e": 24494,
"s": 24415,
"text": "Comments are statements that are not executed by the compiler and interpreter."
},
{
"code": null,
"e": 24539,
"s": 24494,
"text": "In C/C++ there are two types of comments : "
},
{
"code": null,
"e": 24577,
"s": 24539,
"text": "Single line commentMulti-line comment"
},
{
"code": null,
"e": 24597,
"s": 24577,
"text": "Single line comment"
},
{
"code": null,
"e": 24616,
"s": 24597,
"text": "Multi-line comment"
},
{
"code": null,
"e": 24640,
"s": 24620,
"text": "Single line Comment"
},
{
"code": null,
"e": 24865,
"s": 24640,
"text": "Represented as // double forward slash It is used to denote a single line comment. It applies comment to a single line only. It is referred to as C++-style comments as it is originally part of C++ programming. for example: "
},
{
"code": null,
"e": 24888,
"s": 24865,
"text": "// single line comment"
},
{
"code": null,
"e": 24999,
"s": 24888,
"text": "Example: This example goes same for C and C++ as the style of commenting remains same for both the language. "
},
{
"code": null,
"e": 25001,
"s": 24999,
"text": "C"
},
{
"code": "// C program to illustrate// use of multi-line comment#include <stdio.h>int main(void){ // Single line Welcome user comment printf(\"Welcome to GeeksforGeeks\"); return 0;}",
"e": 25182,
"s": 25001,
"text": null
},
{
"code": null,
"e": 25207,
"s": 25182,
"text": "Welcome to GeeksforGeeks"
},
{
"code": null,
"e": 25228,
"s": 25209,
"text": "Multi-line comment"
},
{
"code": null,
"e": 25514,
"s": 25228,
"text": "Represented as /* any_text */ start with forward slash and asterisk (/*) and end with asterisk and forward slash (*/). It is used to denote multi-line comment. It can apply comment to more than a single line. It is referred to as C-Style comment as it was introduced in C programming. "
},
{
"code": null,
"e": 25572,
"s": 25514,
"text": "/*Comment starts\ncontinues\ncontinues\n.\n.\n.\nComment ends*/"
},
{
"code": null,
"e": 25683,
"s": 25572,
"text": "Example: This example goes same for C and C++ as the style of commenting remains same for both the language. "
},
{
"code": null,
"e": 25685,
"s": 25683,
"text": "C"
},
{
"code": "/* C program to illustrateuse ofmulti-line comment */#include <stdio.h>int main(void){ /* Multi-line Welcome user comment written to demonstrate comments in C/C++ */ printf(\"Welcome to GeeksforGeeks\"); return 0;}",
"e": 25914,
"s": 25685,
"text": null
},
{
"code": null,
"e": 25939,
"s": 25914,
"text": "Welcome to GeeksforGeeks"
},
{
"code": null,
"e": 25969,
"s": 25941,
"text": "Comment at End of Code Line"
},
{
"code": null,
"e": 26234,
"s": 25969,
"text": "You can also create a comment that displays at the end of a line of code. But generally its a better practice to put the comment before the line of code. Example: This example goes same for C and C++ as the style of commenting remains same for both the language. "
},
{
"code": null,
"e": 26265,
"s": 26234,
"text": " int age; // age of the person"
},
{
"code": null,
"e": 26312,
"s": 26267,
"text": "When and Why to use Comments in programming?"
},
{
"code": null,
"e": 26664,
"s": 26314,
"text": "A person reading a large code will be bemused if comments are not provided about details of the program.Comments are a way to make a code more readable by providing more description.Comments can include a description of an algorithm to make code understandable.Comments can be helpful for one’s own self too if code is to be reused after a long gap."
},
{
"code": null,
"e": 26769,
"s": 26664,
"text": "A person reading a large code will be bemused if comments are not provided about details of the program."
},
{
"code": null,
"e": 26848,
"s": 26769,
"text": "Comments are a way to make a code more readable by providing more description."
},
{
"code": null,
"e": 26928,
"s": 26848,
"text": "Comments can include a description of an algorithm to make code understandable."
},
{
"code": null,
"e": 27017,
"s": 26928,
"text": "Comments can be helpful for one’s own self too if code is to be reused after a long gap."
},
{
"code": null,
"e": 27029,
"s": 27019,
"text": "sangai260"
},
{
"code": null,
"e": 27045,
"s": 27029,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 27052,
"s": 27045,
"text": "Picked"
},
{
"code": null,
"e": 27071,
"s": 27052,
"text": "school-programming"
},
{
"code": null,
"e": 27082,
"s": 27071,
"text": "C Language"
},
{
"code": null,
"e": 27101,
"s": 27082,
"text": "School Programming"
},
{
"code": null,
"e": 27199,
"s": 27101,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27208,
"s": 27199,
"text": "Comments"
},
{
"code": null,
"e": 27221,
"s": 27208,
"text": "Old Comments"
},
{
"code": null,
"e": 27249,
"s": 27221,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27261,
"s": 27249,
"text": "fork() in C"
},
{
"code": null,
"e": 27293,
"s": 27261,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 27310,
"s": 27293,
"text": "Substring in C++"
},
{
"code": null,
"e": 27332,
"s": 27310,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27350,
"s": 27332,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27375,
"s": 27350,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27394,
"s": 27375,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27418,
"s": 27394,
"text": "C++ Classes and Objects"
}
] |
Longest subarray with sum divisible by K | Practice | GeeksforGeeks | Given an array containing N integers and a positive integer K, find the length of the longest sub array with sum of the elements divisible by the given value K.
Example 1:
Input:
A[] = {2, 7, 6, 1, 4, 5}
K = 3
Output: 4
Explanation:The subarray is {7, 6, 1, 4}
with sum 18, which is divisible by 3.
Example 2:
Input:
A[] = {-2, 2, -5, 12, -11, -1, 7}
K = 3
Output: 5
Explanation:
The subarray is {2,-5,12,-11,-1} with
sum -3, which is divisible by 3.
Your Task:
The input is already taken care of by the driver code. You only need to complete the function longSubarrWthSumDivByK() that takes an array (arr), sizeOfArray (n), positive integer K, and return the length of the longest subarray which has sum divisible by K. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).​
Constraints:
1<=N,K<=106
-105<=A[i]<=105
+2
neeramrutia2 months ago
HashMap<Integer,Integer> hm=new HashMap<>(); int sum=0; hm.put(0,-1); int i; int rem; int maxl=0; for(i=0;i<n;i++) { sum=sum+a[i]; rem=sum%k; if(rem<0) rem=rem+k; if(hm.containsKey(rem)) { maxl=Math.max(maxl,i-hm.get(rem)); } else { hm.put(rem,i); } } return maxl;
0
sy9924552 months ago
int longSubarrWthSumDivByK(int arr[], int n, int k)
{
HashMap<Integer,Integer> map = new HashMap<>();
int sum = 0;
int rem = 0;
int mLen = 0;
map.put(0 , -1);
for(int i=0;i<n;i++){
sum+=arr[i];
rem = sum % k;
if(rem < 0) rem+=k;
if(map.containsKey(rem)){
mLen = Math.max(mLen , i - map.get(rem));
}else{
map.put(rem , i);
}
}
return mLen;
}
0
sy992455
This comment was deleted.
0
akkeshri140420012 months ago
int longSubarrWthSumDivByK(int arr[], int n, int k)
{
// Complete the function
unordered_map<int,int>m;
m[0]=-1;
int maxi=0;
int sum=0;
for(int i=0;i<n;i++){
sum+=arr[i];
int rem=sum%k;
if(rem<0){
rem+=k;
}
if(m.find(rem)!=m.end()){
int len=i-m[rem];
if(len>maxi){
maxi=len;
}
}
else if(m.find(rem)==m.end()){
m[rem]=i;
}
}
return maxi;
}
0
asissrmakumar6663 months ago
JAVA || prefixSum || Total Time Taken: 0.9/5.4
class Solution{
int longSubarrWthSumDivByK(int arr[], int n, int k)
{
HashMap<Integer,Integer> hs=new HashMap<>();
hs.put(0,-1);
int pS=0,max=0;
for(int i=0;i<arr.length;i++){
pS=((pS+arr[i])%k+k)%k;
if(hs.get(pS)!=null){
max=Math.max(max,i-hs.get(pS));
}
else hs.put(pS,i);
}
return max;
}
}
0
hrithikrsgupta3 months ago
This mod type of questions have so many edge cases :/
0
aloksinghbais023 months ago
C++ solution having time complexity O(N) and space complexity as O(N) is as follows :-
Note :- Similar question in which we find total subarrays having sum divisible by k.
Execution Time :- 0.5 / 1.8 sec
int longSubarrWthSumDivByK(int arr[], int n, int k){ unordered_map<int,int> firstLastInd; unordered_map<int,bool> mp; int len = 0; int sum = 0; mp[sum] = true; firstLastInd[0] = 0; for(int i=0; i<n; i++){ sum += arr[i]; int rem = sum % k; if(rem < 0) rem += k; if(mp[rem]){ len = max(len,(i - firstLastInd[rem] + 1)); } mp[rem] = true; if(firstLastInd[rem] == 0 && rem) firstLastInd[rem] = i+1; } return (len);}
0
soumo2k154 months ago
int longSubarrWthSumDivByK(int a[], int n, int k){ map<int,int>m; int sum=0,rem=0,ans=0; for(int i=0;i<n;i++){ sum+=a[i]; rem=sum%k; if(rem<0)rem+=k; if(!rem)ans=i+1; if(m.find(rem)==m.end())m[rem]=i; if(m.find(rem)!=m.end())ans=max(ans,i-m[rem]); } return ans;}
0
rohanpandey7494 months ago
C++ solution:
class Solution{
public:
int longSubarrWthSumDivByK(int arr[], int n, int k)
{
// Complete the function
unordered_map<int,int>mp;
mp[0]=-1;
int sum=0, answer=0;
int cur;
for(int i=0;i<n;i++){
sum+=arr[i];
cur=((sum%k)+k)%k;
if(mp.find(cur)!=mp.end()){
answer=max(answer,i-mp[cur]);
}
else{
mp[cur]=i;
}
}
return answer;
}
};
0
rajput91894 months ago
class Solution{
public:
int longSubarrWthSumDivByK(int arr[], int n, int k)
{
unordered_map<int,int>mp;
mp.insert({0,-1});
int prefix=0;
int ans=0;
for(int i=0;i<n;++i)
{
prefix+=arr[i];
int rem=prefix%k;
if(rem<0)
rem+=k;
if(mp.find(rem)!=mp.end())
{
ans=max(ans,i-mp[rem]);
}
else
{
mp.insert({rem,i});
}
}
return ans;
}
};
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": 399,
"s": 238,
"text": "Given an array containing N integers and a positive integer K, find the length of the longest sub array with sum of the elements divisible by the given value K."
},
{
"code": null,
"e": 410,
"s": 399,
"text": "Example 1:"
},
{
"code": null,
"e": 537,
"s": 410,
"text": "Input:\nA[] = {2, 7, 6, 1, 4, 5}\nK = 3\nOutput: 4\nExplanation:The subarray is {7, 6, 1, 4}\nwith sum 18, which is divisible by 3."
},
{
"code": null,
"e": 548,
"s": 537,
"text": "Example 2:"
},
{
"code": null,
"e": 689,
"s": 548,
"text": "Input:\nA[] = {-2, 2, -5, 12, -11, -1, 7}\nK = 3\nOutput: 5\nExplanation:\nThe subarray is {2,-5,12,-11,-1} with\nsum -3, which is divisible by 3."
},
{
"code": null,
"e": 1074,
"s": 691,
"text": "Your Task:\nThe input is already taken care of by the driver code. You only need to complete the function longSubarrWthSumDivByK() that takes an array (arr), sizeOfArray (n), positive integer K, and return the length of the longest subarray which has sum divisible by K. The driver code takes care of the printing.\n\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).​"
},
{
"code": null,
"e": 1117,
"s": 1074,
"text": "Constraints:\n1<=N,K<=106\n-105<=A[i]<=105\n "
},
{
"code": null,
"e": 1120,
"s": 1117,
"text": "+2"
},
{
"code": null,
"e": 1144,
"s": 1120,
"text": "neeramrutia2 months ago"
},
{
"code": null,
"e": 1571,
"s": 1144,
"text": " HashMap<Integer,Integer> hm=new HashMap<>(); int sum=0; hm.put(0,-1); int i; int rem; int maxl=0; for(i=0;i<n;i++) { sum=sum+a[i]; rem=sum%k; if(rem<0) rem=rem+k; if(hm.containsKey(rem)) { maxl=Math.max(maxl,i-hm.get(rem)); } else { hm.put(rem,i); } } return maxl;"
},
{
"code": null,
"e": 1573,
"s": 1571,
"text": "0"
},
{
"code": null,
"e": 1594,
"s": 1573,
"text": "sy9924552 months ago"
},
{
"code": null,
"e": 2113,
"s": 1594,
"text": " int longSubarrWthSumDivByK(int arr[], int n, int k)\n {\n HashMap<Integer,Integer> map = new HashMap<>();\n int sum = 0;\n int rem = 0;\n int mLen = 0;\n map.put(0 , -1);\n for(int i=0;i<n;i++){\n sum+=arr[i];\n rem = sum % k;\n if(rem < 0) rem+=k;\n if(map.containsKey(rem)){\n mLen = Math.max(mLen , i - map.get(rem));\n }else{\n map.put(rem , i);\n }\n }\n return mLen;\n }"
},
{
"code": null,
"e": 2115,
"s": 2113,
"text": "0"
},
{
"code": null,
"e": 2124,
"s": 2115,
"text": "sy992455"
},
{
"code": null,
"e": 2150,
"s": 2124,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2152,
"s": 2150,
"text": "0"
},
{
"code": null,
"e": 2181,
"s": 2152,
"text": "akkeshri140420012 months ago"
},
{
"code": null,
"e": 2697,
"s": 2181,
"text": "int longSubarrWthSumDivByK(int arr[], int n, int k)\n{\n // Complete the function\n unordered_map<int,int>m;\n m[0]=-1;\n int maxi=0;\n int sum=0;\n for(int i=0;i<n;i++){\n sum+=arr[i];\n int rem=sum%k;\n if(rem<0){\n rem+=k;\n }\n if(m.find(rem)!=m.end()){\n int len=i-m[rem];\n if(len>maxi){\n maxi=len;\n }\n }\n else if(m.find(rem)==m.end()){\n m[rem]=i;\n }\n }\n return maxi;\n \n}"
},
{
"code": null,
"e": 2699,
"s": 2697,
"text": "0"
},
{
"code": null,
"e": 2728,
"s": 2699,
"text": "asissrmakumar6663 months ago"
},
{
"code": null,
"e": 2775,
"s": 2728,
"text": "JAVA || prefixSum || Total Time Taken: 0.9/5.4"
},
{
"code": null,
"e": 3212,
"s": 2775,
"text": "class Solution{\n int longSubarrWthSumDivByK(int arr[], int n, int k)\n {\n HashMap<Integer,Integer> hs=new HashMap<>();\n hs.put(0,-1);\n int pS=0,max=0;\n for(int i=0;i<arr.length;i++){\n pS=((pS+arr[i])%k+k)%k;\n \n if(hs.get(pS)!=null){\n max=Math.max(max,i-hs.get(pS));\n }\n else hs.put(pS,i);\n }\n return max;\n \n }\n \n}"
},
{
"code": null,
"e": 3216,
"s": 3214,
"text": "0"
},
{
"code": null,
"e": 3243,
"s": 3216,
"text": "hrithikrsgupta3 months ago"
},
{
"code": null,
"e": 3297,
"s": 3243,
"text": "This mod type of questions have so many edge cases :/"
},
{
"code": null,
"e": 3299,
"s": 3297,
"text": "0"
},
{
"code": null,
"e": 3327,
"s": 3299,
"text": "aloksinghbais023 months ago"
},
{
"code": null,
"e": 3414,
"s": 3327,
"text": "C++ solution having time complexity O(N) and space complexity as O(N) is as follows :-"
},
{
"code": null,
"e": 3499,
"s": 3414,
"text": "Note :- Similar question in which we find total subarrays having sum divisible by k."
},
{
"code": null,
"e": 3533,
"s": 3501,
"text": "Execution Time :- 0.5 / 1.8 sec"
},
{
"code": null,
"e": 4079,
"s": 3535,
"text": "int longSubarrWthSumDivByK(int arr[], int n, int k){ unordered_map<int,int> firstLastInd; unordered_map<int,bool> mp; int len = 0; int sum = 0; mp[sum] = true; firstLastInd[0] = 0; for(int i=0; i<n; i++){ sum += arr[i]; int rem = sum % k; if(rem < 0) rem += k; if(mp[rem]){ len = max(len,(i - firstLastInd[rem] + 1)); } mp[rem] = true; if(firstLastInd[rem] == 0 && rem) firstLastInd[rem] = i+1; } return (len);}"
},
{
"code": null,
"e": 4081,
"s": 4079,
"text": "0"
},
{
"code": null,
"e": 4103,
"s": 4081,
"text": "soumo2k154 months ago"
},
{
"code": null,
"e": 4423,
"s": 4103,
"text": "int longSubarrWthSumDivByK(int a[], int n, int k){ map<int,int>m; int sum=0,rem=0,ans=0; for(int i=0;i<n;i++){ sum+=a[i]; rem=sum%k; if(rem<0)rem+=k; if(!rem)ans=i+1; if(m.find(rem)==m.end())m[rem]=i; if(m.find(rem)!=m.end())ans=max(ans,i-m[rem]); } return ans;}"
},
{
"code": null,
"e": 4425,
"s": 4423,
"text": "0"
},
{
"code": null,
"e": 4452,
"s": 4425,
"text": "rohanpandey7494 months ago"
},
{
"code": null,
"e": 4466,
"s": 4452,
"text": "C++ solution:"
},
{
"code": null,
"e": 4915,
"s": 4466,
"text": "class Solution{\npublic:\t\n\tint longSubarrWthSumDivByK(int arr[], int n, int k)\n\t{\n\t // Complete the function\n\t unordered_map<int,int>mp;\n\t mp[0]=-1;\n\t int sum=0, answer=0;\n\t int cur;\n\t for(int i=0;i<n;i++){\n\t sum+=arr[i];\n\t cur=((sum%k)+k)%k;\n\t \n\t if(mp.find(cur)!=mp.end()){\n\t answer=max(answer,i-mp[cur]);\n\t }\n\t else{\n\t mp[cur]=i;\n\t }\n\t }\n\t return answer;\n\t}\n};"
},
{
"code": null,
"e": 4917,
"s": 4915,
"text": "0"
},
{
"code": null,
"e": 4940,
"s": 4917,
"text": "rajput91894 months ago"
},
{
"code": null,
"e": 5455,
"s": 4940,
"text": "\nclass Solution{\npublic:\t\n\tint longSubarrWthSumDivByK(int arr[], int n, int k)\n\t{\n\t unordered_map<int,int>mp;\n\t mp.insert({0,-1});\n\t int prefix=0;\n\t int ans=0;\n\t for(int i=0;i<n;++i)\n\t {\n\t prefix+=arr[i];\n\t int rem=prefix%k;\n\t \n\t if(rem<0)\n\t rem+=k;\n\t \n\t if(mp.find(rem)!=mp.end())\n\t {\n\t ans=max(ans,i-mp[rem]);\n\t }\n\t else\n\t {\n\t mp.insert({rem,i});\n\t }\n\t }\n\t return ans;\n\t}\n};"
},
{
"code": null,
"e": 5601,
"s": 5455,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5637,
"s": 5601,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5647,
"s": 5637,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5657,
"s": 5647,
"text": "\nContest\n"
},
{
"code": null,
"e": 5720,
"s": 5657,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5868,
"s": 5720,
"text": "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."
},
{
"code": null,
"e": 6076,
"s": 5868,
"text": "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."
},
{
"code": null,
"e": 6182,
"s": 6076,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Entity Framework - DbContext | The Entity Framework enables you to query, insert, update, and delete data, using Common Language Runtime (CLR) objects which is known as entities. The Entity Framework maps the entities and relationships that are defined in your model to a database. It also provides facilities to −
Materialize data returned from the database as entity objects
Track changes that were made to the objects
Handle concurrency
Propagate object changes back to the database
Bind objects to controls
The primary class that is responsible for interacting with data as objects is System.Data.Entity.DbContext. The DbContext API is not released as part of the .NET Framework. In order to be more flexible and frequent with releasing new features to Code First and the DbContext API, the Entity Framework team distributes EntityFramework.dll through Microsoft’s NuGet distribution feature.
NuGet allows you to add references to your .NET projects by pulling the relevant DLLs directly into your project from the Web.
NuGet allows you to add references to your .NET projects by pulling the relevant DLLs directly into your project from the Web.
A Visual Studio extension called the Library Package Manager provides an easy way to pull the appropriate assembly from the Web into your projects.
A Visual Studio extension called the Library Package Manager provides an easy way to pull the appropriate assembly from the Web into your projects.
DbContext API is mostly targeted at simplifying your interaction with Entity Framework.
DbContext API is mostly targeted at simplifying your interaction with Entity Framework.
It also reduces the number of methods and properties you need to access commonly used tasks.
It also reduces the number of methods and properties you need to access commonly used tasks.
In previous versions of Entity Framework, these tasks were often complicated to discover and code.
In previous versions of Entity Framework, these tasks were often complicated to discover and code.
The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database.
The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database.
The recommended way to work with context is to define a class that derives from DbContext and exposes DbSet properties that represent collections of the specified entities in the context. If you are working with the EF Designer, the context will be generated for you. If you are working with Code First, you will typically write the context yourself.
The following code is a simple example which shows that UniContext is derived from DbContext.
You can use automatic properties with DbSet such as getter and setter.
You can use automatic properties with DbSet such as getter and setter.
It also makes much cleaner code, but you aren’t required to use it for the purpose of creating a DbSet when you have no other logic to apply.
It also makes much cleaner code, but you aren’t required to use it for the purpose of creating a DbSet when you have no other logic to apply.
public class UniContext : DbContext {
public UniContext() : base("UniContext") { }
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
}
Previously, EDM used to generate context classes that were derived from the ObjectContext class.
Previously, EDM used to generate context classes that were derived from the ObjectContext class.
Working with ObjectContext was a little complex.
Working with ObjectContext was a little complex.
DbContext is a wrapper around ObjectContext which is actually similar to ObjectContext and is useful and easy in all the development models such Code First, Model First and Database First.
DbContext is a wrapper around ObjectContext which is actually similar to ObjectContext and is useful and easy in all the development models such Code First, Model First and Database First.
There are three types of queries you can use such as −
Adding a new entity.
Changing or updating the property values of an existing entity.
Deleting an existing entity.
Adding a new object with Entity Framework is as simple as constructing a new instance of your object and registering it using the Add method on DbSet. The following code is for when you want to add a new student to database.
private static void AddStudent() {
using (var context = new UniContext()) {
var student = new Student {
LastName = "Khan",
FirstMidName = "Ali",
EnrollmentDate = DateTime.Parse("2005-09-01")
};
context.Students.Add(student);
context.SaveChanges();
}
}
Changing existing objects is as simple as updating the value assigned to the property(s) you want changed and calling SaveChanges. In the following code, the last name of Ali has been changed from Khan to Aslam.
private static void AddStudent() {
private static void ChangeStudent() {
using (var context = new UniContext()) {
var student = (from d in context.Students
where d.FirstMidName == "Ali" select d).Single();
student.LastName = "Aslam";
context.SaveChanges();
}
}
}
To delete an entity using Entity Framework, you use the Remove method on DbSet. Remove works for both existing and newly added entities. Calling Remove on an entity that has been added but not yet saved to the database will cancel the addition of the entity. The entity is removed from the change tracker and is no longer tracked by the DbContext. Calling Remove on an existing entity that is being change-tracked will register the entity for deletion the next time SaveChanges is called. The following example shows an instance where the student is removed from the database whose first name is Ali.
private static void DeleteStudent() {
using (var context = new UniContext()) {
var bay = (from d in context.Students where d.FirstMidName == "Ali" select d).Single();
context.Students.Remove(bay);
context.SaveChanges();
}
}
19 Lectures
5 hours
Trevoir Williams
33 Lectures
3.5 hours
Nilay Mehta
21 Lectures
2.5 hours
TELCOMA Global
89 Lectures
7.5 hours
Mustafa Radaideh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3316,
"s": 3032,
"text": "The Entity Framework enables you to query, insert, update, and delete data, using Common Language Runtime (CLR) objects which is known as entities. The Entity Framework maps the entities and relationships that are defined in your model to a database. It also provides facilities to −"
},
{
"code": null,
"e": 3378,
"s": 3316,
"text": "Materialize data returned from the database as entity objects"
},
{
"code": null,
"e": 3423,
"s": 3378,
"text": "Track changes that were made to the objects "
},
{
"code": null,
"e": 3442,
"s": 3423,
"text": "Handle concurrency"
},
{
"code": null,
"e": 3488,
"s": 3442,
"text": "Propagate object changes back to the database"
},
{
"code": null,
"e": 3513,
"s": 3488,
"text": "Bind objects to controls"
},
{
"code": null,
"e": 3899,
"s": 3513,
"text": "The primary class that is responsible for interacting with data as objects is System.Data.Entity.DbContext. The DbContext API is not released as part of the .NET Framework. In order to be more flexible and frequent with releasing new features to Code First and the DbContext API, the Entity Framework team distributes EntityFramework.dll through Microsoft’s NuGet distribution feature."
},
{
"code": null,
"e": 4026,
"s": 3899,
"text": "NuGet allows you to add references to your .NET projects by pulling the relevant DLLs directly into your project from the Web."
},
{
"code": null,
"e": 4153,
"s": 4026,
"text": "NuGet allows you to add references to your .NET projects by pulling the relevant DLLs directly into your project from the Web."
},
{
"code": null,
"e": 4301,
"s": 4153,
"text": "A Visual Studio extension called the Library Package Manager provides an easy way to pull the appropriate assembly from the Web into your projects."
},
{
"code": null,
"e": 4449,
"s": 4301,
"text": "A Visual Studio extension called the Library Package Manager provides an easy way to pull the appropriate assembly from the Web into your projects."
},
{
"code": null,
"e": 4537,
"s": 4449,
"text": "DbContext API is mostly targeted at simplifying your interaction with Entity Framework."
},
{
"code": null,
"e": 4625,
"s": 4537,
"text": "DbContext API is mostly targeted at simplifying your interaction with Entity Framework."
},
{
"code": null,
"e": 4718,
"s": 4625,
"text": "It also reduces the number of methods and properties you need to access commonly used tasks."
},
{
"code": null,
"e": 4811,
"s": 4718,
"text": "It also reduces the number of methods and properties you need to access commonly used tasks."
},
{
"code": null,
"e": 4910,
"s": 4811,
"text": "In previous versions of Entity Framework, these tasks were often complicated to discover and code."
},
{
"code": null,
"e": 5009,
"s": 4910,
"text": "In previous versions of Entity Framework, these tasks were often complicated to discover and code."
},
{
"code": null,
"e": 5186,
"s": 5009,
"text": "The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database."
},
{
"code": null,
"e": 5363,
"s": 5186,
"text": "The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database."
},
{
"code": null,
"e": 5714,
"s": 5363,
"text": "The recommended way to work with context is to define a class that derives from DbContext and exposes DbSet properties that represent collections of the specified entities in the context. If you are working with the EF Designer, the context will be generated for you. If you are working with Code First, you will typically write the context yourself."
},
{
"code": null,
"e": 5808,
"s": 5714,
"text": "The following code is a simple example which shows that UniContext is derived from DbContext."
},
{
"code": null,
"e": 5879,
"s": 5808,
"text": "You can use automatic properties with DbSet such as getter and setter."
},
{
"code": null,
"e": 5950,
"s": 5879,
"text": "You can use automatic properties with DbSet such as getter and setter."
},
{
"code": null,
"e": 6092,
"s": 5950,
"text": "It also makes much cleaner code, but you aren’t required to use it for the purpose of creating a DbSet when you have no other logic to apply."
},
{
"code": null,
"e": 6234,
"s": 6092,
"text": "It also makes much cleaner code, but you aren’t required to use it for the purpose of creating a DbSet when you have no other logic to apply."
},
{
"code": null,
"e": 6470,
"s": 6234,
"text": "public class UniContext : DbContext {\n public UniContext() : base(\"UniContext\") { }\n public DbSet<Student> Students { get; set; }\n public DbSet<Enrollment> Enrollments { get; set; }\n public DbSet<Course> Courses { get; set; }\n}"
},
{
"code": null,
"e": 6567,
"s": 6470,
"text": "Previously, EDM used to generate context classes that were derived from the ObjectContext class."
},
{
"code": null,
"e": 6664,
"s": 6567,
"text": "Previously, EDM used to generate context classes that were derived from the ObjectContext class."
},
{
"code": null,
"e": 6713,
"s": 6664,
"text": "Working with ObjectContext was a little complex."
},
{
"code": null,
"e": 6762,
"s": 6713,
"text": "Working with ObjectContext was a little complex."
},
{
"code": null,
"e": 6951,
"s": 6762,
"text": "DbContext is a wrapper around ObjectContext which is actually similar to ObjectContext and is useful and easy in all the development models such Code First, Model First and Database First."
},
{
"code": null,
"e": 7140,
"s": 6951,
"text": "DbContext is a wrapper around ObjectContext which is actually similar to ObjectContext and is useful and easy in all the development models such Code First, Model First and Database First."
},
{
"code": null,
"e": 7195,
"s": 7140,
"text": "There are three types of queries you can use such as −"
},
{
"code": null,
"e": 7216,
"s": 7195,
"text": "Adding a new entity."
},
{
"code": null,
"e": 7280,
"s": 7216,
"text": "Changing or updating the property values of an existing entity."
},
{
"code": null,
"e": 7309,
"s": 7280,
"text": "Deleting an existing entity."
},
{
"code": null,
"e": 7534,
"s": 7309,
"text": "Adding a new object with Entity Framework is as simple as constructing a new instance of your object and registering it using the Add method on DbSet. The following code is for when you want to add a new student to database."
},
{
"code": null,
"e": 7851,
"s": 7534,
"text": "private static void AddStudent() {\n\n using (var context = new UniContext()) {\n\n var student = new Student {\n LastName = \"Khan\", \n FirstMidName = \"Ali\", \n EnrollmentDate = DateTime.Parse(\"2005-09-01\") \n };\n\n context.Students.Add(student); \n context.SaveChanges();\n\n }\n}"
},
{
"code": null,
"e": 8063,
"s": 7851,
"text": "Changing existing objects is as simple as updating the value assigned to the property(s) you want changed and calling SaveChanges. In the following code, the last name of Ali has been changed from Khan to Aslam."
},
{
"code": null,
"e": 8387,
"s": 8063,
"text": "private static void AddStudent() {\n\n private static void ChangeStudent() {\n\n using (var context = new UniContext()) {\n\n var student = (from d in context.Students\n where d.FirstMidName == \"Ali\" select d).Single();\n student.LastName = \"Aslam\";\n context.SaveChanges();\n\n }\n }\n}"
},
{
"code": null,
"e": 8988,
"s": 8387,
"text": "To delete an entity using Entity Framework, you use the Remove method on DbSet. Remove works for both existing and newly added entities. Calling Remove on an entity that has been added but not yet saved to the database will cancel the addition of the entity. The entity is removed from the change tracker and is no longer tracked by the DbContext. Calling Remove on an existing entity that is being change-tracked will register the entity for deletion the next time SaveChanges is called. The following example shows an instance where the student is removed from the database whose first name is Ali."
},
{
"code": null,
"e": 9237,
"s": 8988,
"text": "private static void DeleteStudent() {\n\n using (var context = new UniContext()) {\n var bay = (from d in context.Students where d.FirstMidName == \"Ali\" select d).Single();\n context.Students.Remove(bay);\n context.SaveChanges();\n }\n}"
},
{
"code": null,
"e": 9270,
"s": 9237,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9288,
"s": 9270,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 9323,
"s": 9288,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9336,
"s": 9323,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 9371,
"s": 9336,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9387,
"s": 9371,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 9422,
"s": 9387,
"text": "\n 89 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9440,
"s": 9422,
"text": " Mustafa Radaideh"
},
{
"code": null,
"e": 9447,
"s": 9440,
"text": " Print"
},
{
"code": null,
"e": 9458,
"s": 9447,
"text": " Add Notes"
}
] |
Minimum sum of two integers whose product is strictly greater than N - GeeksforGeeks | 23 Apr, 2021
Given an integer N, the task is to find two integers with minimum possible sum such that their product is strictly greater than N.
Examples:
Input: N = 10Output: 7Explanation: The integers are 3 and 4. Their product is 3 × 4 = 12, which is greater than N.
Input: N = 1Output: 3Explanation: The integers are 1 and 2. Their product is 1 × 2 = 2, which is greater than N.
Naive Approach: Let the required numbers be A and B. The idea is based on the observation that in order to minimize their sum A should be the smallest number greater than √N. Once A is found, B will be equal to the smallest number for which A×B > N, which can be found linearly.
Time Complexity: O(√N)Auxiliary Space: O(1)
Efficient Approach: The above solution can be optimized by using Binary Search to find A and B. Follow the steps below to solve the problem:
Initialize two variables low = 0 and high = 109.
Iterate until (high – low) is greater than 1 and do the following:Find the value of middle-range mid as (low + high)/2.Now, compare √N with the middle element mid, and if √N is less than or equal to the middle element, then high as mid.Else, update low as mid.
Find the value of middle-range mid as (low + high)/2.
Now, compare √N with the middle element mid, and if √N is less than or equal to the middle element, then high as mid.
Else, update low as mid.
After all the above steps set A = high.
Repeat the same procedure to find B such that A×B > N.
After the above steps, print the sum of A and B as the result.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nvoid minSum(int N){ // Initialise low as 0 and // high as 1e9 ll low = 0, high = 1e9; // Iterate to find the first number while (low + 1 < high) { // Find the middle value ll mid = low + (high - low) / 2; // If mid^2 is greater than // equal to A, then update // high to mid if (mid * mid >= N) { high = mid; } // Otherwise update low else { low = mid; } } // Store the first number ll first = high; // Again, set low as 0 and // high as 1e9 low = 0; high = 1e9; // Iterate to find the second number while (low + 1 < high) { // Find the middle value ll mid = low + (high - low) / 2; // If first number * mid is // greater than N then update // high to mid if (first * mid > N) { high = mid; } // Else, update low to mid else { low = mid; } } // Store the second number ll second = high; // Print the result cout << first + second;} // Driver Codeint main(){ int N = 10; // Function Call minSum(N); return 0;}
// Java program for the above approachimport java.io.*; class GFG{ // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nstatic void minSum(int N){ // Initialise low as 0 and // high as 1e9 long low = 0, high = 1000000000; // Iterate to find the first number while (low + 1 < high) { // Find the middle value long mid = low + (high - low) / 2; // If mid^2 is greater than // equal to A, then update // high to mid if (mid * mid >= N) { high = mid; } // Otherwise update low else { low = mid; } } // Store the first number long first = high; // Again, set low as 0 and // high as 1e9 low = 0; high = 1000000000; // Iterate to find the second number while (low + 1 < high) { // Find the middle value long mid = low + (high - low) / 2; // If first number * mid is // greater than N then update // high to mid if (first * mid > N) { high = mid; } // Else, update low to mid else { low = mid; } } // Store the second number long second = high; // Print the result System.out.println(first + second);} // Driver Codepublic static void main(String[] args){ int N = 10; // Function Call minSum(N);}} // This code is contributed by Dharanendra L V
# Python3 program for the above approach # Function to find the minimum sum of# two integers such that their product# is strictly greater than Ndef minSum(N): # Initialise low as 0 and # high as 1e9 low = 0 high = 1000000000 # Iterate to find the first number while (low + 1 < high): # Find the middle value mid = low + (high - low) / 2 # If mid^2 is greater than # equal to A, then update # high to mid if (mid * mid >= N): high = mid # Otherwise update low else: low = mid # Store the first number first = high # Again, set low as 0 and # high as 1e9 low = 0 high = 1000000000 # Iterate to find the second number while (low + 1 < high): # Find the middle value mid = low + (high - low) / 2 # If first number * mid is # greater than N then update # high to mid if (first * mid > N): high = mid # Else, update low to mid else: low = mid # Store the second number second = high # Print the result print(round(first + second)) # Driver CodeN = 10 # Function CallminSum(N) # This code is contributed by Dharanendra L V
// C# program for the above approachusing System; class GFG{ // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nstatic void minSum(int N){ // Initialise low as 0 and // high as 1e9 long low = 0, high = 1000000000; // Iterate to find the first number while (low + 1 < high) { // Find the middle value long mid = low + (high - low) / 2; // If mid^2 is greater than // equal to A, then update // high to mid if (mid * mid >= N) { high = mid; } // Otherwise update low else { low = mid; } } // Store the first number long first = high; // Again, set low as 0 and // high as 1e9 low = 0; high = 1000000000; // Iterate to find the second number while (low + 1 < high) { // Find the middle value long mid = low + (high - low) / 2; // If first number * mid is // greater than N then update // high to mid if (first * mid > N) { high = mid; } // Else, update low to mid else { low = mid; } } // Store the second number long second = high; // Print the result Console.WriteLine( first + second);} // Driver Codestatic public void Main(){ int N = 10; // Function Call minSum(N);}} // This code is contributed by Dharanendra L V
<script>// Javascript program for the above approach // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nfunction minSum(N){ // Initialise low as 0 and // high as 1e9 let low = 0, high = 1000000000; // Iterate to find the first number while (low + 1 < high) { // Find the middle value let mid = low + parseInt((high - low) / 2); // If mid^2 is greater than // equal to A, then update // high to mid if (mid * mid >= N) { high = mid; } // Otherwise update low else { low = mid; } } // Store the first number let first = high; // Again, set low as 0 and // high as 1e9 low = 0; high = 1000000000; // Iterate to find the second number while (low + 1 < high) { // Find the middle value let mid = low + parseInt((high - low) / 2); // If first number * mid is // greater than N then update // high to mid if (first * mid > N) { high = mid; } // Else, update low to mid else { low = mid; } } // Store the second number let second = high; // Print the result document.write(first + second);} // Driver Code let N = 10; // Function Call minSum(N); // This code is contributed by rishavmahato348.</script>
7
Time Complexity: O(log N)Auxiliary Space: O(1)
Most Efficient Approach: To optimize the above approach, the idea is based on Inequality of Arithmetic and Geometric progression as illustrated below.
From the inequality, If there are two integers A and B, (A + B)/2 ≥ √(A×B)Now, A×B = Product of the two integers, which is N and A+B is sum(=S).Therefore, S ≥ 2*√NTo get strictly greater product than N, the above equation transforms to: S ≥ 2*√(N+1)
Below is the program for the above approach:
C++14
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nvoid minSum(int N){ // Store the answer using the // AP-GP inequality int ans = ceil(2 * sqrt(N + 1)); // Print the answer cout << ans;} // Driver Codeint main(){ int N = 10; // Function Call minSum(N); return 0;}
// Java program for the above approachimport java.lang.*; class GFG{ // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nstatic void minSum(int N){ // Store the answer using the // AP-GP inequality int ans = (int)Math.ceil(2 * Math.sqrt(N + 1)); // Print the answer System.out.println( ans);} // Driver Codepublic static void main(String[] args){ int N = 10; // Function Call minSum(N);}} // This code is contributed by Dharanendra L V
# Python3 program for the above approachimport math # Function to find the minimum sum of# two integers such that their product# is strictly greater than Ndef minSum(N): # Store the answer using the # AP-GP inequality ans = math.ceil(2 * math.sqrt(N + 1)) # Print the result print(math.trunc(ans)) # Driver CodeN = 10 # Function CallminSum(N) # This code is contributed by Dharanendra L V
// C# program for the above approachusing System; class GFG{ // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nstatic void minSum(int N){ // Store the answer using the // AP-GP inequality int ans = (int)Math.Ceiling(2 * Math.Sqrt(N + 1)); // Print the answer Console.WriteLine( ans);} // Driver Codestatic public void Main(){ int N = 10; // Function Call minSum(N);}} // This code is contributed by Dharanendra L V
<script> // Javascript program for the above approach // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nfunction minSum(N){ // Store the answer using the // AP-GP inequality let ans = Math.ceil(2 * Math.sqrt(N + 1)); // Print the answer document.write(ans);} // Driver Codelet N = 10; // Function CallminSum(N); </script>
7
Time Complexity: O(1)Auxiliary Space: O(1)
dharanendralv23
subhammahato348
rishavmahato348
Binary Search
Greedy
Mathematical
Searching
Searching
Greedy
Mathematical
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Huffman Coding | Greedy Algo-3
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find sum of elements in a given array
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays | [
{
"code": null,
"e": 24549,
"s": 24521,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 24680,
"s": 24549,
"text": "Given an integer N, the task is to find two integers with minimum possible sum such that their product is strictly greater than N."
},
{
"code": null,
"e": 24690,
"s": 24680,
"text": "Examples:"
},
{
"code": null,
"e": 24805,
"s": 24690,
"text": "Input: N = 10Output: 7Explanation: The integers are 3 and 4. Their product is 3 × 4 = 12, which is greater than N."
},
{
"code": null,
"e": 24918,
"s": 24805,
"text": "Input: N = 1Output: 3Explanation: The integers are 1 and 2. Their product is 1 × 2 = 2, which is greater than N."
},
{
"code": null,
"e": 25198,
"s": 24918,
"text": "Naive Approach: Let the required numbers be A and B. The idea is based on the observation that in order to minimize their sum A should be the smallest number greater than √N. Once A is found, B will be equal to the smallest number for which A×B > N, which can be found linearly. "
},
{
"code": null,
"e": 25242,
"s": 25198,
"text": "Time Complexity: O(√N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 25383,
"s": 25242,
"text": "Efficient Approach: The above solution can be optimized by using Binary Search to find A and B. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25433,
"s": 25383,
"text": "Initialize two variables low = 0 and high = 109."
},
{
"code": null,
"e": 25695,
"s": 25433,
"text": "Iterate until (high – low) is greater than 1 and do the following:Find the value of middle-range mid as (low + high)/2.Now, compare √N with the middle element mid, and if √N is less than or equal to the middle element, then high as mid.Else, update low as mid."
},
{
"code": null,
"e": 25749,
"s": 25695,
"text": "Find the value of middle-range mid as (low + high)/2."
},
{
"code": null,
"e": 25868,
"s": 25749,
"text": "Now, compare √N with the middle element mid, and if √N is less than or equal to the middle element, then high as mid."
},
{
"code": null,
"e": 25893,
"s": 25868,
"text": "Else, update low as mid."
},
{
"code": null,
"e": 25933,
"s": 25893,
"text": "After all the above steps set A = high."
},
{
"code": null,
"e": 25988,
"s": 25933,
"text": "Repeat the same procedure to find B such that A×B > N."
},
{
"code": null,
"e": 26051,
"s": 25988,
"text": "After the above steps, print the sum of A and B as the result."
},
{
"code": null,
"e": 26102,
"s": 26051,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26108,
"s": 26102,
"text": "C++14"
},
{
"code": null,
"e": 26113,
"s": 26108,
"text": "Java"
},
{
"code": null,
"e": 26121,
"s": 26113,
"text": "Python3"
},
{
"code": null,
"e": 26124,
"s": 26121,
"text": "C#"
},
{
"code": null,
"e": 26135,
"s": 26124,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nvoid minSum(int N){ // Initialise low as 0 and // high as 1e9 ll low = 0, high = 1e9; // Iterate to find the first number while (low + 1 < high) { // Find the middle value ll mid = low + (high - low) / 2; // If mid^2 is greater than // equal to A, then update // high to mid if (mid * mid >= N) { high = mid; } // Otherwise update low else { low = mid; } } // Store the first number ll first = high; // Again, set low as 0 and // high as 1e9 low = 0; high = 1e9; // Iterate to find the second number while (low + 1 < high) { // Find the middle value ll mid = low + (high - low) / 2; // If first number * mid is // greater than N then update // high to mid if (first * mid > N) { high = mid; } // Else, update low to mid else { low = mid; } } // Store the second number ll second = high; // Print the result cout << first + second;} // Driver Codeint main(){ int N = 10; // Function Call minSum(N); return 0;}",
"e": 27523,
"s": 26135,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nstatic void minSum(int N){ // Initialise low as 0 and // high as 1e9 long low = 0, high = 1000000000; // Iterate to find the first number while (low + 1 < high) { // Find the middle value long mid = low + (high - low) / 2; // If mid^2 is greater than // equal to A, then update // high to mid if (mid * mid >= N) { high = mid; } // Otherwise update low else { low = mid; } } // Store the first number long first = high; // Again, set low as 0 and // high as 1e9 low = 0; high = 1000000000; // Iterate to find the second number while (low + 1 < high) { // Find the middle value long mid = low + (high - low) / 2; // If first number * mid is // greater than N then update // high to mid if (first * mid > N) { high = mid; } // Else, update low to mid else { low = mid; } } // Store the second number long second = high; // Print the result System.out.println(first + second);} // Driver Codepublic static void main(String[] args){ int N = 10; // Function Call minSum(N);}} // This code is contributed by Dharanendra L V",
"e": 29040,
"s": 27523,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the minimum sum of# two integers such that their product# is strictly greater than Ndef minSum(N): # Initialise low as 0 and # high as 1e9 low = 0 high = 1000000000 # Iterate to find the first number while (low + 1 < high): # Find the middle value mid = low + (high - low) / 2 # If mid^2 is greater than # equal to A, then update # high to mid if (mid * mid >= N): high = mid # Otherwise update low else: low = mid # Store the first number first = high # Again, set low as 0 and # high as 1e9 low = 0 high = 1000000000 # Iterate to find the second number while (low + 1 < high): # Find the middle value mid = low + (high - low) / 2 # If first number * mid is # greater than N then update # high to mid if (first * mid > N): high = mid # Else, update low to mid else: low = mid # Store the second number second = high # Print the result print(round(first + second)) # Driver CodeN = 10 # Function CallminSum(N) # This code is contributed by Dharanendra L V",
"e": 30291,
"s": 29040,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nstatic void minSum(int N){ // Initialise low as 0 and // high as 1e9 long low = 0, high = 1000000000; // Iterate to find the first number while (low + 1 < high) { // Find the middle value long mid = low + (high - low) / 2; // If mid^2 is greater than // equal to A, then update // high to mid if (mid * mid >= N) { high = mid; } // Otherwise update low else { low = mid; } } // Store the first number long first = high; // Again, set low as 0 and // high as 1e9 low = 0; high = 1000000000; // Iterate to find the second number while (low + 1 < high) { // Find the middle value long mid = low + (high - low) / 2; // If first number * mid is // greater than N then update // high to mid if (first * mid > N) { high = mid; } // Else, update low to mid else { low = mid; } } // Store the second number long second = high; // Print the result Console.WriteLine( first + second);} // Driver Codestatic public void Main(){ int N = 10; // Function Call minSum(N);}} // This code is contributed by Dharanendra L V",
"e": 31787,
"s": 30291,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nfunction minSum(N){ // Initialise low as 0 and // high as 1e9 let low = 0, high = 1000000000; // Iterate to find the first number while (low + 1 < high) { // Find the middle value let mid = low + parseInt((high - low) / 2); // If mid^2 is greater than // equal to A, then update // high to mid if (mid * mid >= N) { high = mid; } // Otherwise update low else { low = mid; } } // Store the first number let first = high; // Again, set low as 0 and // high as 1e9 low = 0; high = 1000000000; // Iterate to find the second number while (low + 1 < high) { // Find the middle value let mid = low + parseInt((high - low) / 2); // If first number * mid is // greater than N then update // high to mid if (first * mid > N) { high = mid; } // Else, update low to mid else { low = mid; } } // Store the second number let second = high; // Print the result document.write(first + second);} // Driver Code let N = 10; // Function Call minSum(N); // This code is contributed by rishavmahato348.</script>",
"e": 33200,
"s": 31787,
"text": null
},
{
"code": null,
"e": 33202,
"s": 33200,
"text": "7"
},
{
"code": null,
"e": 33251,
"s": 33204,
"text": "Time Complexity: O(log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33402,
"s": 33251,
"text": "Most Efficient Approach: To optimize the above approach, the idea is based on Inequality of Arithmetic and Geometric progression as illustrated below."
},
{
"code": null,
"e": 33652,
"s": 33402,
"text": "From the inequality, If there are two integers A and B, (A + B)/2 ≥ √(A×B)Now, A×B = Product of the two integers, which is N and A+B is sum(=S).Therefore, S ≥ 2*√NTo get strictly greater product than N, the above equation transforms to: S ≥ 2*√(N+1)"
},
{
"code": null,
"e": 33697,
"s": 33652,
"text": "Below is the program for the above approach:"
},
{
"code": null,
"e": 33703,
"s": 33697,
"text": "C++14"
},
{
"code": null,
"e": 33708,
"s": 33703,
"text": "Java"
},
{
"code": null,
"e": 33716,
"s": 33708,
"text": "Python3"
},
{
"code": null,
"e": 33719,
"s": 33716,
"text": "C#"
},
{
"code": null,
"e": 33730,
"s": 33719,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nvoid minSum(int N){ // Store the answer using the // AP-GP inequality int ans = ceil(2 * sqrt(N + 1)); // Print the answer cout << ans;} // Driver Codeint main(){ int N = 10; // Function Call minSum(N); return 0;}",
"e": 34162,
"s": 33730,
"text": null
},
{
"code": "// Java program for the above approachimport java.lang.*; class GFG{ // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nstatic void minSum(int N){ // Store the answer using the // AP-GP inequality int ans = (int)Math.ceil(2 * Math.sqrt(N + 1)); // Print the answer System.out.println( ans);} // Driver Codepublic static void main(String[] args){ int N = 10; // Function Call minSum(N);}} // This code is contributed by Dharanendra L V",
"e": 34692,
"s": 34162,
"text": null
},
{
"code": "# Python3 program for the above approachimport math # Function to find the minimum sum of# two integers such that their product# is strictly greater than Ndef minSum(N): # Store the answer using the # AP-GP inequality ans = math.ceil(2 * math.sqrt(N + 1)) # Print the result print(math.trunc(ans)) # Driver CodeN = 10 # Function CallminSum(N) # This code is contributed by Dharanendra L V",
"e": 35106,
"s": 34692,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nstatic void minSum(int N){ // Store the answer using the // AP-GP inequality int ans = (int)Math.Ceiling(2 * Math.Sqrt(N + 1)); // Print the answer Console.WriteLine( ans);} // Driver Codestatic public void Main(){ int N = 10; // Function Call minSum(N);}} // This code is contributed by Dharanendra L V",
"e": 35612,
"s": 35106,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the minimum sum of// two integers such that their product// is strictly greater than Nfunction minSum(N){ // Store the answer using the // AP-GP inequality let ans = Math.ceil(2 * Math.sqrt(N + 1)); // Print the answer document.write(ans);} // Driver Codelet N = 10; // Function CallminSum(N); </script>",
"e": 36006,
"s": 35612,
"text": null
},
{
"code": null,
"e": 36008,
"s": 36006,
"text": "7"
},
{
"code": null,
"e": 36053,
"s": 36010,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 36069,
"s": 36053,
"text": "dharanendralv23"
},
{
"code": null,
"e": 36085,
"s": 36069,
"text": "subhammahato348"
},
{
"code": null,
"e": 36101,
"s": 36085,
"text": "rishavmahato348"
},
{
"code": null,
"e": 36115,
"s": 36101,
"text": "Binary Search"
},
{
"code": null,
"e": 36122,
"s": 36115,
"text": "Greedy"
},
{
"code": null,
"e": 36135,
"s": 36122,
"text": "Mathematical"
},
{
"code": null,
"e": 36145,
"s": 36135,
"text": "Searching"
},
{
"code": null,
"e": 36155,
"s": 36145,
"text": "Searching"
},
{
"code": null,
"e": 36162,
"s": 36155,
"text": "Greedy"
},
{
"code": null,
"e": 36175,
"s": 36162,
"text": "Mathematical"
},
{
"code": null,
"e": 36189,
"s": 36175,
"text": "Binary Search"
},
{
"code": null,
"e": 36287,
"s": 36189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36296,
"s": 36287,
"text": "Comments"
},
{
"code": null,
"e": 36309,
"s": 36296,
"text": "Old Comments"
},
{
"code": null,
"e": 36340,
"s": 36309,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 36421,
"s": 36340,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 36464,
"s": 36421,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 36492,
"s": 36464,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 36515,
"s": 36492,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 36530,
"s": 36515,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36573,
"s": 36530,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 36622,
"s": 36573,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 36665,
"s": 36622,
"text": "Modulo Operator (%) in C/C++ with Examples"
}
] |
Program to find frequency of each element in a vector using map in C++ | 29 May, 2021
Given a vector vec, the task is to find the frequency of each element of vec using a map. Examples:
Input: vec = {1, 2, 2, 3, 1, 4, 4, 5} Output: 1 2 2 2 3 1 4 2 5 1 Explanation: 1 has occurred 2 times 2 has occurred 2 times 3 has occurred 1 times 4 has occurred 2 times 5 has occurred 1 times Input: v1 = {6, 7, 8, 6, 4, 1} Output: 1 1 4 1 6 2 7 1 8 1 Explanation: 1 has occurred 1 times 4 has occurred 1 times 6 has occurred 2 times 7 has occurred 1 times 8 has occurred 1 times
Approach: We can find the frequency of elements in a vector using given four steps efficiently:
Traverse the elements of the given vector vec.check whether the current element is present in the map or not.If it is present, then update the frequency of the current element, else insert the element with frequency 1 as shown below:Traverse the map and print the frequency of each element stored as a mapped value.
Traverse the elements of the given vector vec.
check whether the current element is present in the map or not.
If it is present, then update the frequency of the current element, else insert the element with frequency 1 as shown below:
Traverse the map and print the frequency of each element stored as a mapped value.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>using namespace std; void printFrequency(vector<int> vec){ // Define an map map<int, int> M; // Traverse vector vec check if // current element is present // or not for (int i = 0; vec[i]; i++) { // If the current element // is not found then insert // current element with // frequency 1 if (M.find(vec[i]) == M.end()) { M[vec[i]] = 1; } // Else update the frequency else { M[vec[i]]++; } } // Traverse the map to print the // frequency for (auto& it : M) { cout << it.first << ' ' << it.second << '\n'; }} // Driver Codeint main(){ vector<int> vec = { 1, 2, 2, 3, 1, 4, 4, 5 }; // Function call printFrequency(vec); return 0;}
1 2
2 2
3 1
4 2
5 1
Complexity Analysis: Time Complexity: O(n log n) For a given vector of size n, we are iterating over it once and the time complexity for searching elements in the map is O(log n). So the time complexity is O(n log n) Space Complexity: O(n) For a given vector of size n, we are using an extra map which can have maximum of n key-values, so space complexity is O(n)
sufyankhan9678
varshagumber28
cpp-map
C++
Data Structures
Write From Home
Data Structures
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Unordered Sets in C++ Standard Template Library
Pair in C++ Standard Template Library (STL)
std::string class in C++
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 156,
"s": 54,
"text": "Given a vector vec, the task is to find the frequency of each element of vec using a map. Examples: "
},
{
"code": null,
"e": 539,
"s": 156,
"text": "Input: vec = {1, 2, 2, 3, 1, 4, 4, 5} Output: 1 2 2 2 3 1 4 2 5 1 Explanation: 1 has occurred 2 times 2 has occurred 2 times 3 has occurred 1 times 4 has occurred 2 times 5 has occurred 1 times Input: v1 = {6, 7, 8, 6, 4, 1} Output: 1 1 4 1 6 2 7 1 8 1 Explanation: 1 has occurred 1 times 4 has occurred 1 times 6 has occurred 2 times 7 has occurred 1 times 8 has occurred 1 times "
},
{
"code": null,
"e": 639,
"s": 541,
"text": "Approach: We can find the frequency of elements in a vector using given four steps efficiently: "
},
{
"code": null,
"e": 955,
"s": 639,
"text": "Traverse the elements of the given vector vec.check whether the current element is present in the map or not.If it is present, then update the frequency of the current element, else insert the element with frequency 1 as shown below:Traverse the map and print the frequency of each element stored as a mapped value."
},
{
"code": null,
"e": 1002,
"s": 955,
"text": "Traverse the elements of the given vector vec."
},
{
"code": null,
"e": 1066,
"s": 1002,
"text": "check whether the current element is present in the map or not."
},
{
"code": null,
"e": 1191,
"s": 1066,
"text": "If it is present, then update the frequency of the current element, else insert the element with frequency 1 as shown below:"
},
{
"code": null,
"e": 1274,
"s": 1191,
"text": "Traverse the map and print the frequency of each element stored as a mapped value."
},
{
"code": null,
"e": 1326,
"s": 1274,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1330,
"s": 1326,
"text": "CPP"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void printFrequency(vector<int> vec){ // Define an map map<int, int> M; // Traverse vector vec check if // current element is present // or not for (int i = 0; vec[i]; i++) { // If the current element // is not found then insert // current element with // frequency 1 if (M.find(vec[i]) == M.end()) { M[vec[i]] = 1; } // Else update the frequency else { M[vec[i]]++; } } // Traverse the map to print the // frequency for (auto& it : M) { cout << it.first << ' ' << it.second << '\\n'; }} // Driver Codeint main(){ vector<int> vec = { 1, 2, 2, 3, 1, 4, 4, 5 }; // Function call printFrequency(vec); return 0;}",
"e": 2137,
"s": 1330,
"text": null
},
{
"code": null,
"e": 2157,
"s": 2137,
"text": "1 2\n2 2\n3 1\n4 2\n5 1"
},
{
"code": null,
"e": 2524,
"s": 2159,
"text": "Complexity Analysis: Time Complexity: O(n log n) For a given vector of size n, we are iterating over it once and the time complexity for searching elements in the map is O(log n). So the time complexity is O(n log n) Space Complexity: O(n) For a given vector of size n, we are using an extra map which can have maximum of n key-values, so space complexity is O(n) "
},
{
"code": null,
"e": 2539,
"s": 2524,
"text": "sufyankhan9678"
},
{
"code": null,
"e": 2554,
"s": 2539,
"text": "varshagumber28"
},
{
"code": null,
"e": 2562,
"s": 2554,
"text": "cpp-map"
},
{
"code": null,
"e": 2566,
"s": 2562,
"text": "C++"
},
{
"code": null,
"e": 2582,
"s": 2566,
"text": "Data Structures"
},
{
"code": null,
"e": 2598,
"s": 2582,
"text": "Write From Home"
},
{
"code": null,
"e": 2614,
"s": 2598,
"text": "Data Structures"
},
{
"code": null,
"e": 2618,
"s": 2614,
"text": "CPP"
},
{
"code": null,
"e": 2716,
"s": 2618,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2740,
"s": 2716,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2760,
"s": 2740,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2808,
"s": 2760,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2852,
"s": 2808,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2877,
"s": 2852,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2902,
"s": 2877,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 2951,
"s": 2902,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 2995,
"s": 2951,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 3033,
"s": 2995,
"text": "What is Hashing | A Complete Tutorial"
}
] |
C# | Int 64 Struct | 02 May, 2019
In C#, Int64 Struct is used to represent 64-bit signed integer(also termed as long data type) starting from range -9,223,372,036,854,775,808 to +9, 223,372,036,854,775,807. It provides different types of method to perform various operations. A user can perform the mathematical operation like addition, subtraction, multiplication, etc. on Int64 type. It supports bitwise operations like AND, OR, XOR, etc. It provides full support for standard and custom numeric format strings. The user can also call the methods of Convert and Math class to perform operations on Int64 value. Int64 struct inherits the ValueType class which inherits the Object class.
Example 1:
// C# program to illustrate the // MaxValue and MinValue fieldusing System; class GFG { // Main method static public void Main() { Int64 var1 = 89; Int64 var2 = 50; Int64 var3 = 10; // Get the Maximum and Minimum value of // Int64 type Using MaxValue and // MinValue field Console.WriteLine("Value 1: {0}", var1); Console.WriteLine("Value 2: {0}", var2); Console.WriteLine("Value 3: {0}", var3); Console.WriteLine("Maximum Value: {0}", Int64.MaxValue); Console.WriteLine("Minimum Value: {0}", Int64.MinValue); }}
Value 1: 89
Value 2: 50
Value 3: 10
Maximum Value: 9223372036854775807
Minimum Value: -9223372036854775808
Example 1:
// C# program to demonstrate the // Int64.Equals(Int64) Method using System; using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 long value1 = 45643212342; // Declaring and initializing value2 long value2 = 543256344233; // using Equals(Int64) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); } }
45643212342 is not equal to 543256344233
Example 2:
// C# program to illustrate the // Int64.GetTypeCode() Method using System; class GFG { // Main Method public static void Main() { // Taking long value // i.e. Int64 long val = 45789478123; // Getting the typecode for Int64 // using GetTypeCode() method TypeCode result = val.GetTypeCode(); // Display the TypeCode Console.WriteLine("TypeCode for Int64 is: {0}", result); } }
TypeCode for Int64 is: Int64
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int64?view=netframework-4.7.2
CSharp-Int64-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 May, 2019"
},
{
"code": null,
"e": 682,
"s": 28,
"text": "In C#, Int64 Struct is used to represent 64-bit signed integer(also termed as long data type) starting from range -9,223,372,036,854,775,808 to +9, 223,372,036,854,775,807. It provides different types of method to perform various operations. A user can perform the mathematical operation like addition, subtraction, multiplication, etc. on Int64 type. It supports bitwise operations like AND, OR, XOR, etc. It provides full support for standard and custom numeric format strings. The user can also call the methods of Convert and Math class to perform operations on Int64 value. Int64 struct inherits the ValueType class which inherits the Object class."
},
{
"code": null,
"e": 693,
"s": 682,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the // MaxValue and MinValue fieldusing System; class GFG { // Main method static public void Main() { Int64 var1 = 89; Int64 var2 = 50; Int64 var3 = 10; // Get the Maximum and Minimum value of // Int64 type Using MaxValue and // MinValue field Console.WriteLine(\"Value 1: {0}\", var1); Console.WriteLine(\"Value 2: {0}\", var2); Console.WriteLine(\"Value 3: {0}\", var3); Console.WriteLine(\"Maximum Value: {0}\", Int64.MaxValue); Console.WriteLine(\"Minimum Value: {0}\", Int64.MinValue); }}",
"e": 1366,
"s": 693,
"text": null
},
{
"code": null,
"e": 1474,
"s": 1366,
"text": "Value 1: 89\nValue 2: 50\nValue 3: 10\nMaximum Value: 9223372036854775807\nMinimum Value: -9223372036854775808\n"
},
{
"code": null,
"e": 1485,
"s": 1474,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the // Int64.Equals(Int64) Method using System; using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 long value1 = 45643212342; // Declaring and initializing value2 long value2 = 543256344233; // using Equals(Int64) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine(\"{0} is equal to {1}\", value1, value2); else Console.WriteLine(\"{0} is not equal to {1}\", value1, value2); } } ",
"e": 2213,
"s": 1485,
"text": null
},
{
"code": null,
"e": 2255,
"s": 2213,
"text": "45643212342 is not equal to 543256344233\n"
},
{
"code": null,
"e": 2266,
"s": 2255,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the // Int64.GetTypeCode() Method using System; class GFG { // Main Method public static void Main() { // Taking long value // i.e. Int64 long val = 45789478123; // Getting the typecode for Int64 // using GetTypeCode() method TypeCode result = val.GetTypeCode(); // Display the TypeCode Console.WriteLine(\"TypeCode for Int64 is: {0}\", result); } } ",
"e": 2791,
"s": 2266,
"text": null
},
{
"code": null,
"e": 2821,
"s": 2791,
"text": "TypeCode for Int64 is: Int64\n"
},
{
"code": null,
"e": 2832,
"s": 2821,
"text": "Reference:"
},
{
"code": null,
"e": 2913,
"s": 2832,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.int64?view=netframework-4.7.2"
},
{
"code": null,
"e": 2933,
"s": 2913,
"text": "CSharp-Int64-Struct"
},
{
"code": null,
"e": 2936,
"s": 2933,
"text": "C#"
}
] |
Find unit digit of x raised to power y | 23 Jun, 2022
Given two numbers x and y, find unit digit of xy.
Examples :
Input : x = 2, y = 1
Output : 2
Explanation
2^1 = 2 so units digit is 2.
Input : x = 4, y = 2
Output : 6
Explanation
4^2 = 16 so units digit is 6.
Method 1 (Simple) Compute value of xy and find its last digit. This method causes overflow for slightly larger values of x and y.Method 2 (Efficient) 1) Find last digit of x. 2) Compute x^y under modulo 10 and return its value.
C++
Java
Python3
C#
PHP
Javascript
// Efficient C++ program to// find unit digit of x^y.#include <bits/stdc++.h>using namespace std; // Returns unit digit of x// raised to power yint unitDigitXRaisedY(int x, int y){ // Initialize result as 1 to // handle case when y is 0. int res = 1; // One by one multiply with x // mod 10 to avoid overflow. for (int i = 0; i < y; i++) res = (res * x) % 10; return res;} // Driver programint main(){ cout << unitDigitXRaisedY(4, 2); return 0;}
// Efficient Java program to find// unit digit of x^y.import java.io.*; class GFG { // Returns unit digit of x raised to power y static int unitDigitXRaisedY(int x, int y) { // Initialize result as 1 to // handle case when y is 0. int res = 1; // One by one multiply with x // mod 10 to avoid overflow. for (int i = 0; i < y; i++) res = (res * x) % 10; return res; } // Driver program public static void main(String args[])throws IOException { System.out.println(unitDigitXRaisedY(4, 2)); }} // This code is contributed by Nikita Tiwari.
# Python3 code to find# unit digit of x^y. # Returns unit digit of# x raised to power ydef unitDigitXRaisedY( x , y ): # Initialize result as 1 to # handle case when y is 0. res = 1 # One by one multiply with x # mod 10 to avoid overflow. for i in range(y): res = (res * x) % 10 return res # Driver programprint( unitDigitXRaisedY(4, 2)) # This code is contributed by Abhishek Sharma44.
// Efficient Java program to find// unit digit of x^y.using System; class GFG{ // Returns unit digit of x raised to power y static int unitDigitXRaisedY(int x, int y) { // Initialize result as 1 to // handle case when y is 0. int res = 1; // One by one multiply with x // mod 10 to avoid overflow. for (int i = 0; i < y; i++) res = (res * x) % 10; return res; } // Driver program public static void Main() { Console.WriteLine(unitDigitXRaisedY(4, 2)); }} // This code is contributed by vt_m.
<?php// Efficient PHP program to// find unit digit of x^y. // Returns unit digit of x// raised to power yfunction unitDigitXRaisedY($x, $y){ // Initialize result as 1 to // handle case when y is 0. $res = 1; // One by one multiply with x // mod 10 to avoid overflow. for ($i = 0; $i < $y; $i++) $res = ($res * $x) % 10; return $res;} // Driver Codeecho(unitDigitXRaisedY(4, 2)); // This code is contributed by Ajit.?>
<script> // Efficient Javascript program to// find unit digit of x^y. // Returns unit digit of x// raised to power yfunction unitDigitXRaisedY(x, y){ // Initialize result as 1 to // handle case when y is 0. let res = 1; // One by one multiply with x // mod 10 to avoid overflow. for(let i = 0; i < y; i++) res = (res * x) % 10; return res;} // Driver Codedocument.write(unitDigitXRaisedY(4, 2)); // This code is contributed by _saurabh_jaiswal. </script>
Output :
6
Time Complexity: O(y), where y is the powerAuxiliary Space: O(1), as no extra space is required
Further Optimizations: We can compute modular power in Log y.
Method 3 (Direct based on cyclic nature of last digit) This method depends on the cyclicity with the last digit of x that is
x | power 2 | power 3 | power 4 | Cyclicity
0 | .................................. | .... repeat with 0
1 | .................................. | .... repeat with 1
2 | 4 | 8 | 6 | .... repeat with 2
3 | 9 | 7 | 1 | .... repeat with 3
4 | 6 |....................... | .... repeat with 4
5 | .................................. | .... repeat with 5
6 | .................................. | .... repeat with 6
7 | 9 | 3 | 1 | .... repeat with 7
8 | 4 | 2 | 6 | .... repeat with 8
9 | 1 | ...................... | .... repeat with 9
So here we directly mod the power y with 4 because this is the last power after this all number’s repetition start after this we simply power with number x last digit then we get the unit digit of produced number.
C++
Java
Python3
C#
PHP
Javascript
// C++ code to find the unit digit of x// raised to power y.#include<iostream>#include<math.h>using namespace std; // find unit digitint unitnumber(int x, int y){ // Get last digit of x x = x % 10; // Last cyclic modular value if(y!=0) y = y % 4 + 4; // here we simply return the // unit digit or the power // of a number return (((int)(pow(x, y))) % 10);} int main(){ int x = 133, y = 5; // get unit digit number here we pass // the unit digit of x and the last // cyclicity number that is y%4 cout << unitnumber(x, y); return 0;}
// Java code to find the unit// digit of x raised to power y.import java.io.*;import java.util.*; class GFG { // find unit digit static int unitnumber(int x, int y) { // Get last digit of x x = x % 10; // Last cyclic modular value if(y!=0) y = y % 4 + 4; // here we simply return the // unit digit or the power // of a number return (((int)(Math.pow(x, y))) % 10); } public static void main (String[] args) { int x = 133, y = 5; // get unit digit number here we pass // the unit digit of x and the last // cyclicity number that is y%4 System.out.println(unitnumber(x, y)); }} // This code is contributed by Gitanjali.
# Python3 code to find the unit # digit of x raised to power y.import math # Find unit digitdef unitnumber(x, y): # Get last digit of x x = x % 10 # Last cyclic modular value if y!=0: y = y % 4 + 4 # Here we simply return # the unit digit or the # power of a number return (((int)(math.pow(x, y))) % 10) # Driver codex = 133; y = 5 # Get unit digit number here we pass# the unit digit of x and the last# cyclicity number that is y%4print(unitnumber(x, y)) # This code is contributed by Gitanjali.
// C# code to find the unit// digit of x raised to power y.using System; class GFG { // find unit digit static int unitnumber(int x, int y) { // Get last digit of x x = x % 10; // Last cyclic modular value if(y!=0) y = y % 4 + 4; // here we simply return the // unit digit or the power // of a number return (((int)(Math.Pow(x, y))) % 10); } // Driver code public static void Main () { int x = 133, y = 5; // get unit digit number here we pass // the unit digit of x and the last // cyclicity number that is y%4 Console.WriteLine(unitnumber(x, y)); }} // This code is contributed by vt_m.
<?php// PHP code to find the unit// digit of x raised to power y. // find unit digitfunction unitnumber($x, $y){ // Get last digit of x $x = $x % 10; // Last cyclic modular value if($y!=0) $y = $y % 4 + 4; // here we simply return the // unit digit or the power // of a number return (((int)(pow($x, $y))) % 10);} // Driver code$x = 133; $y = 5; // get unit digit number here we pass// the unit digit of x and the last// cyclicity number that is y%4echo(unitnumber($x, $y)); // This code is contributed by Ajit.?>
<script> // Javascript code to find the unit// digit of x raised to power y. // find unit digitfunction unitnumber(x, y){ // Get last digit of x x = x % 10; // Last cyclic modular value if (y != 0) y = y % 4 + 4; // here we simply return the // unit digit or the power // of a number return ((parseInt(Math.pow(x, y))) % 10);} // Driver codelet x = 133;let y = 5; // get unit digit number here we pass// the unit digit of x and the last// cyclicity number that is y%4document.write(unitnumber(x, y)); // This code is contributed by _saurabh_jaiswal. </script>
Output :
3
Time Complexity: O(log n)Auxiliary Space: O(1)
Thanks to DevanshuAgarwal for suggesting above solution.How to handle large numbers? Efficient method for Last Digit Of a^b for Large Numbers
jit_t
gowtham_yuvaraj
_saurabh_jaiswal
singhh3010
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 104,
"s": 54,
"text": "Given two numbers x and y, find unit digit of xy."
},
{
"code": null,
"e": 116,
"s": 104,
"text": "Examples : "
},
{
"code": null,
"e": 265,
"s": 116,
"text": "Input : x = 2, y = 1\nOutput : 2\nExplanation\n2^1 = 2 so units digit is 2.\n\nInput : x = 4, y = 2\nOutput : 6\nExplanation\n4^2 = 16 so units digit is 6."
},
{
"code": null,
"e": 494,
"s": 265,
"text": "Method 1 (Simple) Compute value of xy and find its last digit. This method causes overflow for slightly larger values of x and y.Method 2 (Efficient) 1) Find last digit of x. 2) Compute x^y under modulo 10 and return its value. "
},
{
"code": null,
"e": 498,
"s": 494,
"text": "C++"
},
{
"code": null,
"e": 503,
"s": 498,
"text": "Java"
},
{
"code": null,
"e": 511,
"s": 503,
"text": "Python3"
},
{
"code": null,
"e": 514,
"s": 511,
"text": "C#"
},
{
"code": null,
"e": 518,
"s": 514,
"text": "PHP"
},
{
"code": null,
"e": 529,
"s": 518,
"text": "Javascript"
},
{
"code": "// Efficient C++ program to// find unit digit of x^y.#include <bits/stdc++.h>using namespace std; // Returns unit digit of x// raised to power yint unitDigitXRaisedY(int x, int y){ // Initialize result as 1 to // handle case when y is 0. int res = 1; // One by one multiply with x // mod 10 to avoid overflow. for (int i = 0; i < y; i++) res = (res * x) % 10; return res;} // Driver programint main(){ cout << unitDigitXRaisedY(4, 2); return 0;}",
"e": 1010,
"s": 529,
"text": null
},
{
"code": "// Efficient Java program to find// unit digit of x^y.import java.io.*; class GFG { // Returns unit digit of x raised to power y static int unitDigitXRaisedY(int x, int y) { // Initialize result as 1 to // handle case when y is 0. int res = 1; // One by one multiply with x // mod 10 to avoid overflow. for (int i = 0; i < y; i++) res = (res * x) % 10; return res; } // Driver program public static void main(String args[])throws IOException { System.out.println(unitDigitXRaisedY(4, 2)); }} // This code is contributed by Nikita Tiwari.",
"e": 1650,
"s": 1010,
"text": null
},
{
"code": "# Python3 code to find# unit digit of x^y. # Returns unit digit of# x raised to power ydef unitDigitXRaisedY( x , y ): # Initialize result as 1 to # handle case when y is 0. res = 1 # One by one multiply with x # mod 10 to avoid overflow. for i in range(y): res = (res * x) % 10 return res # Driver programprint( unitDigitXRaisedY(4, 2)) # This code is contributed by Abhishek Sharma44.",
"e": 2081,
"s": 1650,
"text": null
},
{
"code": "// Efficient Java program to find// unit digit of x^y.using System; class GFG{ // Returns unit digit of x raised to power y static int unitDigitXRaisedY(int x, int y) { // Initialize result as 1 to // handle case when y is 0. int res = 1; // One by one multiply with x // mod 10 to avoid overflow. for (int i = 0; i < y; i++) res = (res * x) % 10; return res; } // Driver program public static void Main() { Console.WriteLine(unitDigitXRaisedY(4, 2)); }} // This code is contributed by vt_m.",
"e": 2675,
"s": 2081,
"text": null
},
{
"code": "<?php// Efficient PHP program to// find unit digit of x^y. // Returns unit digit of x// raised to power yfunction unitDigitXRaisedY($x, $y){ // Initialize result as 1 to // handle case when y is 0. $res = 1; // One by one multiply with x // mod 10 to avoid overflow. for ($i = 0; $i < $y; $i++) $res = ($res * $x) % 10; return $res;} // Driver Codeecho(unitDigitXRaisedY(4, 2)); // This code is contributed by Ajit.?>",
"e": 3123,
"s": 2675,
"text": null
},
{
"code": "<script> // Efficient Javascript program to// find unit digit of x^y. // Returns unit digit of x// raised to power yfunction unitDigitXRaisedY(x, y){ // Initialize result as 1 to // handle case when y is 0. let res = 1; // One by one multiply with x // mod 10 to avoid overflow. for(let i = 0; i < y; i++) res = (res * x) % 10; return res;} // Driver Codedocument.write(unitDigitXRaisedY(4, 2)); // This code is contributed by _saurabh_jaiswal. </script>",
"e": 3613,
"s": 3123,
"text": null
},
{
"code": null,
"e": 3623,
"s": 3613,
"text": "Output : "
},
{
"code": null,
"e": 3625,
"s": 3623,
"text": "6"
},
{
"code": null,
"e": 3721,
"s": 3625,
"text": "Time Complexity: O(y), where y is the powerAuxiliary Space: O(1), as no extra space is required"
},
{
"code": null,
"e": 3783,
"s": 3721,
"text": "Further Optimizations: We can compute modular power in Log y."
},
{
"code": null,
"e": 3908,
"s": 3783,
"text": "Method 3 (Direct based on cyclic nature of last digit) This method depends on the cyclicity with the last digit of x that is"
},
{
"code": null,
"e": 4590,
"s": 3908,
"text": "x | power 2 | power 3 | power 4 | Cyclicity \n0 | .................................. | .... repeat with 0\n1 | .................................. | .... repeat with 1\n2 | 4 | 8 | 6 | .... repeat with 2\n3 | 9 | 7 | 1 | .... repeat with 3\n4 | 6 |....................... | .... repeat with 4\n5 | .................................. | .... repeat with 5\n6 | .................................. | .... repeat with 6\n7 | 9 | 3 | 1 | .... repeat with 7\n8 | 4 | 2 | 6 | .... repeat with 8\n9 | 1 | ...................... | .... repeat with 9 "
},
{
"code": null,
"e": 4805,
"s": 4590,
"text": "So here we directly mod the power y with 4 because this is the last power after this all number’s repetition start after this we simply power with number x last digit then we get the unit digit of produced number. "
},
{
"code": null,
"e": 4809,
"s": 4805,
"text": "C++"
},
{
"code": null,
"e": 4814,
"s": 4809,
"text": "Java"
},
{
"code": null,
"e": 4822,
"s": 4814,
"text": "Python3"
},
{
"code": null,
"e": 4825,
"s": 4822,
"text": "C#"
},
{
"code": null,
"e": 4829,
"s": 4825,
"text": "PHP"
},
{
"code": null,
"e": 4840,
"s": 4829,
"text": "Javascript"
},
{
"code": "// C++ code to find the unit digit of x// raised to power y.#include<iostream>#include<math.h>using namespace std; // find unit digitint unitnumber(int x, int y){ // Get last digit of x x = x % 10; // Last cyclic modular value if(y!=0) y = y % 4 + 4; // here we simply return the // unit digit or the power // of a number return (((int)(pow(x, y))) % 10);} int main(){ int x = 133, y = 5; // get unit digit number here we pass // the unit digit of x and the last // cyclicity number that is y%4 cout << unitnumber(x, y); return 0;}",
"e": 5437,
"s": 4840,
"text": null
},
{
"code": "// Java code to find the unit// digit of x raised to power y.import java.io.*;import java.util.*; class GFG { // find unit digit static int unitnumber(int x, int y) { // Get last digit of x x = x % 10; // Last cyclic modular value if(y!=0) y = y % 4 + 4; // here we simply return the // unit digit or the power // of a number return (((int)(Math.pow(x, y))) % 10); } public static void main (String[] args) { int x = 133, y = 5; // get unit digit number here we pass // the unit digit of x and the last // cyclicity number that is y%4 System.out.println(unitnumber(x, y)); }} // This code is contributed by Gitanjali.",
"e": 6223,
"s": 5437,
"text": null
},
{
"code": "# Python3 code to find the unit # digit of x raised to power y.import math # Find unit digitdef unitnumber(x, y): # Get last digit of x x = x % 10 # Last cyclic modular value if y!=0: y = y % 4 + 4 # Here we simply return # the unit digit or the # power of a number return (((int)(math.pow(x, y))) % 10) # Driver codex = 133; y = 5 # Get unit digit number here we pass# the unit digit of x and the last# cyclicity number that is y%4print(unitnumber(x, y)) # This code is contributed by Gitanjali.",
"e": 6772,
"s": 6223,
"text": null
},
{
"code": "// C# code to find the unit// digit of x raised to power y.using System; class GFG { // find unit digit static int unitnumber(int x, int y) { // Get last digit of x x = x % 10; // Last cyclic modular value if(y!=0) y = y % 4 + 4; // here we simply return the // unit digit or the power // of a number return (((int)(Math.Pow(x, y))) % 10); } // Driver code public static void Main () { int x = 133, y = 5; // get unit digit number here we pass // the unit digit of x and the last // cyclicity number that is y%4 Console.WriteLine(unitnumber(x, y)); }} // This code is contributed by vt_m.",
"e": 7526,
"s": 6772,
"text": null
},
{
"code": "<?php// PHP code to find the unit// digit of x raised to power y. // find unit digitfunction unitnumber($x, $y){ // Get last digit of x $x = $x % 10; // Last cyclic modular value if($y!=0) $y = $y % 4 + 4; // here we simply return the // unit digit or the power // of a number return (((int)(pow($x, $y))) % 10);} // Driver code$x = 133; $y = 5; // get unit digit number here we pass// the unit digit of x and the last// cyclicity number that is y%4echo(unitnumber($x, $y)); // This code is contributed by Ajit.?>",
"e": 8081,
"s": 7526,
"text": null
},
{
"code": "<script> // Javascript code to find the unit// digit of x raised to power y. // find unit digitfunction unitnumber(x, y){ // Get last digit of x x = x % 10; // Last cyclic modular value if (y != 0) y = y % 4 + 4; // here we simply return the // unit digit or the power // of a number return ((parseInt(Math.pow(x, y))) % 10);} // Driver codelet x = 133;let y = 5; // get unit digit number here we pass// the unit digit of x and the last// cyclicity number that is y%4document.write(unitnumber(x, y)); // This code is contributed by _saurabh_jaiswal. </script>",
"e": 8687,
"s": 8081,
"text": null
},
{
"code": null,
"e": 8697,
"s": 8687,
"text": "Output : "
},
{
"code": null,
"e": 8699,
"s": 8697,
"text": "3"
},
{
"code": null,
"e": 8746,
"s": 8699,
"text": "Time Complexity: O(log n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8889,
"s": 8746,
"text": "Thanks to DevanshuAgarwal for suggesting above solution.How to handle large numbers? Efficient method for Last Digit Of a^b for Large Numbers "
},
{
"code": null,
"e": 8895,
"s": 8889,
"text": "jit_t"
},
{
"code": null,
"e": 8911,
"s": 8895,
"text": "gowtham_yuvaraj"
},
{
"code": null,
"e": 8928,
"s": 8911,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 8939,
"s": 8928,
"text": "singhh3010"
},
{
"code": null,
"e": 8958,
"s": 8939,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 8971,
"s": 8958,
"text": "Mathematical"
},
{
"code": null,
"e": 8984,
"s": 8971,
"text": "Mathematical"
},
{
"code": null,
"e": 9003,
"s": 8984,
"text": "Modular Arithmetic"
}
] |
How to check interface type in TypeScript ? | 29 Sep, 2020
Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an interface or contract of a car.
interface Audi {
length: number;
width: number;
wheelbase: number;
price:number;
numberOfAirBags:number;
seatingCapacity: number;
getTyrePressure: () => number;
}
Approach:
Declare an interface with a name and its type as a string.
Now create a customized function to check the interface type.
This function returns a boolean value if the name attribute is present in the argument passed.
Now use an if statement to check the value returned by the function and can perform further operation regarding requirements.
Example 1:
Javascript
interface Student{ name:string;} var geek:any = { name: "Jairam" }; function instanceOfStudent(data: any): data is Student { return 'name' in data;} if (instanceOfStudent(geek)) { document.write("Student Name is "+ geek.name);}
Output:
Example 2:
Javascript
interface Bike{ companyName:string; bikeNumber:any; modelNo:any;} var bike:any = { companyName: "Engfield" }; function createName(name:any){ alert(name);} if(instanceOfBike(bike)) { createName(bike.companyName)}else{ createName("No Name is registered with that company name")} function instanceOfBike(data: any): data is Bike { return 'companyName' in data;}
Output:
Picked
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Sep, 2020"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an interface or contract of a car."
},
{
"code": null,
"e": 549,
"s": 358,
"text": "interface Audi {\n length: number;\n width: number;\n wheelbase: number;\n price:number;\n numberOfAirBags:number;\n seatingCapacity: number;\n getTyrePressure: () => number;\n}"
},
{
"code": null,
"e": 559,
"s": 549,
"text": "Approach:"
},
{
"code": null,
"e": 618,
"s": 559,
"text": "Declare an interface with a name and its type as a string."
},
{
"code": null,
"e": 680,
"s": 618,
"text": "Now create a customized function to check the interface type."
},
{
"code": null,
"e": 775,
"s": 680,
"text": "This function returns a boolean value if the name attribute is present in the argument passed."
},
{
"code": null,
"e": 901,
"s": 775,
"text": "Now use an if statement to check the value returned by the function and can perform further operation regarding requirements."
},
{
"code": null,
"e": 912,
"s": 901,
"text": "Example 1:"
},
{
"code": null,
"e": 923,
"s": 912,
"text": "Javascript"
},
{
"code": "interface Student{ name:string;} var geek:any = { name: \"Jairam\" }; function instanceOfStudent(data: any): data is Student { return 'name' in data;} if (instanceOfStudent(geek)) { document.write(\"Student Name is \"+ geek.name);}",
"e": 1171,
"s": 923,
"text": null
},
{
"code": null,
"e": 1180,
"s": 1171,
"text": "Output: "
},
{
"code": null,
"e": 1191,
"s": 1180,
"text": "Example 2:"
},
{
"code": null,
"e": 1202,
"s": 1191,
"text": "Javascript"
},
{
"code": "interface Bike{ companyName:string; bikeNumber:any; modelNo:any;} var bike:any = { companyName: \"Engfield\" }; function createName(name:any){ alert(name);} if(instanceOfBike(bike)) { createName(bike.companyName)}else{ createName(\"No Name is registered with that company name\")} function instanceOfBike(data: any): data is Bike { return 'companyName' in data;}",
"e": 1593,
"s": 1202,
"text": null
},
{
"code": null,
"e": 1602,
"s": 1593,
"text": "Output: "
},
{
"code": null,
"e": 1609,
"s": 1602,
"text": "Picked"
},
{
"code": null,
"e": 1620,
"s": 1609,
"text": "TypeScript"
},
{
"code": null,
"e": 1631,
"s": 1620,
"text": "JavaScript"
},
{
"code": null,
"e": 1648,
"s": 1631,
"text": "Web Technologies"
}
] |
How to set the Visibility of ListBox in C#? | 17 Jul, 2019
In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you can set the visibility of the ListBox using Visible Property of the ListBox.If the value of this property is set to true, then the Listbox control and its child control are visible on the screen and if the value of this property is set to false, then the Listbox control and its child control are not visible on the screen. The default value of this property is true. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the visibility of the ListBox as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the ListBox control to set the visibility of the ListBox.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the visibility of the ListBox control programmatically with the help of given syntax:
public bool Visible { get; set; }
Here, the value of this property is of System.Boolean type. The following steps show how to set the visibility of the ListBox dynamically:
Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor
ListBox lstbox = new ListBox();
// Creating ListBox using ListBox class constructor
ListBox lstbox = new ListBox();
Step 2: After creating ListBox, set the Visible property of the ListBox provided by the ListBox class.// Setting the visibility of the listbox
lstbox.Visible = false;
// Setting the visibility of the listbox
lstbox.Visible = false;
Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form
this.Controls.Add(lstbox);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(243, 80); lb.Text = "Select post"; // Adding label control to the form this.Controls.Add(lb); // Creating and setting the // properties of ListBox ListBox lstbox = new ListBox(); lstbox.Location = new Point(246, 104); lstbox.Visible = false; lstbox.Items.Add("Intern"); lstbox.Items.Add("Software Engineer"); lstbox.Items.Add("Project Manager"); lstbox.Items.Add("HR"); // Adding listbox control to the form this.Controls.Add(lstbox); }}}Output:Before setting visibility to false:After setting visibility to false:
// Add this ListBox to the form
this.Controls.Add(lstbox);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(243, 80); lb.Text = "Select post"; // Adding label control to the form this.Controls.Add(lb); // Creating and setting the // properties of ListBox ListBox lstbox = new ListBox(); lstbox.Location = new Point(246, 104); lstbox.Visible = false; lstbox.Items.Add("Intern"); lstbox.Items.Add("Software Engineer"); lstbox.Items.Add("Project Manager"); lstbox.Items.Add("HR"); // Adding listbox control to the form this.Controls.Add(lstbox); }}}
Output:
Before setting visibility to false:
After setting visibility to false:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jul, 2019"
},
{
"code": null,
"e": 678,
"s": 54,
"text": "In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you can set the visibility of the ListBox using Visible Property of the ListBox.If the value of this property is set to true, then the Listbox control and its child control are visible on the screen and if the value of this property is set to false, then the Listbox control and its child control are not visible on the screen. The default value of this property is true. You can set this property in two different ways:"
},
{
"code": null,
"e": 786,
"s": 678,
"text": "1. Design-Time: It is the easiest way to set the visibility of the ListBox as shown in the following steps:"
},
{
"code": null,
"e": 902,
"s": 786,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 1081,
"s": 902,
"text": "Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 1207,
"s": 1081,
"text": "Step 3: After drag and drop you will go to the properties of the ListBox control to set the visibility of the ListBox.Output:"
},
{
"code": null,
"e": 1215,
"s": 1207,
"text": "Output:"
},
{
"code": null,
"e": 1393,
"s": 1215,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the visibility of the ListBox control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1427,
"s": 1393,
"text": "public bool Visible { get; set; }"
},
{
"code": null,
"e": 1566,
"s": 1427,
"text": "Here, the value of this property is of System.Boolean type. The following steps show how to set the visibility of the ListBox dynamically:"
},
{
"code": null,
"e": 1742,
"s": 1566,
"text": "Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.// Creating ListBox using ListBox class constructor\nListBox lstbox = new ListBox();\n"
},
{
"code": null,
"e": 1827,
"s": 1742,
"text": "// Creating ListBox using ListBox class constructor\nListBox lstbox = new ListBox();\n"
},
{
"code": null,
"e": 1995,
"s": 1827,
"text": "Step 2: After creating ListBox, set the Visible property of the ListBox provided by the ListBox class.// Setting the visibility of the listbox\nlstbox.Visible = false;\n"
},
{
"code": null,
"e": 2061,
"s": 1995,
"text": "// Setting the visibility of the listbox\nlstbox.Visible = false;\n"
},
{
"code": null,
"e": 3351,
"s": 2061,
"text": "Step 3: And last add this ListBox control to the form using Add() method.// Add this ListBox to the form\nthis.Controls.Add(lstbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(243, 80); lb.Text = \"Select post\"; // Adding label control to the form this.Controls.Add(lb); // Creating and setting the // properties of ListBox ListBox lstbox = new ListBox(); lstbox.Location = new Point(246, 104); lstbox.Visible = false; lstbox.Items.Add(\"Intern\"); lstbox.Items.Add(\"Software Engineer\"); lstbox.Items.Add(\"Project Manager\"); lstbox.Items.Add(\"HR\"); // Adding listbox control to the form this.Controls.Add(lstbox); }}}Output:Before setting visibility to false:After setting visibility to false:"
},
{
"code": null,
"e": 3411,
"s": 3351,
"text": "// Add this ListBox to the form\nthis.Controls.Add(lstbox);\n"
},
{
"code": null,
"e": 3420,
"s": 3411,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp28 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(243, 80); lb.Text = \"Select post\"; // Adding label control to the form this.Controls.Add(lb); // Creating and setting the // properties of ListBox ListBox lstbox = new ListBox(); lstbox.Location = new Point(246, 104); lstbox.Visible = false; lstbox.Items.Add(\"Intern\"); lstbox.Items.Add(\"Software Engineer\"); lstbox.Items.Add(\"Project Manager\"); lstbox.Items.Add(\"HR\"); // Adding listbox control to the form this.Controls.Add(lstbox); }}}",
"e": 4494,
"s": 3420,
"text": null
},
{
"code": null,
"e": 4502,
"s": 4494,
"text": "Output:"
},
{
"code": null,
"e": 4538,
"s": 4502,
"text": "Before setting visibility to false:"
},
{
"code": null,
"e": 4573,
"s": 4538,
"text": "After setting visibility to false:"
},
{
"code": null,
"e": 4576,
"s": 4573,
"text": "C#"
}
] |
How to Read and Print an Integer value in C++ | 09 May, 2022
The given task is to take an integer as input from the user and print that integer in C++ language. In below program, the syntax and procedures to take the integer as input from the user is shown in C++ language.
Steps:
The user enters an integer value when asked.
This value is taken from the user with the help of cin method. The cin method, in C++, reads the value from the console into the specified variable.
Syntax:
cin >> variableOfXType;
where >> is the extraction operator
and is used along with the object cin
for reading inputs. The extraction operator
extracts the data from the object cin
which is entered using the keyboard.
For an integer value, the X is replaced with type int. The syntax of cin method becomes as follows then:
Syntax:
cin >> variableOfIntType;
This entered value is now stored in the variableOfIntType.
Now to print this value, cout method is used. The cout method, in C++, prints the value passed as the parameter to it, on the console screen.
Syntax:
cout << variableOfXType;
where << is the insertion operator.
The data needed to be displayed on the screen
is inserted in the standard output stream (cout)
using the insertion operator (<<).
For an integer value, the X is replaced with type int. The syntax of cout() method becomes as follows then:
Syntax:
cout << variableOfIntType;
Hence, the integer value is successfully read and printed.
Program:
C++
// C++ program to take an integer// as input and print it #include <iostream>using namespace std; int main(){ // Declare the variables int num; // Input the integer cout << "Enter the integer: "; cin >> num; // Display the integer cout << "Entered integer is: " << num; return 0;}
Output:
Enter the integer: 10
Entered integer is: 10
sweetyty
CPP-Basics
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "The given task is to take an integer as input from the user and print that integer in C++ language. In below program, the syntax and procedures to take the integer as input from the user is shown in C++ language. "
},
{
"code": null,
"e": 250,
"s": 243,
"text": "Steps:"
},
{
"code": null,
"e": 295,
"s": 250,
"text": "The user enters an integer value when asked."
},
{
"code": null,
"e": 445,
"s": 295,
"text": "This value is taken from the user with the help of cin method. The cin method, in C++, reads the value from the console into the specified variable. "
},
{
"code": null,
"e": 453,
"s": 445,
"text": "Syntax:"
},
{
"code": null,
"e": 672,
"s": 453,
"text": "cin >> variableOfXType;\n\nwhere >> is the extraction operator\nand is used along with the object cin\nfor reading inputs. The extraction operator \nextracts the data from the object cin\nwhich is entered using the keyboard."
},
{
"code": null,
"e": 778,
"s": 672,
"text": "For an integer value, the X is replaced with type int. The syntax of cin method becomes as follows then: "
},
{
"code": null,
"e": 786,
"s": 778,
"text": "Syntax:"
},
{
"code": null,
"e": 812,
"s": 786,
"text": "cin >> variableOfIntType;"
},
{
"code": null,
"e": 871,
"s": 812,
"text": "This entered value is now stored in the variableOfIntType."
},
{
"code": null,
"e": 1014,
"s": 871,
"text": "Now to print this value, cout method is used. The cout method, in C++, prints the value passed as the parameter to it, on the console screen. "
},
{
"code": null,
"e": 1022,
"s": 1014,
"text": "Syntax:"
},
{
"code": null,
"e": 1215,
"s": 1022,
"text": "cout << variableOfXType;\n\nwhere << is the insertion operator.\nThe data needed to be displayed on the screen \nis inserted in the standard output stream (cout)\nusing the insertion operator (<<)."
},
{
"code": null,
"e": 1324,
"s": 1215,
"text": "For an integer value, the X is replaced with type int. The syntax of cout() method becomes as follows then: "
},
{
"code": null,
"e": 1332,
"s": 1324,
"text": "Syntax:"
},
{
"code": null,
"e": 1359,
"s": 1332,
"text": "cout << variableOfIntType;"
},
{
"code": null,
"e": 1418,
"s": 1359,
"text": "Hence, the integer value is successfully read and printed."
},
{
"code": null,
"e": 1428,
"s": 1418,
"text": "Program: "
},
{
"code": null,
"e": 1432,
"s": 1428,
"text": "C++"
},
{
"code": "// C++ program to take an integer// as input and print it #include <iostream>using namespace std; int main(){ // Declare the variables int num; // Input the integer cout << \"Enter the integer: \"; cin >> num; // Display the integer cout << \"Entered integer is: \" << num; return 0;}",
"e": 1741,
"s": 1432,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1741,
"text": "Output:"
},
{
"code": null,
"e": 1794,
"s": 1749,
"text": "Enter the integer: 10\nEntered integer is: 10"
},
{
"code": null,
"e": 1803,
"s": 1794,
"text": "sweetyty"
},
{
"code": null,
"e": 1814,
"s": 1803,
"text": "CPP-Basics"
},
{
"code": null,
"e": 1818,
"s": 1814,
"text": "C++"
},
{
"code": null,
"e": 1837,
"s": 1818,
"text": "School Programming"
},
{
"code": null,
"e": 1841,
"s": 1837,
"text": "CPP"
}
] |
move_to_element_with_offset method – Action Chains in Selenium Python | 15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around move_to_element_with_offset method on Action Chains in Python Selenium. move_to_element_with_offset method is used to move the mouse by an offset of the specified element. Offsets are relative to the top-left corner of the element.Syntax –
move_to_element_with_offset(to_element, xoffset, yoffset)
to_element: The WebElement to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use move_to_element_with_offset method as an Action chain as below –
move_to_element_with_offset(to_element=element, 100, 200)
To demonstrate, move_to_element_with_offset method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # perform the operationaction.move_to_element_with_offset(element, 100, 200).click().perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 720,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around move_to_element_with_offset method on Action Chains in Python Selenium. move_to_element_with_offset method is used to move the mouse by an offset of the specified element. Offsets are relative to the top-left corner of the element.Syntax –"
},
{
"code": null,
"e": 778,
"s": 720,
"text": "move_to_element_with_offset(to_element, xoffset, yoffset)"
},
{
"code": null,
"e": 817,
"s": 778,
"text": "to_element: The WebElement to move to."
},
{
"code": null,
"e": 847,
"s": 817,
"text": "xoffset: X offset to move to."
},
{
"code": null,
"e": 877,
"s": 847,
"text": "yoffset: Y offset to move to."
},
{
"code": null,
"e": 887,
"s": 877,
"text": "Example –"
},
{
"code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />",
"e": 941,
"s": 887,
"text": null
},
{
"code": null,
"e": 1022,
"s": 941,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": "element = driver.find_element_by_id(\"passwd-id\")element = driver.find_element_by_name(\"passwd\")",
"e": 1118,
"s": 1022,
"text": null
},
{
"code": null,
"e": 1199,
"s": 1118,
"text": "Now one can use move_to_element_with_offset method as an Action chain as below –"
},
{
"code": null,
"e": 1258,
"s": 1199,
"text": "move_to_element_with_offset(to_element=element, 100, 200)\n"
},
{
"code": null,
"e": 1417,
"s": 1258,
"text": "To demonstrate, move_to_element_with_offset method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element."
},
{
"code": null,
"e": 1427,
"s": 1417,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # perform the operationaction.move_to_element_with_offset(element, 100, 200).click().perform()",
"e": 1914,
"s": 1427,
"text": null
},
{
"code": null,
"e": 1923,
"s": 1914,
"text": "Output –"
},
{
"code": null,
"e": 1939,
"s": 1923,
"text": "Python-selenium"
},
{
"code": null,
"e": 1948,
"s": 1939,
"text": "selenium"
},
{
"code": null,
"e": 1955,
"s": 1948,
"text": "Python"
}
] |
Python program to count the number of blank spaces in a text file | 26 Nov, 2020
All programs need input to process and after processing gives the output. Python support file handling and allow user to handle files. The concept of file handling has stretched over various other languages, But the implementation is either lengthy or complicated. Python treats file differently as text and binary,One thing to note while writing data to a file is that its consistency and integrity should be maintained. Once you have stored your data on a file now the most important thing is its retrieval because the computer data store as bits of 1s and 0s and if its retrieval is not done properly then it becomes completely useless and data is said to be corrupted. Hence, writing as well as reading is also an important aspect of File Handling in Python.
‘ ‘ (Space) also comes under Printable ASCII Character type, while NULL is not Printable ASCII Character type.
How to write to a file using Python?
Open a file to write.Count the number of spaces in that text file.Close a file.
Open a file to write.
Count the number of spaces in that text file.
Close a file.
Here our text file.
Implementation:
Methods #1: Using isspace() function.
Firstly, we will open our text file and store that text file in that variable. A loop is used to count spaces in a text file. if condition ( char.isspace()) to test all the condition, if it returns True then the count will be incremented by 1. After testing all the character’s loop will return False and terminate itself. Finally, the program will display the total number of spaces.
Python3
# this will open the file and store# in "file" variablefile = open("test1.txt", "r") count = 0while True: # this will read each character # and store in char char = file.read(1) if char.isspace(): count += 1 if not char: break print(count)
Output:
5
Note – isspace() also count new line character therefore it is showing output as 6.
Methods #2: Using Loop:
Firstly, we will open our text file and store that text file in that variable. A loop is used to count spaces in a text file. if condition ( char == ” ” ) to test all the condition, if it returns True then the count will be incremented by 1. After testing all the character’s loop will return False and terminate itself. Finally, the program will display the total number of spaces.
Python3
# this will open the file and store in# "file" variablefile = open("test1.txt", "r") count = 0while True: # this will read each character # and store in char char = file.read(1) if char == " ": count += 1 if not char: break print(count)
Output:
4
Methods #3: Using a python module “functools”.
A Partial function is a function for a particular argument value. They can be created in python by using ‘partial’ from the “functools” library.
Python3
import functools with open("test1.txt") as file: file_char = functools.partial(file.read, 1) for char in iter(file_char, " "): if char == " ": count += 1 print("count: ", count)
Output:
4
Python file-handling-programs
python-file-handling
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 791,
"s": 28,
"text": "All programs need input to process and after processing gives the output. Python support file handling and allow user to handle files. The concept of file handling has stretched over various other languages, But the implementation is either lengthy or complicated. Python treats file differently as text and binary,One thing to note while writing data to a file is that its consistency and integrity should be maintained. Once you have stored your data on a file now the most important thing is its retrieval because the computer data store as bits of 1s and 0s and if its retrieval is not done properly then it becomes completely useless and data is said to be corrupted. Hence, writing as well as reading is also an important aspect of File Handling in Python."
},
{
"code": null,
"e": 905,
"s": 791,
"text": "‘ ‘ (Space) also comes under Printable ASCII Character type, while NULL is not Printable ASCII Character type. "
},
{
"code": null,
"e": 943,
"s": 905,
"text": "How to write to a file using Python? "
},
{
"code": null,
"e": 1023,
"s": 943,
"text": "Open a file to write.Count the number of spaces in that text file.Close a file."
},
{
"code": null,
"e": 1045,
"s": 1023,
"text": "Open a file to write."
},
{
"code": null,
"e": 1091,
"s": 1045,
"text": "Count the number of spaces in that text file."
},
{
"code": null,
"e": 1105,
"s": 1091,
"text": "Close a file."
},
{
"code": null,
"e": 1125,
"s": 1105,
"text": "Here our text file."
},
{
"code": null,
"e": 1141,
"s": 1125,
"text": "Implementation:"
},
{
"code": null,
"e": 1179,
"s": 1141,
"text": "Methods #1: Using isspace() function."
},
{
"code": null,
"e": 1564,
"s": 1179,
"text": "Firstly, we will open our text file and store that text file in that variable. A loop is used to count spaces in a text file. if condition ( char.isspace()) to test all the condition, if it returns True then the count will be incremented by 1. After testing all the character’s loop will return False and terminate itself. Finally, the program will display the total number of spaces."
},
{
"code": null,
"e": 1572,
"s": 1564,
"text": "Python3"
},
{
"code": "# this will open the file and store# in \"file\" variablefile = open(\"test1.txt\", \"r\") count = 0while True: # this will read each character # and store in char char = file.read(1) if char.isspace(): count += 1 if not char: break print(count)",
"e": 1853,
"s": 1572,
"text": null
},
{
"code": null,
"e": 1861,
"s": 1853,
"text": "Output:"
},
{
"code": null,
"e": 1864,
"s": 1861,
"text": "5\n"
},
{
"code": null,
"e": 1950,
"s": 1864,
"text": "Note – isspace() also count new line character therefore it is showing output as 6. "
},
{
"code": null,
"e": 1974,
"s": 1950,
"text": "Methods #2: Using Loop:"
},
{
"code": null,
"e": 2357,
"s": 1974,
"text": "Firstly, we will open our text file and store that text file in that variable. A loop is used to count spaces in a text file. if condition ( char == ” ” ) to test all the condition, if it returns True then the count will be incremented by 1. After testing all the character’s loop will return False and terminate itself. Finally, the program will display the total number of spaces."
},
{
"code": null,
"e": 2365,
"s": 2357,
"text": "Python3"
},
{
"code": "# this will open the file and store in# \"file\" variablefile = open(\"test1.txt\", \"r\") count = 0while True: # this will read each character # and store in char char = file.read(1) if char == \" \": count += 1 if not char: break print(count)",
"e": 2643,
"s": 2365,
"text": null
},
{
"code": null,
"e": 2651,
"s": 2643,
"text": "Output:"
},
{
"code": null,
"e": 2654,
"s": 2651,
"text": "4\n"
},
{
"code": null,
"e": 2701,
"s": 2654,
"text": "Methods #3: Using a python module “functools”."
},
{
"code": null,
"e": 2846,
"s": 2701,
"text": "A Partial function is a function for a particular argument value. They can be created in python by using ‘partial’ from the “functools” library."
},
{
"code": null,
"e": 2854,
"s": 2846,
"text": "Python3"
},
{
"code": "import functools with open(\"test1.txt\") as file: file_char = functools.partial(file.read, 1) for char in iter(file_char, \" \"): if char == \" \": count += 1 print(\"count: \", count)",
"e": 3078,
"s": 2854,
"text": null
},
{
"code": null,
"e": 3086,
"s": 3078,
"text": "Output:"
},
{
"code": null,
"e": 3089,
"s": 3086,
"text": "4\n"
},
{
"code": null,
"e": 3119,
"s": 3089,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 3140,
"s": 3119,
"text": "python-file-handling"
},
{
"code": null,
"e": 3147,
"s": 3140,
"text": "Python"
},
{
"code": null,
"e": 3163,
"s": 3147,
"text": "Python Programs"
},
{
"code": null,
"e": 3261,
"s": 3163,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3293,
"s": 3261,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3320,
"s": 3293,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3351,
"s": 3320,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3374,
"s": 3351,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3395,
"s": 3374,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3417,
"s": 3395,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3456,
"s": 3417,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3494,
"s": 3456,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3531,
"s": 3494,
"text": "Python Program for Fibonacci numbers"
}
] |
Difference between Data Lake and Data Warehouse | 09 Feb, 2022
1. Data Lake : It is the concept where all sorts of data can be landed at a low cost but exceedingly adaptable storage/zone.to be examined afterward for potential insights. It is another advancement of what ETL/DWH pros called the Landing Zone of data. Only presently we are looking at ALL sorts of information .independent of construction, structure, metadata, etc. One of the thoughts behind Data Lake is that presently innovation has made it conceivable to store ALL information that a firm generates/buys (prior it would be a case where the firm HAD to select the pertinent information and store in a structured distribution center.).
2. Data Warehouse : It is essentially a social database facilitated on cloud or an endeavor centralized computer server. It collects information from shifted, heterogeneous sources for the most reason for supporting the investigation and choice-making preparation of administration of any business. A data warehouse is characterized as Subject-oriented, coordinates, time-variant, and non-unstable collection of information in arrange to supply business insights and help within the choice-making process.
Difference between Data Lake and Data Warehouse
ashushrma378
varshagumber28
Picked
DBMS
Difference Between
GBlog
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 668,
"s": 28,
"text": "1. Data Lake : It is the concept where all sorts of data can be landed at a low cost but exceedingly adaptable storage/zone.to be examined afterward for potential insights. It is another advancement of what ETL/DWH pros called the Landing Zone of data. Only presently we are looking at ALL sorts of information .independent of construction, structure, metadata, etc. One of the thoughts behind Data Lake is that presently innovation has made it conceivable to store ALL information that a firm generates/buys (prior it would be a case where the firm HAD to select the pertinent information and store in a structured distribution center.). "
},
{
"code": null,
"e": 1175,
"s": 668,
"text": "2. Data Warehouse : It is essentially a social database facilitated on cloud or an endeavor centralized computer server. It collects information from shifted, heterogeneous sources for the most reason for supporting the investigation and choice-making preparation of administration of any business. A data warehouse is characterized as Subject-oriented, coordinates, time-variant, and non-unstable collection of information in arrange to supply business insights and help within the choice-making process. "
},
{
"code": null,
"e": 1224,
"s": 1175,
"text": "Difference between Data Lake and Data Warehouse "
},
{
"code": null,
"e": 1237,
"s": 1224,
"text": "ashushrma378"
},
{
"code": null,
"e": 1252,
"s": 1237,
"text": "varshagumber28"
},
{
"code": null,
"e": 1259,
"s": 1252,
"text": "Picked"
},
{
"code": null,
"e": 1264,
"s": 1259,
"text": "DBMS"
},
{
"code": null,
"e": 1283,
"s": 1264,
"text": "Difference Between"
},
{
"code": null,
"e": 1289,
"s": 1283,
"text": "GBlog"
},
{
"code": null,
"e": 1294,
"s": 1289,
"text": "DBMS"
}
] |
New self vs. new static in PHP | 21 May, 2020
New self: The self is keyword in PHP. It refers to the same class in which the new keyword is actually written. It refers to the class members, but not for any particular object. This is because the static members(variables or functions) are class members shared by all the objects of the class. The function called self::theFunction() behaves like “I will execute in the context of the class whom I physically belong to.”(Assuming the inheritance scenario).
Example: Suppose we make this call to the static model function in the Car class – since it is a static function we can, of course, call the function directly using only the class name:<?phpclass Car{ public static function model() { self::getModel(); } protected static function getModel() { echo "I am a Car!"; } } class Mercedes extends Car{ protected static function getModel() { echo "I am a Mercedes!"; } }Car::model();echo("\n");Mercedes::model();?>
<?phpclass Car{ public static function model() { self::getModel(); } protected static function getModel() { echo "I am a Car!"; } } class Mercedes extends Car{ protected static function getModel() { echo "I am a Mercedes!"; } }Car::model();echo("\n");Mercedes::model();?>
Output:I am a Car!
I am a Car!
I am a Car!
I am a Car!
Explanation: The model function is defined inside the Car class, and it is not overridden by the Mercedes class– but the model function is of course inherited by the Mercedes class.As a result, when we call the version of the model inside the Mercedes class, the scope of the function is still inside the Car class– because the function definition is inside the Car class. The way the keyword “self” works are that it will call the current class’s implementation of the getModel function – and since the model function is defined inside the Car class, the current class would be the Car class.So, it will call the Car class implementation of getModel and NOT the Mercedes class implementation. This behavior may be considered undesirable because it is not polymorphic, and is not aligned with the object-oriented design principles. But, there is an alternative solution that can get us that kind of behavior– and this is where the static keyword becomes useful.
So, it will call the Car class implementation of getModel and NOT the Mercedes class implementation. This behavior may be considered undesirable because it is not polymorphic, and is not aligned with the object-oriented design principles. But, there is an alternative solution that can get us that kind of behavior– and this is where the static keyword becomes useful.
New static: The static is a keyword in PHP. Static in PHP 5.3’s late static bindings, refers to whatever class in the hierarchy you called the method on. The most common usage of static is for defining static methods. Such methods are part of a class, just like any method, though they may be used even without any such instantiated object. The function called static::theFunction() behaves like “I will execute in the context of the class, which has been actually called by the outside world”.
Example:<?phpclass Car{ public static function model() { static::getModel(); } protected static function getModel() { echo "I am a Car!"; }} class Mercedes extends Car{ protected static function getModel() { echo "I am a Mercedes!"; } }Car::model();echo("\n");Mercedes::model();?>
<?phpclass Car{ public static function model() { static::getModel(); } protected static function getModel() { echo "I am a Car!"; }} class Mercedes extends Car{ protected static function getModel() { echo "I am a Mercedes!"; } }Car::model();echo("\n");Mercedes::model();?>
Output:I am a Car!
I am a Mercedes!
I am a Car!
I am a Mercedes!
PHP new self vs new static: Now that we changed the code in our example to use static instead of self, you can see the difference is that self references the current class, whereas the static keyword allows the function to bind to the calling class at runtime. The difference between self and static keywords is fairly easy to understand with an example.
<?phpclass g { /* The new self */ public static function get_self() { return new self(); } /* The new static */ public static function get_static() { return new static(); }} class f extends g {} echo get_class(f::get_self()); // gecho get_class(f::get_static()); // fecho get_class(g::get_self()); // g?>
Output: In this example of code, f inherits both methods from g. The self invocation is bound to A because it is defined in g’s implementation of the method, whereas static is bound to the called class.
gfg
PHP-Misc
Picked
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2020"
},
{
"code": null,
"e": 487,
"s": 28,
"text": "New self: The self is keyword in PHP. It refers to the same class in which the new keyword is actually written. It refers to the class members, but not for any particular object. This is because the static members(variables or functions) are class members shared by all the objects of the class. The function called self::theFunction() behaves like “I will execute in the context of the class whom I physically belong to.”(Assuming the inheritance scenario)."
},
{
"code": null,
"e": 998,
"s": 487,
"text": "Example: Suppose we make this call to the static model function in the Car class – since it is a static function we can, of course, call the function directly using only the class name:<?phpclass Car{ public static function model() { self::getModel(); } protected static function getModel() { echo \"I am a Car!\"; } } class Mercedes extends Car{ protected static function getModel() { echo \"I am a Mercedes!\"; } }Car::model();echo(\"\\n\");Mercedes::model();?>"
},
{
"code": "<?phpclass Car{ public static function model() { self::getModel(); } protected static function getModel() { echo \"I am a Car!\"; } } class Mercedes extends Car{ protected static function getModel() { echo \"I am a Mercedes!\"; } }Car::model();echo(\"\\n\");Mercedes::model();?>",
"e": 1324,
"s": 998,
"text": null
},
{
"code": null,
"e": 1355,
"s": 1324,
"text": "Output:I am a Car!\nI am a Car!"
},
{
"code": null,
"e": 1379,
"s": 1355,
"text": "I am a Car!\nI am a Car!"
},
{
"code": null,
"e": 2341,
"s": 1379,
"text": "Explanation: The model function is defined inside the Car class, and it is not overridden by the Mercedes class– but the model function is of course inherited by the Mercedes class.As a result, when we call the version of the model inside the Mercedes class, the scope of the function is still inside the Car class– because the function definition is inside the Car class. The way the keyword “self” works are that it will call the current class’s implementation of the getModel function – and since the model function is defined inside the Car class, the current class would be the Car class.So, it will call the Car class implementation of getModel and NOT the Mercedes class implementation. This behavior may be considered undesirable because it is not polymorphic, and is not aligned with the object-oriented design principles. But, there is an alternative solution that can get us that kind of behavior– and this is where the static keyword becomes useful."
},
{
"code": null,
"e": 2710,
"s": 2341,
"text": "So, it will call the Car class implementation of getModel and NOT the Mercedes class implementation. This behavior may be considered undesirable because it is not polymorphic, and is not aligned with the object-oriented design principles. But, there is an alternative solution that can get us that kind of behavior– and this is where the static keyword becomes useful."
},
{
"code": null,
"e": 3205,
"s": 2710,
"text": "New static: The static is a keyword in PHP. Static in PHP 5.3’s late static bindings, refers to whatever class in the hierarchy you called the method on. The most common usage of static is for defining static methods. Such methods are part of a class, just like any method, though they may be used even without any such instantiated object. The function called static::theFunction() behaves like “I will execute in the context of the class, which has been actually called by the outside world”."
},
{
"code": null,
"e": 3541,
"s": 3205,
"text": "Example:<?phpclass Car{ public static function model() { static::getModel(); } protected static function getModel() { echo \"I am a Car!\"; }} class Mercedes extends Car{ protected static function getModel() { echo \"I am a Mercedes!\"; } }Car::model();echo(\"\\n\");Mercedes::model();?>"
},
{
"code": "<?phpclass Car{ public static function model() { static::getModel(); } protected static function getModel() { echo \"I am a Car!\"; }} class Mercedes extends Car{ protected static function getModel() { echo \"I am a Mercedes!\"; } }Car::model();echo(\"\\n\");Mercedes::model();?>",
"e": 3869,
"s": 3541,
"text": null
},
{
"code": null,
"e": 3905,
"s": 3869,
"text": "Output:I am a Car!\nI am a Mercedes!"
},
{
"code": null,
"e": 3934,
"s": 3905,
"text": "I am a Car!\nI am a Mercedes!"
},
{
"code": null,
"e": 4289,
"s": 3934,
"text": "PHP new self vs new static: Now that we changed the code in our example to use static instead of self, you can see the difference is that self references the current class, whereas the static keyword allows the function to bind to the calling class at runtime. The difference between self and static keywords is fairly easy to understand with an example."
},
{
"code": "<?phpclass g { /* The new self */ public static function get_self() { return new self(); } /* The new static */ public static function get_static() { return new static(); }} class f extends g {} echo get_class(f::get_self()); // gecho get_class(f::get_static()); // fecho get_class(g::get_self()); // g?>",
"e": 4631,
"s": 4289,
"text": null
},
{
"code": null,
"e": 4834,
"s": 4631,
"text": "Output: In this example of code, f inherits both methods from g. The self invocation is bound to A because it is defined in g’s implementation of the method, whereas static is bound to the called class."
},
{
"code": null,
"e": 4838,
"s": 4834,
"text": "gfg"
},
{
"code": null,
"e": 4847,
"s": 4838,
"text": "PHP-Misc"
},
{
"code": null,
"e": 4854,
"s": 4847,
"text": "Picked"
},
{
"code": null,
"e": 4858,
"s": 4854,
"text": "PHP"
},
{
"code": null,
"e": 4875,
"s": 4858,
"text": "Web Technologies"
},
{
"code": null,
"e": 4902,
"s": 4875,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4906,
"s": 4902,
"text": "PHP"
}
] |
How to make whole row in a table clickable as link in Bootstrap ? | 19 Jun, 2019
Tables in Bootstrap can be formed either using traditional <table> tags or using the in-built ‘grid’ system. Earlier, <table> tags were often employed to designing grids for the sites, but nowadays with flexbox and table display properties in CSS, it is easier to just use divs.
In the following examples, we’ll see how to make a complete row clickable as a link for both the cases.
Now to make the entire row as clickable, one may think of wrapping the content of <tr> tag into a link (<a>) element. But that would result in nothing. Actually, it’s an invalid HTML approach and should be avoided.
We can call onclick method on <tr> tag and then navigate to whatever location as per the requirements. Here’s an example explaining how to do so.
In this case, the markup for an example table looks like this:
<table>
<tr>
<th>IDE</th>
<th>Link</th>
</tr>
<tr>
<td>GeeksforGeeks</td>
<td>https://ide.geeksforgeeks.org/Y4U8qx</td>
</tr>
</table>
Example:1
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" /> <title>Table Row Clickable</title> <style> th { background: green; border: 2px solid black; } .clickable { height: 50px; background: gray; border: 2px solid black; } .clickable:hover { background: green; } </style></head> <body> <h1 style="color:green;text-align:center;">GeeksforGeeks</h1> <div class="container"> <table class="w-100"> <tr class="text-center"> <th>IDE</th> <th>link</th> </tr> <tr class="clickable text-center" onclick="window.location='https://ide.geeksforgeeks.org/Y4U8qx'"> <td>GeeksforGeeks</td> <td>https://ide.geeksforgeeks.org/Y4U8qx</td> </tr> </table> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script></body> </html>
Before clicking the row:
After clicking the row:GeeksforGeeks IDE will open
GeeksforGeeks IDE will open
Building tables using Bootstrap Grid System is much easier and provide a lot more flexibility than using <table> tag.
To make the entire row as clickable in this case, one can use a link <a> tag to wrap its content. Here’s an example of doing so.
The exact same table in the previous example can be re-designed using Bootstrap as follows:
<div class="row">
<div class="col-6"><b>IDE</b></div>
<div class="col-6"><b>Link</b></div>
<div class="col-6 py-3">GeeksforGeeks</div>
<div class="col-6 py-3">https://ide.geeksforgeeks.org/Y4U8qx</div>
</div>
Example:
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" /> <title>Table Row Clickable</title> <style> .clickable { height: 40px; } </style></head> <body> <h1 style="color:green;text-align:center;">GeeksforGeeks</h1> <div class="container"> <center class="row"> <div style="border:2px solid black" class="col-6 py-2"> <b>IDE</b> </div> <div style="border:2px solid black" class="col-6 py-2"> <b>Link</b> </div> <div style="border:2px solid black" class="col-12"> <a class="row clickable" href="https://ide.geeksforgeeks.org/Y4U8qx"> <div class="col-5 py-2"> GeeksforGeeks </div> <div class="col-5 py-2"> https://ide.geeksforgeeks.org/Y4U8qx </div> </a> </div> </center> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script></body> </html>
Before clicking the row:
After clicking the row:GeeksforGeeks IDE will open
GeeksforGeeks IDE will open
Bootstrap-Misc
Picked
Bootstrap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to set vertical alignment in Bootstrap ?
How to toggle password visibility in forms using Bootstrap-icons ?
How to place table text into center using Bootstrap?
JavaScript Project on Todo List
How to add icons in project using Bootstrap ?
How to add and remove input fields dynamically using jQuery with Bootstrap ?
How to change background color of table rows or individual cells in Bootstrap ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 307,
"s": 28,
"text": "Tables in Bootstrap can be formed either using traditional <table> tags or using the in-built ‘grid’ system. Earlier, <table> tags were often employed to designing grids for the sites, but nowadays with flexbox and table display properties in CSS, it is easier to just use divs."
},
{
"code": null,
"e": 411,
"s": 307,
"text": "In the following examples, we’ll see how to make a complete row clickable as a link for both the cases."
},
{
"code": null,
"e": 626,
"s": 411,
"text": "Now to make the entire row as clickable, one may think of wrapping the content of <tr> tag into a link (<a>) element. But that would result in nothing. Actually, it’s an invalid HTML approach and should be avoided."
},
{
"code": null,
"e": 772,
"s": 626,
"text": "We can call onclick method on <tr> tag and then navigate to whatever location as per the requirements. Here’s an example explaining how to do so."
},
{
"code": null,
"e": 835,
"s": 772,
"text": "In this case, the markup for an example table looks like this:"
},
{
"code": null,
"e": 996,
"s": 835,
"text": "<table>\n <tr>\n <th>IDE</th>\n <th>Link</th>\n </tr>\n <tr>\n <td>GeeksforGeeks</td>\n <td>https://ide.geeksforgeeks.org/Y4U8qx</td>\n </tr>\n</table>"
},
{
"code": null,
"e": 1006,
"s": 996,
"text": "Example:1"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" /> <title>Table Row Clickable</title> <style> th { background: green; border: 2px solid black; } .clickable { height: 50px; background: gray; border: 2px solid black; } .clickable:hover { background: green; } </style></head> <body> <h1 style=\"color:green;text-align:center;\">GeeksforGeeks</h1> <div class=\"container\"> <table class=\"w-100\"> <tr class=\"text-center\"> <th>IDE</th> <th>link</th> </tr> <tr class=\"clickable text-center\" onclick=\"window.location='https://ide.geeksforgeeks.org/Y4U8qx'\"> <td>GeeksforGeeks</td> <td>https://ide.geeksforgeeks.org/Y4U8qx</td> </tr> </table> </div> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script></body> </html>",
"e": 2335,
"s": 1006,
"text": null
},
{
"code": null,
"e": 2360,
"s": 2335,
"text": "Before clicking the row:"
},
{
"code": null,
"e": 2411,
"s": 2360,
"text": "After clicking the row:GeeksforGeeks IDE will open"
},
{
"code": null,
"e": 2439,
"s": 2411,
"text": "GeeksforGeeks IDE will open"
},
{
"code": null,
"e": 2557,
"s": 2439,
"text": "Building tables using Bootstrap Grid System is much easier and provide a lot more flexibility than using <table> tag."
},
{
"code": null,
"e": 2686,
"s": 2557,
"text": "To make the entire row as clickable in this case, one can use a link <a> tag to wrap its content. Here’s an example of doing so."
},
{
"code": null,
"e": 2778,
"s": 2686,
"text": "The exact same table in the previous example can be re-designed using Bootstrap as follows:"
},
{
"code": null,
"e": 3000,
"s": 2778,
"text": "<div class=\"row\">\n <div class=\"col-6\"><b>IDE</b></div>\n <div class=\"col-6\"><b>Link</b></div>\n <div class=\"col-6 py-3\">GeeksforGeeks</div>\n <div class=\"col-6 py-3\">https://ide.geeksforgeeks.org/Y4U8qx</div>\n</div>\n"
},
{
"code": null,
"e": 3009,
"s": 3000,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" /> <title>Table Row Clickable</title> <style> .clickable { height: 40px; } </style></head> <body> <h1 style=\"color:green;text-align:center;\">GeeksforGeeks</h1> <div class=\"container\"> <center class=\"row\"> <div style=\"border:2px solid black\" class=\"col-6 py-2\"> <b>IDE</b> </div> <div style=\"border:2px solid black\" class=\"col-6 py-2\"> <b>Link</b> </div> <div style=\"border:2px solid black\" class=\"col-12\"> <a class=\"row clickable\" href=\"https://ide.geeksforgeeks.org/Y4U8qx\"> <div class=\"col-5 py-2\"> GeeksforGeeks </div> <div class=\"col-5 py-2\"> https://ide.geeksforgeeks.org/Y4U8qx </div> </a> </div> </center> </div> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\"></script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script></body> </html>",
"e": 4438,
"s": 3009,
"text": null
},
{
"code": null,
"e": 4463,
"s": 4438,
"text": "Before clicking the row:"
},
{
"code": null,
"e": 4514,
"s": 4463,
"text": "After clicking the row:GeeksforGeeks IDE will open"
},
{
"code": null,
"e": 4542,
"s": 4514,
"text": "GeeksforGeeks IDE will open"
},
{
"code": null,
"e": 4557,
"s": 4542,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 4564,
"s": 4557,
"text": "Picked"
},
{
"code": null,
"e": 4574,
"s": 4564,
"text": "Bootstrap"
},
{
"code": null,
"e": 4672,
"s": 4574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4713,
"s": 4672,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 4746,
"s": 4713,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 4772,
"s": 4746,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 4817,
"s": 4772,
"text": "How to set vertical alignment in Bootstrap ?"
},
{
"code": null,
"e": 4884,
"s": 4817,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 4937,
"s": 4884,
"text": "How to place table text into center using Bootstrap?"
},
{
"code": null,
"e": 4969,
"s": 4937,
"text": "JavaScript Project on Todo List"
},
{
"code": null,
"e": 5015,
"s": 4969,
"text": "How to add icons in project using Bootstrap ?"
},
{
"code": null,
"e": 5092,
"s": 5015,
"text": "How to add and remove input fields dynamically using jQuery with Bootstrap ?"
}
] |
MessageDigest getInstance() method in Java with Examples | 09 Jun, 2020
The getInstance() method of java.security.MessageDigest class used to return a object of MessageDigest type that applys the assigned MessageDigest algorithm.
Syntax:
public static MessageDigest
getInstance(String algorithm)
throws NoSuchAlgorithmException
Parameters: This method accepts the name of the standard Algorithm as a parameter.
Return Value: This method provides an object of type MessageDigest.
Exception: This method throws following exception:
NoSuchAlgorithmException: if no provider supports an message digest spi application for the particular algorithm.
NullPointerException: if algorithm is null.
Below are the examples to illustrate the getInstance() method:
Example 1:
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of MessageDigest // and getting instance // By using getInstance() method MessageDigest sr = MessageDigest.getInstance("MD5"); // getting the status of MessageDigest object String str = sr.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
Status : MD5 Message Digest from SUN, <initialized>
Example 2: To show NoSuchAlgorithmException
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of MessageDigest // and getting instance // By using getInstance() method MessageDigest sr = MessageDigest.getInstance("GFG"); // getting the status of MessageDigest object String str = sr.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
Exception thrown :
java.security.NoSuchAlgorithmException:
GFG MessageDigest not available
This getInstance() method of java.security.MessageDigest class provides an object of MessageDigest type that applys the assigned MessageDigest algorithm and assigned provider object.
Syntax:
public static MessageDigest
getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException
Parameters: This method seeks the following arguments as a parameters:
algorithm: which is the name of the algorithm to be specified in this instance.
provider: which is the name of the provider to be specified in this instance
Return Value: This method provides an object of type MessageDigest.
Exception: This method throws following exceptions:
NoSuchAlgorithmException:– if no MessageDigestSpi implementation for the particular algorithm is available from the particular Provider .
IllegalArgumentException: if the provider is null.
NullPointerException: if algorithm is null
Below are the examples to illustrate the getInstance() method:
Example 1:
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of MessageDigest // and getting instance // By using getInstance() method MessageDigest sr = MessageDigest.getInstance( "SHA-384", "SUN"); // getting the status of MessageDigest object String str = sr.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchProviderException e) { System.out.println("Exception thrown : " + e); } }}
Status : SHA-384 Message Digest from SUN, <initialized>
Example 2: To show NoSuchAlgorithmException
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of MessageDigest // and getting instance // By using getInstance() method MessageDigest sr = MessageDigest.getInstance( "GFG", "SUN"); // getting the status of MessageDigest object String str = sr.toString(); // printing the status System.out.println("Status : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchProviderException e) { System.out.println("Exception thrown : " + e); } }}
Exception thrown :
java.security.NoSuchAlgorithmException:
no such algorithm: GFG for provider SUN
Reference: https://docs.oracle.com/javase/9/docs/api/java/security/MessageDigest.html#getInstance-java.lang.String-java.lang.String-
Akanksha_Rai
Java-Functions
Java-MessageDigest
Java-security package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2020"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "The getInstance() method of java.security.MessageDigest class used to return a object of MessageDigest type that applys the assigned MessageDigest algorithm."
},
{
"code": null,
"e": 194,
"s": 186,
"text": "Syntax:"
},
{
"code": null,
"e": 288,
"s": 194,
"text": "public static MessageDigest\n getInstance(String algorithm)\n throws NoSuchAlgorithmException"
},
{
"code": null,
"e": 371,
"s": 288,
"text": "Parameters: This method accepts the name of the standard Algorithm as a parameter."
},
{
"code": null,
"e": 439,
"s": 371,
"text": "Return Value: This method provides an object of type MessageDigest."
},
{
"code": null,
"e": 490,
"s": 439,
"text": "Exception: This method throws following exception:"
},
{
"code": null,
"e": 604,
"s": 490,
"text": "NoSuchAlgorithmException: if no provider supports an message digest spi application for the particular algorithm."
},
{
"code": null,
"e": 648,
"s": 604,
"text": "NullPointerException: if algorithm is null."
},
{
"code": null,
"e": 711,
"s": 648,
"text": "Below are the examples to illustrate the getInstance() method:"
},
{
"code": null,
"e": 722,
"s": 711,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of MessageDigest // and getting instance // By using getInstance() method MessageDigest sr = MessageDigest.getInstance(\"MD5\"); // getting the status of MessageDigest object String str = sr.toString(); // printing the status System.out.println(\"Status : \" + str); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 1533,
"s": 722,
"text": null
},
{
"code": null,
"e": 1587,
"s": 1533,
"text": "Status : MD5 Message Digest from SUN, <initialized>\n\n"
},
{
"code": null,
"e": 1631,
"s": 1587,
"text": "Example 2: To show NoSuchAlgorithmException"
},
{
"code": "// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of MessageDigest // and getting instance // By using getInstance() method MessageDigest sr = MessageDigest.getInstance(\"GFG\"); // getting the status of MessageDigest object String str = sr.toString(); // printing the status System.out.println(\"Status : \" + str); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 2442,
"s": 1631,
"text": null
},
{
"code": null,
"e": 2537,
"s": 2442,
"text": "Exception thrown :\n java.security.NoSuchAlgorithmException:\n GFG MessageDigest not available\n\n"
},
{
"code": null,
"e": 2720,
"s": 2537,
"text": "This getInstance() method of java.security.MessageDigest class provides an object of MessageDigest type that applys the assigned MessageDigest algorithm and assigned provider object."
},
{
"code": null,
"e": 2728,
"s": 2720,
"text": "Syntax:"
},
{
"code": null,
"e": 2840,
"s": 2728,
"text": "public static MessageDigest \n getInstance(String algorithm, String provider)\n throws NoSuchAlgorithmException"
},
{
"code": null,
"e": 2911,
"s": 2840,
"text": "Parameters: This method seeks the following arguments as a parameters:"
},
{
"code": null,
"e": 2991,
"s": 2911,
"text": "algorithm: which is the name of the algorithm to be specified in this instance."
},
{
"code": null,
"e": 3068,
"s": 2991,
"text": "provider: which is the name of the provider to be specified in this instance"
},
{
"code": null,
"e": 3136,
"s": 3068,
"text": "Return Value: This method provides an object of type MessageDigest."
},
{
"code": null,
"e": 3188,
"s": 3136,
"text": "Exception: This method throws following exceptions:"
},
{
"code": null,
"e": 3326,
"s": 3188,
"text": "NoSuchAlgorithmException:– if no MessageDigestSpi implementation for the particular algorithm is available from the particular Provider ."
},
{
"code": null,
"e": 3377,
"s": 3326,
"text": "IllegalArgumentException: if the provider is null."
},
{
"code": null,
"e": 3420,
"s": 3377,
"text": "NullPointerException: if algorithm is null"
},
{
"code": null,
"e": 3483,
"s": 3420,
"text": "Below are the examples to illustrate the getInstance() method:"
},
{
"code": null,
"e": 3494,
"s": 3483,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of MessageDigest // and getting instance // By using getInstance() method MessageDigest sr = MessageDigest.getInstance( \"SHA-384\", \"SUN\"); // getting the status of MessageDigest object String str = sr.toString(); // printing the status System.out.println(\"Status : \" + str); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } catch (NoSuchProviderException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 4448,
"s": 3494,
"text": null
},
{
"code": null,
"e": 4506,
"s": 4448,
"text": "Status : SHA-384 Message Digest from SUN, <initialized>\n\n"
},
{
"code": null,
"e": 4550,
"s": 4506,
"text": "Example 2: To show NoSuchAlgorithmException"
},
{
"code": "// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of MessageDigest // and getting instance // By using getInstance() method MessageDigest sr = MessageDigest.getInstance( \"GFG\", \"SUN\"); // getting the status of MessageDigest object String str = sr.toString(); // printing the status System.out.println(\"Status : \" + str); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } catch (NoSuchProviderException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 5500,
"s": 4550,
"text": null
},
{
"code": null,
"e": 5603,
"s": 5500,
"text": "Exception thrown :\n java.security.NoSuchAlgorithmException:\n no such algorithm: GFG for provider SUN\n\n"
},
{
"code": null,
"e": 5736,
"s": 5603,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/security/MessageDigest.html#getInstance-java.lang.String-java.lang.String-"
},
{
"code": null,
"e": 5749,
"s": 5736,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5764,
"s": 5749,
"text": "Java-Functions"
},
{
"code": null,
"e": 5783,
"s": 5764,
"text": "Java-MessageDigest"
},
{
"code": null,
"e": 5805,
"s": 5783,
"text": "Java-security package"
},
{
"code": null,
"e": 5810,
"s": 5805,
"text": "Java"
},
{
"code": null,
"e": 5815,
"s": 5810,
"text": "Java"
}
] |
How to play a custom ringtone/alarm sound in Android? | This example demonstrates about How to play a custom ringtone/alarm sound in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:onClick="playRingtone"
android:text="Play Ringtone" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void playRingtone(View view) {
try {
Uri path = Uri.parse("android.resource://" + getPackageName() + "/raw/ringtone.mp3");
RingtoneManager.setActualDefaultRingtoneUri(
getApplicationContext(), RingtoneManager.TYPE_RINGTONE, path
);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), path);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "This example demonstrates about How to play a custom ringtone/alarm sound in Android"
},
{
"code": null,
"e": 1276,
"s": 1147,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1341,
"s": 1276,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1881,
"s": 1341,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:gravity=\"center\"\n android:onClick=\"playRingtone\"\n android:text=\"Play Ringtone\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1938,
"s": 1881,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2835,
"s": 1938,
"text": "package app.com.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.media.Ringtone;\nimport android.media.RingtoneManager;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.View;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void playRingtone(View view) {\n try {\n Uri path = Uri.parse(\"android.resource://\" + getPackageName() + \"/raw/ringtone.mp3\");\n RingtoneManager.setActualDefaultRingtoneUri(\n getApplicationContext(), RingtoneManager.TYPE_RINGTONE, path\n );\n Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), path);\n r.play();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2890,
"s": 2835,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3560,
"s": 2890,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3907,
"s": 3560,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3948,
"s": 3907,
"text": "Click here to download the project code."
}
] |
ES6 - Array Method concat() | concat() method returns a new array comprised of this array joined with two or more arrays.
array.concat(value1, value2, ..., valueN);
valueN − Arrays and/or values to concatenate to the resulting array.
valueN − Arrays and/or values to concatenate to the resulting array.
Returns a new array.
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
console.log("alphaNumeric : " + alphaNumeric );
alphaNumeric : a,b,c,1,2,3
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": 2369,
"s": 2277,
"text": "concat() method returns a new array comprised of this array joined with two or more arrays."
},
{
"code": null,
"e": 2413,
"s": 2369,
"text": "array.concat(value1, value2, ..., valueN);\n"
},
{
"code": null,
"e": 2482,
"s": 2413,
"text": "valueN − Arrays and/or values to concatenate to the resulting array."
},
{
"code": null,
"e": 2551,
"s": 2482,
"text": "valueN − Arrays and/or values to concatenate to the resulting array."
},
{
"code": null,
"e": 2572,
"s": 2551,
"text": "Returns a new array."
},
{
"code": null,
"e": 2719,
"s": 2572,
"text": "var alpha = [\"a\", \"b\", \"c\"]; \nvar numeric = [1, 2, 3];\nvar alphaNumeric = alpha.concat(numeric); \nconsole.log(\"alphaNumeric : \" + alphaNumeric ); "
},
{
"code": null,
"e": 2747,
"s": 2719,
"text": "alphaNumeric : a,b,c,1,2,3\n"
},
{
"code": null,
"e": 2782,
"s": 2747,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2796,
"s": 2782,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 2829,
"s": 2796,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2847,
"s": 2829,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 2880,
"s": 2847,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2894,
"s": 2880,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 2929,
"s": 2894,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2946,
"s": 2929,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 2979,
"s": 2946,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2995,
"s": 2979,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 3030,
"s": 2995,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3038,
"s": 3030,
"text": " Shweta"
},
{
"code": null,
"e": 3045,
"s": 3038,
"text": " Print"
},
{
"code": null,
"e": 3056,
"s": 3045,
"text": " Add Notes"
}
] |
React Lifecycle | Each component in React has a lifecycle which you can monitor and manipulate during its
three main phases.
The three phases are: Mounting, Updating, and
Unmounting.
Mounting means putting elements into the DOM.
React has four built-in methods that gets called, in this order, when
mounting a component:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
The render() method is required and will
always be called, the others are optional and will be called if you define them.
The constructor() method is called before anything else,
when the component is initiated, and it is the natural
place to set up the initial state and other
initial values.
The constructor() method is called with the
props, as arguments, and you should always
start by calling the super(props) before
anything else, this will initiate the parent's constructor method and allows the
component to inherit methods from its parent (React.Component).
The constructor method is called, by
React, every time you make a component:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Run
Example »
The getDerivedStateFromProps() method is
called right before rendering the element(s) in the DOM.
This is the natural place to set the state object based on the initial
props.
It takes
state as an argument, and returns an object with changes to the
state.
The example below starts with the favorite color being
"red", but the
getDerivedStateFromProps() method updates the favorite color based on the
favcol attribute:
The getDerivedStateFromProps method is called
right before the render method:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
Run
Example »
The render() method is required, and is the
method that actually outputs the HTML to the DOM.
A simple component with a simple render()
method:
class Header extends React.Component {
render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Run
Example »
The componentDidMount() method is called after the
component is rendered.
This is where you run statements that requires that the component is already placed in the DOM.
At first my favorite color is red, but give me a second, and it is yellow
instead:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Run
Example »
The next phase in the lifecycle is when a component is updated.
A component is updated whenever there is a change in the component's
state or props.
React has five built-in methods that gets called, in this order, when a component
is updated:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
The render() method is required and will
always be called, the others are optional and will be called if you define them.
Also at updates the getDerivedStateFromProps method is
called. This is the first method that is called when a component gets updated.
This is still the natural place to set the state object based on the initial props.
The example below has a button that changes the favorite color to blue, but
since the getDerivedStateFromProps() method is called,
which updates the state with the color from the favcol attribute, the favorite color is
still
rendered as yellow:
If the component gets updated, the getDerivedStateFromProps() method is called:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));
Run
Example »
In the shouldComponentUpdate() method
you can return a Boolean value that specifies whether React should continue with the rendering or not.
The default value is true.
The example below shows what happens when the
shouldComponentUpdate() method returns false:
Stop the component from rendering at any update:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Run
Example »
Same example as above, but this time the shouldComponentUpdate() method returns
true instead:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return true;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Run
Example »
The render() method is of course called when a component gets updated,
it has to re-render the HTML to the DOM, with the new changes.
The example below has a button that changes the favorite color to blue:
Click the button to make a change in the component's state:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Run
Example »
In the getSnapshotBeforeUpdate() method
you have access to the props and
state before the update, meaning that
even after the update, you can check what the values were before the
update.
If the getSnapshotBeforeUpdate() method
is present, you should also include the
componentDidUpdate() method, otherwise you will get an error.
The example below might seem complicated, but all it does is this:
When the component is mounting it is rendered with the favorite
color "red".
When the component has been mounted, a timer changes the state, and
after one second, the favorite color becomes "yellow".
This action triggers the update phase, and since this component has a
getSnapshotBeforeUpdate() method, this method is executed, and writes a
message to the empty DIV1 element.
Then the componentDidUpdate() method is
executed and writes a message in the empty DIV2 element:
Use the
getSnapshotBeforeUpdate() method to find out
what the state object looked like before
the update:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState.favoritecolor;
}
componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Run
Example »
The componentDidUpdate method
is called after the component is updated in the DOM.
The example below might seem complicated, but all it does is this:
When the component is mounting it is rendered with the favorite
color "red".
When the component has been mounted, a timer changes the state, and
the color becomes "yellow".
This action triggers the update phase, and since this component has
a componentDidUpdate method, this method is
executed and writes a message in the empty DIV element:
The componentDidUpdate method is called
after the update has been rendered in the DOM:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
componentDidUpdate() {
document.getElementById("mydiv").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="mydiv"></div>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Run
Example »
The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it.
React has only one built-in method that gets called when a component is unmounted:
componentWillUnmount()
The componentWillUnmount method is
called when the component is about to be removed from the DOM.
Click the button to delete the header:
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={this.delHeader}>Delete Header</button>
</div>
);
}
}
class Child extends React.Component {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
}
}
ReactDOM.render(<Container />, document.getElementById('root'));
Run
Example »
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:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 108,
"s": 0,
"text": "Each component in React has a lifecycle which you can monitor and manipulate during its \nthree main phases."
},
{
"code": null,
"e": 166,
"s": 108,
"text": "The three phases are: Mounting, Updating, and\nUnmounting."
},
{
"code": null,
"e": 212,
"s": 166,
"text": "Mounting means putting elements into the DOM."
},
{
"code": null,
"e": 305,
"s": 212,
"text": "React has four built-in methods that gets called, in this order, when \nmounting a component:"
},
{
"code": null,
"e": 377,
"s": 305,
"text": "\nconstructor()\ngetDerivedStateFromProps()\nrender()\ncomponentDidMount()\n"
},
{
"code": null,
"e": 391,
"s": 377,
"text": "constructor()"
},
{
"code": null,
"e": 418,
"s": 391,
"text": "getDerivedStateFromProps()"
},
{
"code": null,
"e": 427,
"s": 418,
"text": "render()"
},
{
"code": null,
"e": 447,
"s": 427,
"text": "componentDidMount()"
},
{
"code": null,
"e": 570,
"s": 447,
"text": "The render() method is required and will \nalways be called, the others are optional and will be called if you define them."
},
{
"code": null,
"e": 745,
"s": 570,
"text": "The constructor() method is called before anything else, \nwhen the component is initiated, and it is the natural \nplace to set up the initial state and other \ninitial values."
},
{
"code": null,
"e": 1022,
"s": 745,
"text": "The constructor() method is called with the \nprops, as arguments, and you should always \nstart by calling the super(props) before \nanything else, this will initiate the parent's constructor method and allows the \ncomponent to inherit methods from its parent (React.Component)."
},
{
"code": null,
"e": 1102,
"s": 1022,
"text": "The constructor method is called, by \n React, every time you make a component:"
},
{
"code": null,
"e": 1401,
"s": 1102,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n render() {\n return (\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n );\n }\n}\n\nReactDOM.render(<Header />, document.getElementById('root'));\n \n \n \n \n"
},
{
"code": null,
"e": 1418,
"s": 1401,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1517,
"s": 1418,
"text": "The getDerivedStateFromProps() method is \ncalled right before rendering the element(s) in the DOM."
},
{
"code": null,
"e": 1597,
"s": 1517,
"text": "This is the natural place to set the state object based on the initial \nprops.\n"
},
{
"code": null,
"e": 1678,
"s": 1597,
"text": "It takes \nstate as an argument, and returns an object with changes to the\nstate."
},
{
"code": null,
"e": 1842,
"s": 1678,
"text": "The example below starts with the favorite color being \n\"red\", but the\n\ngetDerivedStateFromProps() method updates the favorite color based on the\nfavcol attribute:"
},
{
"code": null,
"e": 1923,
"s": 1842,
"text": "The getDerivedStateFromProps method is called \n right before the render method:"
},
{
"code": null,
"e": 2333,
"s": 1923,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n static getDerivedStateFromProps(props, state) {\n return {favoritecolor: props.favcol };\n }\n render() {\n return (\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n );\n }\n}\n\nReactDOM.render(<Header favcol=\"yellow\"/>, document.getElementById('root')); \n \n \n \n"
},
{
"code": null,
"e": 2350,
"s": 2333,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2445,
"s": 2350,
"text": "The render() method is required, and is the \nmethod that actually outputs the HTML to the DOM."
},
{
"code": null,
"e": 2498,
"s": 2445,
"text": "A simple component with a simple render() \n method:"
},
{
"code": null,
"e": 2699,
"s": 2498,
"text": "class Header extends React.Component {\n render() {\n return (\n <h1>This is the content of the Header component</h1>\n );\n }\n}\n\nReactDOM.render(<Header />, document.getElementById('root'));\n"
},
{
"code": null,
"e": 2716,
"s": 2699,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2791,
"s": 2716,
"text": "The componentDidMount() method is called after the \ncomponent is rendered."
},
{
"code": null,
"e": 2887,
"s": 2791,
"text": "This is where you run statements that requires that the component is already placed in the DOM."
},
{
"code": null,
"e": 2973,
"s": 2887,
"text": "At first my favorite color is red, but give me a second, and it is yellow \n instead:"
},
{
"code": null,
"e": 3385,
"s": 2973,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n componentDidMount() {\n setTimeout(() => {\n this.setState({favoritecolor: \"yellow\"})\n }, 1000)\n }\n render() {\n return (\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n );\n }\n}\n\nReactDOM.render(<Header />, document.getElementById('root'));\n \n \n \n \n \n"
},
{
"code": null,
"e": 3402,
"s": 3385,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 3466,
"s": 3402,
"text": "The next phase in the lifecycle is when a component is updated."
},
{
"code": null,
"e": 3551,
"s": 3466,
"text": "A component is updated whenever there is a change in the component's\nstate or props."
},
{
"code": null,
"e": 3646,
"s": 3551,
"text": "React has five built-in methods that gets called, in this order, when a component \nis updated:"
},
{
"code": null,
"e": 3755,
"s": 3646,
"text": "\ngetDerivedStateFromProps()\nshouldComponentUpdate()\nrender()\ngetSnapshotBeforeUpdate()\ncomponentDidUpdate()\n"
},
{
"code": null,
"e": 3782,
"s": 3755,
"text": "getDerivedStateFromProps()"
},
{
"code": null,
"e": 3806,
"s": 3782,
"text": "shouldComponentUpdate()"
},
{
"code": null,
"e": 3815,
"s": 3806,
"text": "render()"
},
{
"code": null,
"e": 3841,
"s": 3815,
"text": "getSnapshotBeforeUpdate()"
},
{
"code": null,
"e": 3862,
"s": 3841,
"text": "componentDidUpdate()"
},
{
"code": null,
"e": 3985,
"s": 3862,
"text": "The render() method is required and will \nalways be called, the others are optional and will be called if you define them."
},
{
"code": null,
"e": 4120,
"s": 3985,
"text": "Also at updates the getDerivedStateFromProps method is \ncalled. This is the first method that is called when a component gets updated."
},
{
"code": null,
"e": 4207,
"s": 4120,
"text": "This is still the natural place to set the state object based on the initial props.\n\n\n"
},
{
"code": null,
"e": 4456,
"s": 4207,
"text": "The example below has a button that changes the favorite color to blue, but \nsince the getDerivedStateFromProps() method is called, \nwhich updates the state with the color from the favcol attribute, the favorite color is \nstill \nrendered as yellow:"
},
{
"code": null,
"e": 4536,
"s": 4456,
"text": "If the component gets updated, the getDerivedStateFromProps() method is called:"
},
{
"code": null,
"e": 5119,
"s": 4536,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n static getDerivedStateFromProps(props, state) {\n return {favoritecolor: props.favcol };\n }\n changeColor = () => {\n this.setState({favoritecolor: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <button type=\"button\" onClick={this.changeColor}>Change color</button>\n </div>\n );\n }\n}\n\nReactDOM.render(<Header favcol=\"yellow\"/>, document.getElementById('root'));\n \n \n \n"
},
{
"code": null,
"e": 5136,
"s": 5119,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 5277,
"s": 5136,
"text": "In the shouldComponentUpdate() method\nyou can return a Boolean value that specifies whether React should continue with the rendering or not."
},
{
"code": null,
"e": 5304,
"s": 5277,
"text": "The default value is true."
},
{
"code": null,
"e": 5397,
"s": 5304,
"text": "The example below shows what happens when the \nshouldComponentUpdate() method returns false:"
},
{
"code": null,
"e": 5446,
"s": 5397,
"text": "Stop the component from rendering at any update:"
},
{
"code": null,
"e": 5967,
"s": 5446,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n shouldComponentUpdate() {\n return false;\n }\n changeColor = () => {\n this.setState({favoritecolor: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <button type=\"button\" onClick={this.changeColor}>Change color</button>\n </div>\n );\n }\n}\n\nReactDOM.render(<Header />, document.getElementById('root'));\n \n \n \n"
},
{
"code": null,
"e": 5984,
"s": 5967,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 6081,
"s": 5984,
"text": "Same example as above, but this time the shouldComponentUpdate() method returns \n true instead:"
},
{
"code": null,
"e": 6597,
"s": 6081,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n shouldComponentUpdate() {\n return true;\n }\n changeColor = () => {\n this.setState({favoritecolor: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <button type=\"button\" onClick={this.changeColor}>Change color</button>\n </div>\n );\n }\n}\n\nReactDOM.render(<Header />, document.getElementById('root'));\n \n"
},
{
"code": null,
"e": 6614,
"s": 6597,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 6749,
"s": 6614,
"text": "The render() method is of course called when a component gets updated, \nit has to re-render the HTML to the DOM, with the new changes."
},
{
"code": null,
"e": 6821,
"s": 6749,
"text": "The example below has a button that changes the favorite color to blue:"
},
{
"code": null,
"e": 6881,
"s": 6821,
"text": "Click the button to make a change in the component's state:"
},
{
"code": null,
"e": 7346,
"s": 6881,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n changeColor = () => {\n this.setState({favoritecolor: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <button type=\"button\" onClick={this.changeColor}>Change color</button>\n </div>\n );\n }\n}\n\nReactDOM.render(<Header />, document.getElementById('root'));\n"
},
{
"code": null,
"e": 7363,
"s": 7346,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 7554,
"s": 7363,
"text": "In the getSnapshotBeforeUpdate() method\nyou have access to the props and \nstate before the update, meaning that \neven after the update, you can check what the values were before the \nupdate."
},
{
"code": null,
"e": 7697,
"s": 7554,
"text": "If the getSnapshotBeforeUpdate() method\nis present, you should also include the \ncomponentDidUpdate() method, otherwise you will get an error."
},
{
"code": null,
"e": 7764,
"s": 7697,
"text": "The example below might seem complicated, but all it does is this:"
},
{
"code": null,
"e": 7842,
"s": 7764,
"text": "When the component is mounting it is rendered with the favorite \ncolor \"red\"."
},
{
"code": null,
"e": 7966,
"s": 7842,
"text": "When the component has been mounted, a timer changes the state, and \nafter one second, the favorite color becomes \"yellow\"."
},
{
"code": null,
"e": 8145,
"s": 7966,
"text": "This action triggers the update phase, and since this component has a \ngetSnapshotBeforeUpdate() method, this method is executed, and writes a \nmessage to the empty DIV1 element."
},
{
"code": null,
"e": 8243,
"s": 8145,
"text": "Then the componentDidUpdate() method is \nexecuted and writes a message in the empty DIV2 element:"
},
{
"code": null,
"e": 8360,
"s": 8245,
"text": "Use the \n getSnapshotBeforeUpdate() method to find out \n what the state object looked like before \n the update:"
},
{
"code": null,
"e": 9157,
"s": 8360,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n componentDidMount() {\n setTimeout(() => {\n this.setState({favoritecolor: \"yellow\"})\n }, 1000)\n }\n getSnapshotBeforeUpdate(prevProps, prevState) {\n document.getElementById(\"div1\").innerHTML =\n \"Before the update, the favorite was \" + prevState.favoritecolor;\n }\n componentDidUpdate() {\n document.getElementById(\"div2\").innerHTML =\n \"The updated favorite is \" + this.state.favoritecolor;\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <div id=\"div1\"></div>\n <div id=\"div2\"></div>\n </div>\n );\n }\n}\n\nReactDOM.render(<Header />, document.getElementById('root'));\n"
},
{
"code": null,
"e": 9174,
"s": 9157,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 9257,
"s": 9174,
"text": "The componentDidUpdate method\nis called after the component is updated in the DOM."
},
{
"code": null,
"e": 9324,
"s": 9257,
"text": "The example below might seem complicated, but all it does is this:"
},
{
"code": null,
"e": 9402,
"s": 9324,
"text": "When the component is mounting it is rendered with the favorite \ncolor \"red\"."
},
{
"code": null,
"e": 9499,
"s": 9402,
"text": "When the component has been mounted, a timer changes the state, and \nthe color becomes \"yellow\"."
},
{
"code": null,
"e": 9669,
"s": 9499,
"text": "This action triggers the update phase, and since this component has \na componentDidUpdate method, this method is \nexecuted and writes a message in the empty DIV element:"
},
{
"code": null,
"e": 9759,
"s": 9669,
"text": "The componentDidUpdate method is called \n after the update has been rendered in the DOM:"
},
{
"code": null,
"e": 10352,
"s": 9759,
"text": "class Header extends React.Component {\n constructor(props) {\n super(props);\n this.state = {favoritecolor: \"red\"};\n }\n componentDidMount() {\n setTimeout(() => {\n this.setState({favoritecolor: \"yellow\"})\n }, 1000)\n }\n componentDidUpdate() {\n document.getElementById(\"mydiv\").innerHTML =\n \"The updated favorite is \" + this.state.favoritecolor;\n }\n render() {\n return (\n <div>\n <h1>My Favorite Color is {this.state.favoritecolor}</h1>\n <div id=\"mydiv\"></div>\n </div>\n );\n }\n}\n\nReactDOM.render(<Header />, document.getElementById('root'));\n"
},
{
"code": null,
"e": 10369,
"s": 10352,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 10487,
"s": 10369,
"text": "The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it."
},
{
"code": null,
"e": 10570,
"s": 10487,
"text": "React has only one built-in method that gets called when a component is unmounted:"
},
{
"code": null,
"e": 10593,
"s": 10570,
"text": "componentWillUnmount()"
},
{
"code": null,
"e": 10692,
"s": 10593,
"text": "The componentWillUnmount method is \ncalled when the component is about to be removed from the DOM."
},
{
"code": null,
"e": 10731,
"s": 10692,
"text": "Click the button to delete the header:"
},
{
"code": null,
"e": 11417,
"s": 10731,
"text": "class Container extends React.Component {\n constructor(props) {\n super(props);\n this.state = {show: true};\n }\n delHeader = () => {\n this.setState({show: false});\n }\n render() {\n let myheader;\n if (this.state.show) {\n myheader = <Child />;\n };\n return (\n <div>\n {myheader}\n <button type=\"button\" onClick={this.delHeader}>Delete Header</button>\n </div>\n );\n }\n}\n\nclass Child extends React.Component {\n componentWillUnmount() {\n alert(\"The component named Header is about to be unmounted.\");\n }\n render() {\n return (\n <h1>Hello World!</h1>\n );\n }\n}\n\nReactDOM.render(<Container />, document.getElementById('root'));\n"
},
{
"code": null,
"e": 11434,
"s": 11417,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 11467,
"s": 11434,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 11509,
"s": 11467,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 11616,
"s": 11509,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 11635,
"s": 11616,
"text": "[email protected]"
}
] |
A complete Data Analysis workflow in Python and scikit-learn | by Angelica Lo Duca | Towards Data Science | In this short tutorial I illustrate a complete data analysis process which exploits the scikit-learn Python library. The process includes
preprocessing, which includes features selection, normalization and balancing
model selection with parameters tuning
model evaluation
The code of this tutorial can be downloaded from my Github Repository.
Firstly, I load the dataset through the Python pandas library. I exploit the heart.csv dataset, provided by the Kaggle repository.
import pandas as pddf = pd.read_csv('source/heart.csv')df.head()
I calculate the number of records and the number of columns in the dataset:
df.shape
which gives the following output:
(303, 14)
Now, I split the columns of the dataset in input (X) and output (Y). I use all the columns but output as input features.
features = []for column in df.columns: if column != 'output': features.append(column)X = df[features]Y = df['output']
In order to select the minimum set of input features, I calculate the Pearson correlation coefficient among features, through corr() function, provided by a pandas dataframe.
I note that all the features have a low correlation, thus I can keep all of them as input features.
Data Normalization scales all the features in the same interval. I exploit the MinMaxScaler() provided by the scikit-learn library. I dealt with Data Normalization in scikit-learn in my previous article, while I this article I described the general process of Data Normalization without scikit-learn.
X.describe()
Looking at the minimum and maximum value for each feature, I note that there are many features out the range [0,1], thus I need to scale them.
For each input feature I calculate the MinMaxScaler() and I store the result in the same X column. The MinMaxScaler() must be fitted firstly through the fit() function and then can be applied for a transformation through the transform() function. Note that I must reshape every feature in the format (-1,1) in order to be passed as input parameter of the scaler. For example, Reshape(-1,1) transforms the array [0,1,2,3,5] into [[0],[1],[2],[3],[5]].
from sklearn.preprocessing import MinMaxScalerfor column in X.columns: feature = np.array(X[column]).reshape(-1,1) scaler = MinMaxScaler() scaler.fit(feature) feature_scaled = scaler.transform(feature) X[column] = feature_scaled.reshape(1,-1)[0]
Now I split the dataset into two parts: training and testset. The test set size is 20% of the whole dataset. I exploit the scikit-learn function train_test_split(). I will use the training set to train the model and the testset to test the performance of the model.
import numpy as npfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, Y, test_size=0.20, random_state=42)
I check whether the dataset is balanced or not, i.e. if the output classes in the training set are equally represented. I can use the value_counts() function to calculate the number of records in each output class.
y_train.value_counts()
which gives the following output:
1 1330 109
The output classes are not balanced, thus I can balance it. I can exploit the imblearn library, to perform balancing. I try both oversampling the minority class and undersampling the majority class. More details related to the Imbalanced Learn library can be found here. Firstly, I perform over sampling through the RandomOverSampler(). I create the model and then I fit with the training set. The fit_resample() function returns the balanced training set.
from imblearn.over_sampling import RandomOverSamplerover_sampler = RandomOverSampler(random_state=42)X_bal_over, y_bal_over = over_sampler.fit_resample(X_train, y_train)
I calculate the number of records in each class through the value_counts() function and I note that now the dataset is balanced.
y_bal_over.value_counts()
which gives the following output:
1 1330 133
Secondly, I perform under sampling through the RandomUnderSampler() model.
from imblearn.under_sampling import RandomUnderSamplerunder_sampler = RandomUnderSampler(random_state=42)X_bal_under, y_bal_under = under_sampler.fit_resample(X_train, y_train)
Now, I’m ready to train the model. I choose a KNeighborsClassifier and firstly I train it with imbalanced data. I exploit the fit() function to train the model and then thepredict_proba() function to predict the values of the test set.
from sklearn.neighbors import KNeighborsClassifiermodel = KNeighborsClassifier(n_neighbors=3)model.fit(X_train, y_train)y_score = model.predict_proba(X_test)
I calculate the performance of the model. In particular, I calculate the roc_curve() and the precision_recall() and then I plot them. I exploit the scikitplot library to plot curves.
From the plot I note that there is a roc curve for each class. With respect to the precision recall curve, the class 1 works better than class 0, probably because it is represented by a greater number of samples.
import matplotlib.pyplot as pltfrom sklearn.metrics import roc_curvefrom scikitplot.metrics import plot_roc,aucfrom scikitplot.metrics import plot_precision_recallfpr0, tpr0, thresholds = roc_curve(y_test, y_score[:, 1])# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()
Now, I recalculate the same things with oversampling balancing. I note that the precision recall curve of class 0 increases, while that of class 1 decreases.
model = KNeighborsClassifier(n_neighbors=3)model.fit(X_bal_over, y_bal_over)y_score = model.predict_proba(X_test)fpr0, tpr0, thresholds = roc_curve(y_test, y_score[:, 1])# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()
Finally, I train the model through under sampled data and I note a general deterioration of the performance.
model = KNeighborsClassifier(n_neighbors=3)model.fit(X_bal_under, y_bal_under)y_score = model.predict_proba(X_test)fpr0, tpr0, thresholds = roc_curve(y_test, y_score[:, 1])# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()
In the last part of this tutorial, I try to improve the performance of the model by searching for best parameters for my model. I exploit the GridSearchCV mechanism provided by the scikit-learn library. I select a range of values for each parameter to be tested and I put them in the param_grid variable. I create a GridSearchCV() object, I fit with the training set and then I retrieve the best estimator, contained in the best_estimator_ variable.
from sklearn.model_selection import GridSearchCVmodel = KNeighborsClassifier()param_grid = { 'n_neighbors': np.arange(2,8), 'algorithm' : ['auto', 'ball_tree', 'kd_tree', 'brute'], 'metric' : ['euclidean','manhattan','chebyshev','minkowski']}grid = GridSearchCV(model, param_grid = param_grid)grid.fit(X_train, y_train)best_estimator = grid.best_estimator_
I exploit the best estimator as model for my predictions and I calculate the performance of the algorithm.
best_estimator.fit(X_train, y_train)y_score = best_estimator.predict_proba(X_test)fpr0, tpr0, thresholds = roc_curve(y_test, y_score[:, 1])# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()
I note that the roc curve has improved. I try now with the over sampled training set. I omit the code because it is the same as before. In this case I obtain the best performance.
In this tutorial I have illustrated the full workflow to build a good model for data analysis. The workflow includes:
data preprocessing, with features selection and balancing
model selection and parameters tuning with Grid Search with Cross Validation
model evaluation, through the ROC curve and the Precision Recall curve.
In this tutorial I have not dealt with Outliers Detection. If you want to learn something about this aspect, you can give a look to my previous article.
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github. | [
{
"code": null,
"e": 309,
"s": 171,
"text": "In this short tutorial I illustrate a complete data analysis process which exploits the scikit-learn Python library. The process includes"
},
{
"code": null,
"e": 387,
"s": 309,
"text": "preprocessing, which includes features selection, normalization and balancing"
},
{
"code": null,
"e": 426,
"s": 387,
"text": "model selection with parameters tuning"
},
{
"code": null,
"e": 443,
"s": 426,
"text": "model evaluation"
},
{
"code": null,
"e": 514,
"s": 443,
"text": "The code of this tutorial can be downloaded from my Github Repository."
},
{
"code": null,
"e": 645,
"s": 514,
"text": "Firstly, I load the dataset through the Python pandas library. I exploit the heart.csv dataset, provided by the Kaggle repository."
},
{
"code": null,
"e": 710,
"s": 645,
"text": "import pandas as pddf = pd.read_csv('source/heart.csv')df.head()"
},
{
"code": null,
"e": 786,
"s": 710,
"text": "I calculate the number of records and the number of columns in the dataset:"
},
{
"code": null,
"e": 795,
"s": 786,
"text": "df.shape"
},
{
"code": null,
"e": 829,
"s": 795,
"text": "which gives the following output:"
},
{
"code": null,
"e": 839,
"s": 829,
"text": "(303, 14)"
},
{
"code": null,
"e": 960,
"s": 839,
"text": "Now, I split the columns of the dataset in input (X) and output (Y). I use all the columns but output as input features."
},
{
"code": null,
"e": 1088,
"s": 960,
"text": "features = []for column in df.columns: if column != 'output': features.append(column)X = df[features]Y = df['output']"
},
{
"code": null,
"e": 1263,
"s": 1088,
"text": "In order to select the minimum set of input features, I calculate the Pearson correlation coefficient among features, through corr() function, provided by a pandas dataframe."
},
{
"code": null,
"e": 1363,
"s": 1263,
"text": "I note that all the features have a low correlation, thus I can keep all of them as input features."
},
{
"code": null,
"e": 1664,
"s": 1363,
"text": "Data Normalization scales all the features in the same interval. I exploit the MinMaxScaler() provided by the scikit-learn library. I dealt with Data Normalization in scikit-learn in my previous article, while I this article I described the general process of Data Normalization without scikit-learn."
},
{
"code": null,
"e": 1677,
"s": 1664,
"text": "X.describe()"
},
{
"code": null,
"e": 1820,
"s": 1677,
"text": "Looking at the minimum and maximum value for each feature, I note that there are many features out the range [0,1], thus I need to scale them."
},
{
"code": null,
"e": 2271,
"s": 1820,
"text": "For each input feature I calculate the MinMaxScaler() and I store the result in the same X column. The MinMaxScaler() must be fitted firstly through the fit() function and then can be applied for a transformation through the transform() function. Note that I must reshape every feature in the format (-1,1) in order to be passed as input parameter of the scaler. For example, Reshape(-1,1) transforms the array [0,1,2,3,5] into [[0],[1],[2],[3],[5]]."
},
{
"code": null,
"e": 2532,
"s": 2271,
"text": "from sklearn.preprocessing import MinMaxScalerfor column in X.columns: feature = np.array(X[column]).reshape(-1,1) scaler = MinMaxScaler() scaler.fit(feature) feature_scaled = scaler.transform(feature) X[column] = feature_scaled.reshape(1,-1)[0]"
},
{
"code": null,
"e": 2798,
"s": 2532,
"text": "Now I split the dataset into two parts: training and testset. The test set size is 20% of the whole dataset. I exploit the scikit-learn function train_test_split(). I will use the training set to train the model and the testset to test the performance of the model."
},
{
"code": null,
"e": 2960,
"s": 2798,
"text": "import numpy as npfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, Y, test_size=0.20, random_state=42)"
},
{
"code": null,
"e": 3175,
"s": 2960,
"text": "I check whether the dataset is balanced or not, i.e. if the output classes in the training set are equally represented. I can use the value_counts() function to calculate the number of records in each output class."
},
{
"code": null,
"e": 3198,
"s": 3175,
"text": "y_train.value_counts()"
},
{
"code": null,
"e": 3232,
"s": 3198,
"text": "which gives the following output:"
},
{
"code": null,
"e": 3249,
"s": 3232,
"text": "1 1330 109"
},
{
"code": null,
"e": 3706,
"s": 3249,
"text": "The output classes are not balanced, thus I can balance it. I can exploit the imblearn library, to perform balancing. I try both oversampling the minority class and undersampling the majority class. More details related to the Imbalanced Learn library can be found here. Firstly, I perform over sampling through the RandomOverSampler(). I create the model and then I fit with the training set. The fit_resample() function returns the balanced training set."
},
{
"code": null,
"e": 3876,
"s": 3706,
"text": "from imblearn.over_sampling import RandomOverSamplerover_sampler = RandomOverSampler(random_state=42)X_bal_over, y_bal_over = over_sampler.fit_resample(X_train, y_train)"
},
{
"code": null,
"e": 4005,
"s": 3876,
"text": "I calculate the number of records in each class through the value_counts() function and I note that now the dataset is balanced."
},
{
"code": null,
"e": 4031,
"s": 4005,
"text": "y_bal_over.value_counts()"
},
{
"code": null,
"e": 4065,
"s": 4031,
"text": "which gives the following output:"
},
{
"code": null,
"e": 4082,
"s": 4065,
"text": "1 1330 133"
},
{
"code": null,
"e": 4157,
"s": 4082,
"text": "Secondly, I perform under sampling through the RandomUnderSampler() model."
},
{
"code": null,
"e": 4334,
"s": 4157,
"text": "from imblearn.under_sampling import RandomUnderSamplerunder_sampler = RandomUnderSampler(random_state=42)X_bal_under, y_bal_under = under_sampler.fit_resample(X_train, y_train)"
},
{
"code": null,
"e": 4570,
"s": 4334,
"text": "Now, I’m ready to train the model. I choose a KNeighborsClassifier and firstly I train it with imbalanced data. I exploit the fit() function to train the model and then thepredict_proba() function to predict the values of the test set."
},
{
"code": null,
"e": 4728,
"s": 4570,
"text": "from sklearn.neighbors import KNeighborsClassifiermodel = KNeighborsClassifier(n_neighbors=3)model.fit(X_train, y_train)y_score = model.predict_proba(X_test)"
},
{
"code": null,
"e": 4911,
"s": 4728,
"text": "I calculate the performance of the model. In particular, I calculate the roc_curve() and the precision_recall() and then I plot them. I exploit the scikitplot library to plot curves."
},
{
"code": null,
"e": 5124,
"s": 4911,
"text": "From the plot I note that there is a roc curve for each class. With respect to the precision recall curve, the class 1 works better than class 0, probably because it is represented by a greater number of samples."
},
{
"code": null,
"e": 5447,
"s": 5124,
"text": "import matplotlib.pyplot as pltfrom sklearn.metrics import roc_curvefrom scikitplot.metrics import plot_roc,aucfrom scikitplot.metrics import plot_precision_recallfpr0, tpr0, thresholds = roc_curve(y_test, y_score[:, 1])# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()"
},
{
"code": null,
"e": 5605,
"s": 5447,
"text": "Now, I recalculate the same things with oversampling balancing. I note that the precision recall curve of class 0 increases, while that of class 1 decreases."
},
{
"code": null,
"e": 5878,
"s": 5605,
"text": "model = KNeighborsClassifier(n_neighbors=3)model.fit(X_bal_over, y_bal_over)y_score = model.predict_proba(X_test)fpr0, tpr0, thresholds = roc_curve(y_test, y_score[:, 1])# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()"
},
{
"code": null,
"e": 5987,
"s": 5878,
"text": "Finally, I train the model through under sampled data and I note a general deterioration of the performance."
},
{
"code": null,
"e": 6262,
"s": 5987,
"text": "model = KNeighborsClassifier(n_neighbors=3)model.fit(X_bal_under, y_bal_under)y_score = model.predict_proba(X_test)fpr0, tpr0, thresholds = roc_curve(y_test, y_score[:, 1])# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()"
},
{
"code": null,
"e": 6712,
"s": 6262,
"text": "In the last part of this tutorial, I try to improve the performance of the model by searching for best parameters for my model. I exploit the GridSearchCV mechanism provided by the scikit-learn library. I select a range of values for each parameter to be tested and I put them in the param_grid variable. I create a GridSearchCV() object, I fit with the training set and then I retrieve the best estimator, contained in the best_estimator_ variable."
},
{
"code": null,
"e": 7076,
"s": 6712,
"text": "from sklearn.model_selection import GridSearchCVmodel = KNeighborsClassifier()param_grid = { 'n_neighbors': np.arange(2,8), 'algorithm' : ['auto', 'ball_tree', 'kd_tree', 'brute'], 'metric' : ['euclidean','manhattan','chebyshev','minkowski']}grid = GridSearchCV(model, param_grid = param_grid)grid.fit(X_train, y_train)best_estimator = grid.best_estimator_"
},
{
"code": null,
"e": 7183,
"s": 7076,
"text": "I exploit the best estimator as model for my predictions and I calculate the performance of the algorithm."
},
{
"code": null,
"e": 7425,
"s": 7183,
"text": "best_estimator.fit(X_train, y_train)y_score = best_estimator.predict_proba(X_test)fpr0, tpr0, thresholds = roc_curve(y_test, y_score[:, 1])# Plot metrics plot_roc(y_test, y_score)plt.show() plot_precision_recall(y_test, y_score)plt.show()"
},
{
"code": null,
"e": 7605,
"s": 7425,
"text": "I note that the roc curve has improved. I try now with the over sampled training set. I omit the code because it is the same as before. In this case I obtain the best performance."
},
{
"code": null,
"e": 7723,
"s": 7605,
"text": "In this tutorial I have illustrated the full workflow to build a good model for data analysis. The workflow includes:"
},
{
"code": null,
"e": 7781,
"s": 7723,
"text": "data preprocessing, with features selection and balancing"
},
{
"code": null,
"e": 7858,
"s": 7781,
"text": "model selection and parameters tuning with Grid Search with Cross Validation"
},
{
"code": null,
"e": 7930,
"s": 7858,
"text": "model evaluation, through the ROC curve and the Precision Recall curve."
},
{
"code": null,
"e": 8083,
"s": 7930,
"text": "In this tutorial I have not dealt with Outliers Detection. If you want to learn something about this aspect, you can give a look to my previous article."
}
] |
How do you force MySQL LIKE to be case sensitive? | To force MySQL LIKE to be case sensitive with the help of LIKE BINARY, the following is the syntax −
select yourColumnName like binary 'anyStringValue' from yourTableName;
To understand the above concept, let us create a table. The following is the query to create a table −
mysql> create table LikeBinaryDemo
−> (
−> Name varchar(200)
−> );
Query OK, 0 rows affected (0.58 sec)
Now you can insert records with small letters to force the MySQL LIKE to be case sensitive −
mysql> insert into LikeBinaryDemo values('john');
Query OK, 1 row affected (0.12 sec)
Display the records in the table. The query is as follows −
mysql> select *from LikeBinaryDemo;
The following is the output −
+------+
| Name |
+------+
| john |
+------+
1 row in set (0.00 sec)
Now you can use LIKE BINARY to force the MySQL Like to be case sensitive.
LIKE BINARY. In this case, we will get value 0 when we compare ‘john’ with ‘JOHN’. The query is as follows −
mysql> select Name like binary 'JOHN' from LikeBinaryDemo;
The following is the output −
+-------------------------+
| Name like binary 'JOHN' |
+-------------------------+
| 0 |
+-------------------------+
1 row in set (0.00 sec)
Now let us see what will happen when we are not using BINARY. The query is as follows −
mysql> select Name like 'JOHN' from LikeBinaryDemo;
The following is the output −
+------------------+
| Name like 'JOHN' |
+------------------+
| 1 |
+------------------+
1 row in set (0.00 sec)
You can use LIKE BINARY to force MySQL to be case sensitive. | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "To force MySQL LIKE to be case sensitive with the help of LIKE BINARY, the following is the syntax −"
},
{
"code": null,
"e": 1234,
"s": 1163,
"text": "select yourColumnName like binary 'anyStringValue' from yourTableName;"
},
{
"code": null,
"e": 1337,
"s": 1234,
"text": "To understand the above concept, let us create a table. The following is the query to create a table −"
},
{
"code": null,
"e": 1450,
"s": 1337,
"text": "mysql> create table LikeBinaryDemo\n −> (\n −> Name varchar(200)\n −> );\nQuery OK, 0 rows affected (0.58 sec)"
},
{
"code": null,
"e": 1543,
"s": 1450,
"text": "Now you can insert records with small letters to force the MySQL LIKE to be case sensitive −"
},
{
"code": null,
"e": 1629,
"s": 1543,
"text": "mysql> insert into LikeBinaryDemo values('john');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1689,
"s": 1629,
"text": "Display the records in the table. The query is as follows −"
},
{
"code": null,
"e": 1725,
"s": 1689,
"text": "mysql> select *from LikeBinaryDemo;"
},
{
"code": null,
"e": 1755,
"s": 1725,
"text": "The following is the output −"
},
{
"code": null,
"e": 1824,
"s": 1755,
"text": "+------+\n| Name |\n+------+\n| john |\n+------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1898,
"s": 1824,
"text": "Now you can use LIKE BINARY to force the MySQL Like to be case sensitive."
},
{
"code": null,
"e": 2007,
"s": 1898,
"text": "LIKE BINARY. In this case, we will get value 0 when we compare ‘john’ with ‘JOHN’. The query is as follows −"
},
{
"code": null,
"e": 2066,
"s": 2007,
"text": "mysql> select Name like binary 'JOHN' from LikeBinaryDemo;"
},
{
"code": null,
"e": 2096,
"s": 2066,
"text": "The following is the output −"
},
{
"code": null,
"e": 2260,
"s": 2096,
"text": "+-------------------------+\n| Name like binary 'JOHN' |\n+-------------------------+\n| 0 |\n+-------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2348,
"s": 2260,
"text": "Now let us see what will happen when we are not using BINARY. The query is as follows −"
},
{
"code": null,
"e": 2400,
"s": 2348,
"text": "mysql> select Name like 'JOHN' from LikeBinaryDemo;"
},
{
"code": null,
"e": 2430,
"s": 2400,
"text": "The following is the output −"
},
{
"code": null,
"e": 2544,
"s": 2430,
"text": "+------------------+\n| Name like 'JOHN' |\n+------------------+\n| 1 |\n+------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2605,
"s": 2544,
"text": "You can use LIKE BINARY to force MySQL to be case sensitive."
}
] |
Count pairs having Bitwise XOR less than K from given array - GeeksforGeeks | 17 Nov, 2021
Given an array arr[]of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is less than K. Examples:
Input: arr = {1, 2, 3, 5} , K = 5 Output: 4 Explanation: Bitwise XOR of all possible pairs that satisfy the given conditions are: arr[0] ^ arr[1] = 1 ^ 2 = 3 arr[0] ^ arr[2] = 1 ^ 3 = 2 arr[0] ^ arr[3] = 1 ^ 5 = 4 arr[1] ^ arr[2] = 3 ^ 5 = 1 Therefore, the required output is 4.
Input: arr[] = {3, 5, 6, 8}, K = 7 Output: 3
Naive Approach: The simplest approach to solve this problem is to traverse the given array and generate all possible pairs of the given array and for each pair, check if bitwise XOR of the pair is less than K or not. If found to be true, then increment the count of pairs having bitwise XOR less than K. Finally, print the count of such pairs obtained.
Time Complexity:O(N2)Auxiliary Space:O(1)
Efficient Approach: The problem can be solved using Trie. The idea is to iterate over the given array and for each array element, count the number of elements present in the Trie whose bitwise XOR with the current element is less than K and insert the binary representation of the current element into the Trie. Finally, print the count of pairs having bitwise XOR less than K. Follow the steps below to solve the problem:
Create a Trie having a root node, say root to store the binary representation of each element of the given array.
Traverse the given array, and count the number of elements present in the Trie whose bitwise XOR with the current element is less than K and insert the binary representation of the current element.
Finally, print the count of pairs that satisfies the given condition.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Structure of Triestruct TrieNode{ // Stores binary representation // of numbers TrieNode *child[2]; // Stores count of elements // present in a node int cnt; // Function to initialize // a Trie Node TrieNode() { child[0] = child[1] = NULL; cnt = 0; }}; // Function to insert a number into Trievoid insertTrie(TrieNode *root, int N) { // Traverse binary representation of X for (int i = 31; i >= 0; i--) { // Stores ith bit of N bool x = (N) & (1 << i); // Check if an element already // present in Trie having ith bit x if(!root->child[x]) { // Create a new node of Trie. root->child[x] = new TrieNode(); } // Update count of elements // whose ith bit is x root->child[x]->cnt+= 1; // Update root root= root->child[x]; }} // Function to count elements// in Trie whose XOR with N// less than Kint cntSmaller(TrieNode * root, int N, int K){ // Stores count of elements // whose XOR with N less than K int cntPairs = 0; // Traverse binary representation // of N and K in Trie for (int i = 31; i >= 0 && root; i--) { // Stores ith bit of N bool x = N & (1 << i); // Stores ith bit of K bool y = K & (1 << i); // If the ith bit of K is 1 if (y) { // If an element already // present in Trie having // ith bit (x) if(root->child[x]) { cntPairs += root->child[x]->cnt; } root = root->child[1 - x]; } // If the ith bit of K is 0 else{ // Update root root = root->child[x]; } } return cntPairs;} // Function to count pairs that// satisfy the given conditionsint cntSmallerPairs(int arr[], int N, int K) { // Create root node of Trie TrieNode *root = new TrieNode(); // Stores count of pairs that // satisfy the given conditions int cntPairs = 0; // Traverse the given array for(int i = 0;i < N; i++){ // Update cntPairs cntPairs += cntSmaller(root, arr[i], K); // Insert arr[i] into Trie insertTrie(root, arr[i]); } return cntPairs;} // Driver Codeint main(){ int arr[] = {3, 5, 6, 8}; int K= 7; int N = sizeof(arr) / sizeof(arr[0]); cout<<cntSmallerPairs(arr, N, K);}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Structure of Triestatic class TrieNode{ // Stores binary representation // of numbers TrieNode child[] = new TrieNode[2]; // Stores count of elements // present in a node int cnt; // Function to initialize // a Trie Node TrieNode() { child[0] = child[1] = null; cnt = 0; }}; // Function to insert a number// into Triestatic void insertTrie(TrieNode root, int N){ // Traverse binary representation // of X for (int i = 31; i >= 0; i--) { // Stores ith bit of N int x = (N) & (1 << i); // Check if an element already // present in Trie having ith // bit x if(x <2 && root.child[x] == null) { // Create a new node of // Trie. root.child[x] = new TrieNode(); } // Update count of elements // whose ith bit is x if(x < 2) root.child[x].cnt += 1; // Update root if(x < 2) root = root.child[x]; }} // Function to count elements// in Trie whose XOR with N// less than Kstatic int cntSmaller(TrieNode root, int N, int K){ // Stores count of elements // whose XOR with N less // than K int cntPairs = 0; // Traverse binary // representation of N // and K in Trie for (int i = 31; i >= 0 && root != null; i--) { // Stores ith bit of N int x = (N & (1 << i)); // Stores ith bit of K int y = (K & (1 << i)); // If the ith bit of K // is 1 if (y == 1) { // If an element already // present in Trie having // ith bit (x) if(root.child[x] != null) { cntPairs += root.child[x].cnt; } root = root.child[1 - x]; } // If the ith bit of K is 0 else { // Update root if(x < 2) root = root.child[x]; } } return cntPairs;} // Function to count pairs that// satisfy the given conditionsstatic int cntSmallerPairs(int arr[], int N, int K){ // Create root node of Trie TrieNode root = new TrieNode(); // Stores count of pairs that // satisfy the given conditions int cntPairs = 0; // Traverse the given array for(int i = 0; i < N; i++) { // Update cntPairs cntPairs += cntSmaller(root, arr[i], K); // Insert arr[i] into Trie insertTrie(root, arr[i]); } return cntPairs;} // Driver Codepublic static void main(String[] args){ int arr[] = {3, 5, 6, 8}; int K= 7; int N = arr.length; System.out.print(cntSmallerPairs(arr, N, K));}} // This code is contributed by Rajput-Ji
# Python3 program to implement# the above approach # Structure of Trieclass TrieNode: # Function to initialize # a Trie Node def __init__(self): self.child = [None, None] self.cnt = 0 # Function to insert a number into Triedef insertTrie(root, N): # Traverse binary representation of X. for i in range(31, -1, -1): # Stores ith bit of N x = bool( (N) & (1 << i)); # Check if an element already # present in Trie having ith bit x. if(root.child[x] == None): # Create a new node of Trie. root.child[x] = TrieNode(); # Update count of elements # whose ith bit is x root.child[x].cnt += 1; # Update root. root= root.child[x]; # Function to count elements# in Trie whose XOR with N# less than Kdef cntSmaller(root, N, K): # Stores count of elements # whose XOR with N exceeding K cntPairs = 0; # Traverse binary representation # of N and K in Trie for i in range(31, -1, -1): if(root == None): break # Stores ith bit of N x = bool(N & (1 << i)) # Stores ith bit of K y = K & (1 << i); # If the ith bit of K is 1 if (y != 0): # If an element already # present in Trie having # ith bit (1 - x) if (root.child[x]): # Update cntPairs cntPairs += root.child[ x].cnt # Update root. root = root.child[1 - x]; # If the ith bit of K is 0 else: # Update root. root = root.child[x] return cntPairs; # Function to count pairs that# satisfy the given conditions.def cntSmallerPairs(arr, N, K): # Create root node of Trie root = TrieNode(); # Stores count of pairs that # satisfy the given conditions cntPairs = 0; # Traverse the given array. for i in range(N): # Update cntPairs cntPairs += cntSmaller(root, arr[i], K); # Insert arr[i] into Trie. insertTrie(root, arr[i]); return cntPairs; # Driver codeif __name__=='__main__': arr = [3, 5, 6, 8] K= 7; N = len(arr) print(cntSmallerPairs(arr, N, K)) # This code is contributed by rutvik_56
// C# program to implement// the above approachusing System; class GFG{ // Structure of Triepublic class TrieNode{ // Stores binary representation // of numbers public TrieNode []child = new TrieNode[2]; // Stores count of elements // present in a node public int cnt; // Function to initialize // a Trie Node public TrieNode() { child[0] = child[1] = null; cnt = 0; }}; // Function to insert a number// into Triestatic void insertTrie(TrieNode root, int N){ // Traverse binary representation // of X for(int i = 31; i >= 0; i--) { // Stores ith bit of N int x = (N) & (1 << i); // Check if an element already // present in Trie having ith // bit x if (x < 2 && root.child[x] == null) { // Create a new node of // Trie. root.child[x] = new TrieNode(); } // Update count of elements // whose ith bit is x if (x < 2) root.child[x].cnt += 1; // Update root if (x < 2) root = root.child[x]; }} // Function to count elements// in Trie whose XOR with N// less than Kstatic int cntSmaller(TrieNode root, int N, int K){ // Stores count of elements // whose XOR with N less // than K int cntPairs = 0; // Traverse binary // representation of N // and K in Trie for(int i = 31; i >= 0 && root != null; i--) { // Stores ith bit of N int x = (N & (1 << i)); // Stores ith bit of K int y = (K & (1 << i)); // If the ith bit of K // is 1 if (y == 1) { // If an element already // present in Trie having // ith bit (x) if (root.child[x] != null) { cntPairs += root.child[x].cnt; } root = root.child[1 - x]; } // If the ith bit of K is 0 else { // Update root if (x < 2) root = root.child[x]; } } return cntPairs;} // Function to count pairs that// satisfy the given conditionsstatic int cntSmallerPairs(int []arr, int N, int K){ // Create root node of Trie TrieNode root = new TrieNode(); // Stores count of pairs that // satisfy the given conditions int cntPairs = 0; // Traverse the given array for(int i = 0; i < N; i++) { // Update cntPairs cntPairs += cntSmaller(root, arr[i], K); // Insert arr[i] into Trie insertTrie(root, arr[i]); } return cntPairs;} // Driver Codepublic static void Main(String[] args){ int []arr = { 3, 5, 6, 8 }; int K= 7; int N = arr.Length; Console.Write(cntSmallerPairs(arr, N, K));}} // This code is contributed by Princi Singh
3
Time Complexity:O(N * 32)Auxiliary Space:O(N * 32)
Rajput-Ji
princi singh
rutvik_56
surindertarika1234
Bitwise-XOR
Trie
Advanced Data Structure
Arrays
Bit Magic
Mathematical
Arrays
Mathematical
Bit Magic
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Agents in Artificial Intelligence
Decision Tree Introduction with example
Disjoint Set Data Structures
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews | [
{
"code": null,
"e": 25574,
"s": 25546,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 25750,
"s": 25574,
"text": "Given an array arr[]of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is less than K. Examples:"
},
{
"code": null,
"e": 26030,
"s": 25750,
"text": "Input: arr = {1, 2, 3, 5} , K = 5 Output: 4 Explanation: Bitwise XOR of all possible pairs that satisfy the given conditions are: arr[0] ^ arr[1] = 1 ^ 2 = 3 arr[0] ^ arr[2] = 1 ^ 3 = 2 arr[0] ^ arr[3] = 1 ^ 5 = 4 arr[1] ^ arr[2] = 3 ^ 5 = 1 Therefore, the required output is 4. "
},
{
"code": null,
"e": 26077,
"s": 26030,
"text": "Input: arr[] = {3, 5, 6, 8}, K = 7 Output: 3 "
},
{
"code": null,
"e": 26430,
"s": 26077,
"text": "Naive Approach: The simplest approach to solve this problem is to traverse the given array and generate all possible pairs of the given array and for each pair, check if bitwise XOR of the pair is less than K or not. If found to be true, then increment the count of pairs having bitwise XOR less than K. Finally, print the count of such pairs obtained."
},
{
"code": null,
"e": 26472,
"s": 26430,
"text": "Time Complexity:O(N2)Auxiliary Space:O(1)"
},
{
"code": null,
"e": 26895,
"s": 26472,
"text": "Efficient Approach: The problem can be solved using Trie. The idea is to iterate over the given array and for each array element, count the number of elements present in the Trie whose bitwise XOR with the current element is less than K and insert the binary representation of the current element into the Trie. Finally, print the count of pairs having bitwise XOR less than K. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27009,
"s": 26895,
"text": "Create a Trie having a root node, say root to store the binary representation of each element of the given array."
},
{
"code": null,
"e": 27207,
"s": 27009,
"text": "Traverse the given array, and count the number of elements present in the Trie whose bitwise XOR with the current element is less than K and insert the binary representation of the current element."
},
{
"code": null,
"e": 27277,
"s": 27207,
"text": "Finally, print the count of pairs that satisfies the given condition."
},
{
"code": null,
"e": 27328,
"s": 27277,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27332,
"s": 27328,
"text": "C++"
},
{
"code": null,
"e": 27337,
"s": 27332,
"text": "Java"
},
{
"code": null,
"e": 27345,
"s": 27337,
"text": "Python3"
},
{
"code": null,
"e": 27348,
"s": 27345,
"text": "C#"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Structure of Triestruct TrieNode{ // Stores binary representation // of numbers TrieNode *child[2]; // Stores count of elements // present in a node int cnt; // Function to initialize // a Trie Node TrieNode() { child[0] = child[1] = NULL; cnt = 0; }}; // Function to insert a number into Trievoid insertTrie(TrieNode *root, int N) { // Traverse binary representation of X for (int i = 31; i >= 0; i--) { // Stores ith bit of N bool x = (N) & (1 << i); // Check if an element already // present in Trie having ith bit x if(!root->child[x]) { // Create a new node of Trie. root->child[x] = new TrieNode(); } // Update count of elements // whose ith bit is x root->child[x]->cnt+= 1; // Update root root= root->child[x]; }} // Function to count elements// in Trie whose XOR with N// less than Kint cntSmaller(TrieNode * root, int N, int K){ // Stores count of elements // whose XOR with N less than K int cntPairs = 0; // Traverse binary representation // of N and K in Trie for (int i = 31; i >= 0 && root; i--) { // Stores ith bit of N bool x = N & (1 << i); // Stores ith bit of K bool y = K & (1 << i); // If the ith bit of K is 1 if (y) { // If an element already // present in Trie having // ith bit (x) if(root->child[x]) { cntPairs += root->child[x]->cnt; } root = root->child[1 - x]; } // If the ith bit of K is 0 else{ // Update root root = root->child[x]; } } return cntPairs;} // Function to count pairs that// satisfy the given conditionsint cntSmallerPairs(int arr[], int N, int K) { // Create root node of Trie TrieNode *root = new TrieNode(); // Stores count of pairs that // satisfy the given conditions int cntPairs = 0; // Traverse the given array for(int i = 0;i < N; i++){ // Update cntPairs cntPairs += cntSmaller(root, arr[i], K); // Insert arr[i] into Trie insertTrie(root, arr[i]); } return cntPairs;} // Driver Codeint main(){ int arr[] = {3, 5, 6, 8}; int K= 7; int N = sizeof(arr) / sizeof(arr[0]); cout<<cntSmallerPairs(arr, N, K);}",
"e": 30177,
"s": 27348,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Structure of Triestatic class TrieNode{ // Stores binary representation // of numbers TrieNode child[] = new TrieNode[2]; // Stores count of elements // present in a node int cnt; // Function to initialize // a Trie Node TrieNode() { child[0] = child[1] = null; cnt = 0; }}; // Function to insert a number// into Triestatic void insertTrie(TrieNode root, int N){ // Traverse binary representation // of X for (int i = 31; i >= 0; i--) { // Stores ith bit of N int x = (N) & (1 << i); // Check if an element already // present in Trie having ith // bit x if(x <2 && root.child[x] == null) { // Create a new node of // Trie. root.child[x] = new TrieNode(); } // Update count of elements // whose ith bit is x if(x < 2) root.child[x].cnt += 1; // Update root if(x < 2) root = root.child[x]; }} // Function to count elements// in Trie whose XOR with N// less than Kstatic int cntSmaller(TrieNode root, int N, int K){ // Stores count of elements // whose XOR with N less // than K int cntPairs = 0; // Traverse binary // representation of N // and K in Trie for (int i = 31; i >= 0 && root != null; i--) { // Stores ith bit of N int x = (N & (1 << i)); // Stores ith bit of K int y = (K & (1 << i)); // If the ith bit of K // is 1 if (y == 1) { // If an element already // present in Trie having // ith bit (x) if(root.child[x] != null) { cntPairs += root.child[x].cnt; } root = root.child[1 - x]; } // If the ith bit of K is 0 else { // Update root if(x < 2) root = root.child[x]; } } return cntPairs;} // Function to count pairs that// satisfy the given conditionsstatic int cntSmallerPairs(int arr[], int N, int K){ // Create root node of Trie TrieNode root = new TrieNode(); // Stores count of pairs that // satisfy the given conditions int cntPairs = 0; // Traverse the given array for(int i = 0; i < N; i++) { // Update cntPairs cntPairs += cntSmaller(root, arr[i], K); // Insert arr[i] into Trie insertTrie(root, arr[i]); } return cntPairs;} // Driver Codepublic static void main(String[] args){ int arr[] = {3, 5, 6, 8}; int K= 7; int N = arr.length; System.out.print(cntSmallerPairs(arr, N, K));}} // This code is contributed by Rajput-Ji",
"e": 32822,
"s": 30177,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Structure of Trieclass TrieNode: # Function to initialize # a Trie Node def __init__(self): self.child = [None, None] self.cnt = 0 # Function to insert a number into Triedef insertTrie(root, N): # Traverse binary representation of X. for i in range(31, -1, -1): # Stores ith bit of N x = bool( (N) & (1 << i)); # Check if an element already # present in Trie having ith bit x. if(root.child[x] == None): # Create a new node of Trie. root.child[x] = TrieNode(); # Update count of elements # whose ith bit is x root.child[x].cnt += 1; # Update root. root= root.child[x]; # Function to count elements# in Trie whose XOR with N# less than Kdef cntSmaller(root, N, K): # Stores count of elements # whose XOR with N exceeding K cntPairs = 0; # Traverse binary representation # of N and K in Trie for i in range(31, -1, -1): if(root == None): break # Stores ith bit of N x = bool(N & (1 << i)) # Stores ith bit of K y = K & (1 << i); # If the ith bit of K is 1 if (y != 0): # If an element already # present in Trie having # ith bit (1 - x) if (root.child[x]): # Update cntPairs cntPairs += root.child[ x].cnt # Update root. root = root.child[1 - x]; # If the ith bit of K is 0 else: # Update root. root = root.child[x] return cntPairs; # Function to count pairs that# satisfy the given conditions.def cntSmallerPairs(arr, N, K): # Create root node of Trie root = TrieNode(); # Stores count of pairs that # satisfy the given conditions cntPairs = 0; # Traverse the given array. for i in range(N): # Update cntPairs cntPairs += cntSmaller(root, arr[i], K); # Insert arr[i] into Trie. insertTrie(root, arr[i]); return cntPairs; # Driver codeif __name__=='__main__': arr = [3, 5, 6, 8] K= 7; N = len(arr) print(cntSmallerPairs(arr, N, K)) # This code is contributed by rutvik_56",
"e": 35314,
"s": 32822,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Structure of Triepublic class TrieNode{ // Stores binary representation // of numbers public TrieNode []child = new TrieNode[2]; // Stores count of elements // present in a node public int cnt; // Function to initialize // a Trie Node public TrieNode() { child[0] = child[1] = null; cnt = 0; }}; // Function to insert a number// into Triestatic void insertTrie(TrieNode root, int N){ // Traverse binary representation // of X for(int i = 31; i >= 0; i--) { // Stores ith bit of N int x = (N) & (1 << i); // Check if an element already // present in Trie having ith // bit x if (x < 2 && root.child[x] == null) { // Create a new node of // Trie. root.child[x] = new TrieNode(); } // Update count of elements // whose ith bit is x if (x < 2) root.child[x].cnt += 1; // Update root if (x < 2) root = root.child[x]; }} // Function to count elements// in Trie whose XOR with N// less than Kstatic int cntSmaller(TrieNode root, int N, int K){ // Stores count of elements // whose XOR with N less // than K int cntPairs = 0; // Traverse binary // representation of N // and K in Trie for(int i = 31; i >= 0 && root != null; i--) { // Stores ith bit of N int x = (N & (1 << i)); // Stores ith bit of K int y = (K & (1 << i)); // If the ith bit of K // is 1 if (y == 1) { // If an element already // present in Trie having // ith bit (x) if (root.child[x] != null) { cntPairs += root.child[x].cnt; } root = root.child[1 - x]; } // If the ith bit of K is 0 else { // Update root if (x < 2) root = root.child[x]; } } return cntPairs;} // Function to count pairs that// satisfy the given conditionsstatic int cntSmallerPairs(int []arr, int N, int K){ // Create root node of Trie TrieNode root = new TrieNode(); // Stores count of pairs that // satisfy the given conditions int cntPairs = 0; // Traverse the given array for(int i = 0; i < N; i++) { // Update cntPairs cntPairs += cntSmaller(root, arr[i], K); // Insert arr[i] into Trie insertTrie(root, arr[i]); } return cntPairs;} // Driver Codepublic static void Main(String[] args){ int []arr = { 3, 5, 6, 8 }; int K= 7; int N = arr.Length; Console.Write(cntSmallerPairs(arr, N, K));}} // This code is contributed by Princi Singh",
"e": 38011,
"s": 35314,
"text": null
},
{
"code": null,
"e": 38013,
"s": 38011,
"text": "3"
},
{
"code": null,
"e": 38066,
"s": 38015,
"text": "Time Complexity:O(N * 32)Auxiliary Space:O(N * 32)"
},
{
"code": null,
"e": 38076,
"s": 38066,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38089,
"s": 38076,
"text": "princi singh"
},
{
"code": null,
"e": 38099,
"s": 38089,
"text": "rutvik_56"
},
{
"code": null,
"e": 38118,
"s": 38099,
"text": "surindertarika1234"
},
{
"code": null,
"e": 38130,
"s": 38118,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 38135,
"s": 38130,
"text": "Trie"
},
{
"code": null,
"e": 38159,
"s": 38135,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 38166,
"s": 38159,
"text": "Arrays"
},
{
"code": null,
"e": 38176,
"s": 38166,
"text": "Bit Magic"
},
{
"code": null,
"e": 38189,
"s": 38176,
"text": "Mathematical"
},
{
"code": null,
"e": 38196,
"s": 38189,
"text": "Arrays"
},
{
"code": null,
"e": 38209,
"s": 38196,
"text": "Mathematical"
},
{
"code": null,
"e": 38219,
"s": 38209,
"text": "Bit Magic"
},
{
"code": null,
"e": 38224,
"s": 38219,
"text": "Trie"
},
{
"code": null,
"e": 38322,
"s": 38224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38331,
"s": 38322,
"text": "Comments"
},
{
"code": null,
"e": 38344,
"s": 38331,
"text": "Old Comments"
},
{
"code": null,
"e": 38378,
"s": 38344,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 38418,
"s": 38378,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 38447,
"s": 38418,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 38475,
"s": 38447,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 38507,
"s": 38475,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 38522,
"s": 38507,
"text": "Arrays in Java"
},
{
"code": null,
"e": 38538,
"s": 38522,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 38565,
"s": 38538,
"text": "Program for array rotation"
},
{
"code": null,
"e": 38613,
"s": 38565,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
GPU-Accelerated Machine Learning on MacOS | by Riccardo Di Sipio | Towards Data Science | Massively parallel programming is very useful to speed up calculations where the same operation is applied multiple times on similar inputs. If your code involves a number of if or case statements, you may want to run on a CPU using e.g. OpenMPI. If your code involves the generation of random numbers, parallel programming may not be the best solution (however, see here). Otherwise, you are probably in the right place, so keep reading!
Training a neural network involves a very large number of matrix multiplications. This is the quintessential massively parallel operation, which constitutes one of the main reasons why GPUs are vital to Machine Learning. One rule of thumb to remember is that 1K CPUs = 16K cores = 3GPUs, although the kind of operations a CPU can perform vastly outperforms those of a single GPU core. For GPUs, strength is in numbers!
iMac and MacBook Pro computers are equipped with an AMD Radeon GPU card. Unfortunately, this kind of hardware can not be used directly to speed-up calculations that are typical in Machine Learning applications, such as training a CNN. While there isn’t a solution for all possible applications, there is still a workaround for simple architectures based on a parallel programming language called OpenCL.
The two most popular ML frameworks Keras and PyTorch support GPU acceleration based on the general-purpose GPU library NVIDIA CUDA. CUDA only works with NVIDIA GPU cards.
NVIDIA external GPU cards (eGPU) can be used by a MacOS systems with a Thunderbolt 3 port and MacOS High Sierra 10.13.4 or later. Follow this guide to install the eGPU.
To install CUDA on MacOs follow the official documentation. Drivers can be found here.
The project PyOpenCL is probably the easiest way to get started with GP-GPU on a Mac. See also its sister project PyCUDA.
$ pip install pyopencl
The centrepiece of OpenCL is a kernel, which is a function (written in a C-like language) that can be applied to chunks of input data.
For an introduction to parallel programming follow this online course based on CUDA, or buy this book by Tim Mattson et al.
OpenCL is more flexible than CUDA to allow programs to be executed on different architectures. This comes with a price: it is necessary to write some “boilerplate” code to define a context (i.e. what kind of hardware is available), a queue (i.e. a sequence of commands) and a set of memory flags (e.g. READ_ONLY, WRITE_ONLY, etc.). The typical workflow is as follows:
Input data is copied to the GPU memoryGPU buffer memory is reserved to host the result of the calculationsA kernels are executedThe result is copied from the GPU memory to the host memory
Input data is copied to the GPU memory
GPU buffer memory is reserved to host the result of the calculations
A kernels are executed
The result is copied from the GPU memory to the host memory
NB: OpenCL kernels can be executed on both CPUs and GPUs, but if the code is highly optimized for a certain GPU architecture (e.g. with large memory) it may not be completely portable.
Though GPUs are generally faster, the time taken to transfer huge amounts of data from CPU to GPU can lead to higher overhead time depending on the architecture of the processors.
Here’s an example of a fully-functional OpenCL program that calculates the sum of two matrices:
#!/usr/bin/env python# -*- coding: utf-8 -*-from __future__ import absolute_import, print_functionimport numpy as npimport pyopencl as cla_np = np.random.rand(50000).astype(np.float32)b_np = np.random.rand(50000).astype(np.float32)ctx = cl.create_some_context()queue = cl.CommandQueue(ctx)mf = cl.mem_flagsa_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a_np)b_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=b_np)kernel = """__kernel void sum( __global const float *a_g, __global const float *b_g, __global float *res_g){ int gid = get_global_id(0); res_g[gid] = a_g[gid] + b_g[gid];}"""prg = cl.Program(ctx, kernel).build()res_g = cl.Buffer(ctx, mf.WRITE_ONLY, a_np.nbytes)prg.sum(queue, a_np.shape, None, a_g, b_g, res_g)res_np = np.empty_like(a_np)cl.enqueue_copy(queue, res_np, res_g)# Check on CPU with Numpy:print(res_np - (a_np + b_np))print(np.linalg.norm(res_np - (a_np + b_np)))assert np.allclose(res_np, a_np + b_np)
Keras is one of the most popular deep learning frameworks. It’s very easy to define the architecture of a network using Keras’ functional APIs, run the training and execute inference. However, Keras does not perform the actual calculations by itself, but rather deploys other software libraries to define, optimize, and evaluate mathematical expressions involving multi-dimensional arrays. The most common ones are Theano and TensorFlow. In turn, these libraries execute parallel calculations on GPUs using CUDA. As previously states, this comes with the very strong hardware limitation that it works only on NVIDIA cards.
This problem can be partially evaded by using instead the PlaidML library:
$ pip install plaidml-keras
Following installation, execute the setup script (select default unless you know what you’re doing):
$ plaidml-setup
You should see something like this:
PlaidML Setup (0.6.4)Thanks for using PlaidML!Some Notes: * Bugs and other issues: https://github.com/plaidml/plaidml * Questions: https://stackoverflow.com/questions/tagged/plaidml * Say hello: https://groups.google.com/forum/#!forum/plaidml-dev * PlaidML is licensed under the Apache License 2.0Default Config Devices: metal_amd_radeon_r9_m380.0 : AMD Radeon R9 M380 (Metal)Experimental Config Devices: llvm_cpu.0 : CPU (LLVM) opencl_amd_radeon_r9_m380_compute_engine.0 : AMD AMD Radeon R9 M380 Compute Engine (OpenCL) opencl_cpu.0 : Intel CPU (OpenCL) metal_amd_radeon_r9_m380.0 : AMD Radeon R9 M380 (Metal)Using experimental devices can cause poor performance, crashes, and other nastiness.Enable experimental device support? (y,n)[n]:Selected device: metal_amd_radeon_r9_m380.0Almost done. Multiplying some matrices...Tile code: function (B[X,Z], C[Z,Y]) -> (A) { A[x,y : X,Y] = +(B[x,z] * C[z,y]); }Whew. That worked.Save settings to /Users/user/.plaidml? (y,n)[y]:Success!
This library supports many but not all Keras layers. If your architecture involves only Dense, LSTM, CNN and Dropout layers, you’re certainly good, otherwise check the documentation.
In principle, all you have to do is to pre-pend the following lines of code to your program to activate the PlaidML backend:
import osos.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
During the execution, you should see some printouts like these:
Using plaindml.keras.backend backendINFO:plaidml:Opening device "metal_amd_radeon_r9_m380.0"
This is an example, adapted from from Keras’ official documentation, that should work out-of-the-box:
#!/usr/bin/env pythonimport osos.environ["KERAS_BACKEND"] = "plaidml.keras.backend"import kerasfrom keras.datasets import mnistfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flattenfrom keras.layers import Conv2D, MaxPooling2Dfrom keras import backend as Kbatch_size = 128num_classes = 10epochs = 12# input image dimensionsimg_rows, img_cols = 28, 28# the data, split between train and test sets(x_train, y_train), (x_test, y_test) = mnist.load_data()if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols)else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1)x_train = x_train.astype('float32')x_test = x_test.astype('float32')x_train /= 255x_test /= 255print('x_train shape:', x_train.shape)print(x_train.shape[0], 'train samples')print(x_test.shape[0], 'test samples')# convert class vectors to binary class matricesy_train = keras.utils.to_categorical(y_train, num_classes)y_test = keras.utils.to_categorical(y_test, num_classes)model = Sequential()model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(128, activation='relu'))model.add(Dropout(0.5))model.add(Dense(num_classes, activation='softmax'))model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))score = model.evaluate(x_test, y_test, verbose=0)print('Test loss:', score[0])print('Test accuracy:', score[1])
On a 2015 iMac (3.2 GHz Intel Core i5, 16 GB DDR RAM, AMD Radeon R9 M380 2 GB GPU) it took 1m50s to train with PlaidML/OpenCL GPU backend, and 5m06s using the TensorFlow-2.0/CPU backend.
Note that the instruction from keras import backend as K would return an error if there is no available backend. For example, if you did not install TensorFlow (default), you would see:
Using TensorFlow backend.Traceback (most recent call last): File "./test_keras.py", line 8, in <module> import keras File "/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/__init__.py", line 3, in <module> from . import utils File "/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/utils/__init__.py", line 6, in <module> from . import conv_utils File "/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/utils/conv_utils.py", line 9, in <module> from .. import backend as K File "/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/backend/__init__.py", line 89, in <module> from .tensorflow_backend import * File "/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py", line 5, in <module> import tensorflow as tfModuleNotFoundError: No module named 'tensorflow'
On a final note, TensorFlow >=2.0 includes Keras API. If your program is written so that layers are defined from TF, and not Keras, you cannot just change the Keras backend to run on the GPU with OpenCL support, because TF2 does not support OpenCL. To be more specific:
This will not use the GPU (assuming you have installed TensorFlow >=2.0)
from tensorflow import kerasfrom tensorflow.keras import layers
This will work just fine (assuming you have installed Keras)
import kerasfrom keras import layers
It turns out that PlaidML can do much more than just being a Keras backend. In fact, it comes with a programming language called Tile to help users writing optimized kernels without requiring an in-depth knowledge of C and most of the quirks of OpenCL. Tile instructions look more like mathematical functions. For example, a matrix multiplication
looks like this in Tile
function (A[M, L], B[L, N]) -> (C) { C[i, j: M, N] = +(A[i, k] * B[k, j]);}
where the “+” operator stands for the “sum” in the mathematical expression.
Many more examples can be found in the documentation, including some of the most common operations such as matrix multiplication, min/max, max pool, convolution, cumulative sum. When the kernel is synthesized, Tile flattens the tensors and transforms indices into pointer offsets. The calculation is split into tiles that fit into memory, with a size that is optimized based on the available hardware. The tiles are then laid out in the GPU memory to optimize SIMDs instructions such as multiplications and accumulations. Finally, the kernels are written out as if they were created by a human user, and passed on to OpenCL for the actual execution.
PlaidML is now part of Intel’s AI group Vertex.ai. It may finally make AMD cards (possibly more vendors to come) a viable option in ML. In fact, Intel is also set to enter the GPU market in 2020 with hardware designed for ML in data centres which could further reduce the price of computation through competition. Intel CEO Bob Swan said that “ in 2020, we’ll continue to expand our 10-nanometer portfolio with exciting new products including an AI Inference Accelerator, 5G base station SOC, Xeon CPUs for server storage, and network and a discrete GPU. This quarter, we’ve achieved power-on exit for our first discrete GPU, DG1, an important milestone.”. So stay tuned! | [
{
"code": null,
"e": 610,
"s": 171,
"text": "Massively parallel programming is very useful to speed up calculations where the same operation is applied multiple times on similar inputs. If your code involves a number of if or case statements, you may want to run on a CPU using e.g. OpenMPI. If your code involves the generation of random numbers, parallel programming may not be the best solution (however, see here). Otherwise, you are probably in the right place, so keep reading!"
},
{
"code": null,
"e": 1029,
"s": 610,
"text": "Training a neural network involves a very large number of matrix multiplications. This is the quintessential massively parallel operation, which constitutes one of the main reasons why GPUs are vital to Machine Learning. One rule of thumb to remember is that 1K CPUs = 16K cores = 3GPUs, although the kind of operations a CPU can perform vastly outperforms those of a single GPU core. For GPUs, strength is in numbers!"
},
{
"code": null,
"e": 1433,
"s": 1029,
"text": "iMac and MacBook Pro computers are equipped with an AMD Radeon GPU card. Unfortunately, this kind of hardware can not be used directly to speed-up calculations that are typical in Machine Learning applications, such as training a CNN. While there isn’t a solution for all possible applications, there is still a workaround for simple architectures based on a parallel programming language called OpenCL."
},
{
"code": null,
"e": 1604,
"s": 1433,
"text": "The two most popular ML frameworks Keras and PyTorch support GPU acceleration based on the general-purpose GPU library NVIDIA CUDA. CUDA only works with NVIDIA GPU cards."
},
{
"code": null,
"e": 1773,
"s": 1604,
"text": "NVIDIA external GPU cards (eGPU) can be used by a MacOS systems with a Thunderbolt 3 port and MacOS High Sierra 10.13.4 or later. Follow this guide to install the eGPU."
},
{
"code": null,
"e": 1860,
"s": 1773,
"text": "To install CUDA on MacOs follow the official documentation. Drivers can be found here."
},
{
"code": null,
"e": 1982,
"s": 1860,
"text": "The project PyOpenCL is probably the easiest way to get started with GP-GPU on a Mac. See also its sister project PyCUDA."
},
{
"code": null,
"e": 2005,
"s": 1982,
"text": "$ pip install pyopencl"
},
{
"code": null,
"e": 2140,
"s": 2005,
"text": "The centrepiece of OpenCL is a kernel, which is a function (written in a C-like language) that can be applied to chunks of input data."
},
{
"code": null,
"e": 2264,
"s": 2140,
"text": "For an introduction to parallel programming follow this online course based on CUDA, or buy this book by Tim Mattson et al."
},
{
"code": null,
"e": 2632,
"s": 2264,
"text": "OpenCL is more flexible than CUDA to allow programs to be executed on different architectures. This comes with a price: it is necessary to write some “boilerplate” code to define a context (i.e. what kind of hardware is available), a queue (i.e. a sequence of commands) and a set of memory flags (e.g. READ_ONLY, WRITE_ONLY, etc.). The typical workflow is as follows:"
},
{
"code": null,
"e": 2820,
"s": 2632,
"text": "Input data is copied to the GPU memoryGPU buffer memory is reserved to host the result of the calculationsA kernels are executedThe result is copied from the GPU memory to the host memory"
},
{
"code": null,
"e": 2859,
"s": 2820,
"text": "Input data is copied to the GPU memory"
},
{
"code": null,
"e": 2928,
"s": 2859,
"text": "GPU buffer memory is reserved to host the result of the calculations"
},
{
"code": null,
"e": 2951,
"s": 2928,
"text": "A kernels are executed"
},
{
"code": null,
"e": 3011,
"s": 2951,
"text": "The result is copied from the GPU memory to the host memory"
},
{
"code": null,
"e": 3196,
"s": 3011,
"text": "NB: OpenCL kernels can be executed on both CPUs and GPUs, but if the code is highly optimized for a certain GPU architecture (e.g. with large memory) it may not be completely portable."
},
{
"code": null,
"e": 3376,
"s": 3196,
"text": "Though GPUs are generally faster, the time taken to transfer huge amounts of data from CPU to GPU can lead to higher overhead time depending on the architecture of the processors."
},
{
"code": null,
"e": 3472,
"s": 3376,
"text": "Here’s an example of a fully-functional OpenCL program that calculates the sum of two matrices:"
},
{
"code": null,
"e": 4432,
"s": 3472,
"text": "#!/usr/bin/env python# -*- coding: utf-8 -*-from __future__ import absolute_import, print_functionimport numpy as npimport pyopencl as cla_np = np.random.rand(50000).astype(np.float32)b_np = np.random.rand(50000).astype(np.float32)ctx = cl.create_some_context()queue = cl.CommandQueue(ctx)mf = cl.mem_flagsa_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a_np)b_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=b_np)kernel = \"\"\"__kernel void sum( __global const float *a_g, __global const float *b_g, __global float *res_g){ int gid = get_global_id(0); res_g[gid] = a_g[gid] + b_g[gid];}\"\"\"prg = cl.Program(ctx, kernel).build()res_g = cl.Buffer(ctx, mf.WRITE_ONLY, a_np.nbytes)prg.sum(queue, a_np.shape, None, a_g, b_g, res_g)res_np = np.empty_like(a_np)cl.enqueue_copy(queue, res_np, res_g)# Check on CPU with Numpy:print(res_np - (a_np + b_np))print(np.linalg.norm(res_np - (a_np + b_np)))assert np.allclose(res_np, a_np + b_np)"
},
{
"code": null,
"e": 5055,
"s": 4432,
"text": "Keras is one of the most popular deep learning frameworks. It’s very easy to define the architecture of a network using Keras’ functional APIs, run the training and execute inference. However, Keras does not perform the actual calculations by itself, but rather deploys other software libraries to define, optimize, and evaluate mathematical expressions involving multi-dimensional arrays. The most common ones are Theano and TensorFlow. In turn, these libraries execute parallel calculations on GPUs using CUDA. As previously states, this comes with the very strong hardware limitation that it works only on NVIDIA cards."
},
{
"code": null,
"e": 5130,
"s": 5055,
"text": "This problem can be partially evaded by using instead the PlaidML library:"
},
{
"code": null,
"e": 5158,
"s": 5130,
"text": "$ pip install plaidml-keras"
},
{
"code": null,
"e": 5259,
"s": 5158,
"text": "Following installation, execute the setup script (select default unless you know what you’re doing):"
},
{
"code": null,
"e": 5275,
"s": 5259,
"text": "$ plaidml-setup"
},
{
"code": null,
"e": 5311,
"s": 5275,
"text": "You should see something like this:"
},
{
"code": null,
"e": 6309,
"s": 5311,
"text": "PlaidML Setup (0.6.4)Thanks for using PlaidML!Some Notes: * Bugs and other issues: https://github.com/plaidml/plaidml * Questions: https://stackoverflow.com/questions/tagged/plaidml * Say hello: https://groups.google.com/forum/#!forum/plaidml-dev * PlaidML is licensed under the Apache License 2.0Default Config Devices: metal_amd_radeon_r9_m380.0 : AMD Radeon R9 M380 (Metal)Experimental Config Devices: llvm_cpu.0 : CPU (LLVM) opencl_amd_radeon_r9_m380_compute_engine.0 : AMD AMD Radeon R9 M380 Compute Engine (OpenCL) opencl_cpu.0 : Intel CPU (OpenCL) metal_amd_radeon_r9_m380.0 : AMD Radeon R9 M380 (Metal)Using experimental devices can cause poor performance, crashes, and other nastiness.Enable experimental device support? (y,n)[n]:Selected device: metal_amd_radeon_r9_m380.0Almost done. Multiplying some matrices...Tile code: function (B[X,Z], C[Z,Y]) -> (A) { A[x,y : X,Y] = +(B[x,z] * C[z,y]); }Whew. That worked.Save settings to /Users/user/.plaidml? (y,n)[y]:Success!"
},
{
"code": null,
"e": 6492,
"s": 6309,
"text": "This library supports many but not all Keras layers. If your architecture involves only Dense, LSTM, CNN and Dropout layers, you’re certainly good, otherwise check the documentation."
},
{
"code": null,
"e": 6617,
"s": 6492,
"text": "In principle, all you have to do is to pre-pend the following lines of code to your program to activate the PlaidML backend:"
},
{
"code": null,
"e": 6680,
"s": 6617,
"text": "import osos.environ[\"KERAS_BACKEND\"] = \"plaidml.keras.backend\""
},
{
"code": null,
"e": 6744,
"s": 6680,
"text": "During the execution, you should see some printouts like these:"
},
{
"code": null,
"e": 6837,
"s": 6744,
"text": "Using plaindml.keras.backend backendINFO:plaidml:Opening device \"metal_amd_radeon_r9_m380.0\""
},
{
"code": null,
"e": 6939,
"s": 6837,
"text": "This is an example, adapted from from Keras’ official documentation, that should work out-of-the-box:"
},
{
"code": null,
"e": 8984,
"s": 6939,
"text": "#!/usr/bin/env pythonimport osos.environ[\"KERAS_BACKEND\"] = \"plaidml.keras.backend\"import kerasfrom keras.datasets import mnistfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flattenfrom keras.layers import Conv2D, MaxPooling2Dfrom keras import backend as Kbatch_size = 128num_classes = 10epochs = 12# input image dimensionsimg_rows, img_cols = 28, 28# the data, split between train and test sets(x_train, y_train), (x_test, y_test) = mnist.load_data()if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols)else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1)x_train = x_train.astype('float32')x_test = x_test.astype('float32')x_train /= 255x_test /= 255print('x_train shape:', x_train.shape)print(x_train.shape[0], 'train samples')print(x_test.shape[0], 'test samples')# convert class vectors to binary class matricesy_train = keras.utils.to_categorical(y_train, num_classes)y_test = keras.utils.to_categorical(y_test, num_classes)model = Sequential()model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(128, activation='relu'))model.add(Dropout(0.5))model.add(Dense(num_classes, activation='softmax'))model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))score = model.evaluate(x_test, y_test, verbose=0)print('Test loss:', score[0])print('Test accuracy:', score[1])"
},
{
"code": null,
"e": 9171,
"s": 8984,
"text": "On a 2015 iMac (3.2 GHz Intel Core i5, 16 GB DDR RAM, AMD Radeon R9 M380 2 GB GPU) it took 1m50s to train with PlaidML/OpenCL GPU backend, and 5m06s using the TensorFlow-2.0/CPU backend."
},
{
"code": null,
"e": 9357,
"s": 9171,
"text": "Note that the instruction from keras import backend as K would return an error if there is no available backend. For example, if you did not install TensorFlow (default), you would see:"
},
{
"code": null,
"e": 10289,
"s": 9357,
"text": "Using TensorFlow backend.Traceback (most recent call last): File \"./test_keras.py\", line 8, in <module> import keras File \"/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/__init__.py\", line 3, in <module> from . import utils File \"/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/utils/__init__.py\", line 6, in <module> from . import conv_utils File \"/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/utils/conv_utils.py\", line 9, in <module> from .. import backend as K File \"/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/backend/__init__.py\", line 89, in <module> from .tensorflow_backend import * File \"/Users/Riccardo/development/venv_opencl/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py\", line 5, in <module> import tensorflow as tfModuleNotFoundError: No module named 'tensorflow'"
},
{
"code": null,
"e": 10559,
"s": 10289,
"text": "On a final note, TensorFlow >=2.0 includes Keras API. If your program is written so that layers are defined from TF, and not Keras, you cannot just change the Keras backend to run on the GPU with OpenCL support, because TF2 does not support OpenCL. To be more specific:"
},
{
"code": null,
"e": 10632,
"s": 10559,
"text": "This will not use the GPU (assuming you have installed TensorFlow >=2.0)"
},
{
"code": null,
"e": 10696,
"s": 10632,
"text": "from tensorflow import kerasfrom tensorflow.keras import layers"
},
{
"code": null,
"e": 10757,
"s": 10696,
"text": "This will work just fine (assuming you have installed Keras)"
},
{
"code": null,
"e": 10794,
"s": 10757,
"text": "import kerasfrom keras import layers"
},
{
"code": null,
"e": 11141,
"s": 10794,
"text": "It turns out that PlaidML can do much more than just being a Keras backend. In fact, it comes with a programming language called Tile to help users writing optimized kernels without requiring an in-depth knowledge of C and most of the quirks of OpenCL. Tile instructions look more like mathematical functions. For example, a matrix multiplication"
},
{
"code": null,
"e": 11165,
"s": 11141,
"text": "looks like this in Tile"
},
{
"code": null,
"e": 11244,
"s": 11165,
"text": "function (A[M, L], B[L, N]) -> (C) { C[i, j: M, N] = +(A[i, k] * B[k, j]);}"
},
{
"code": null,
"e": 11320,
"s": 11244,
"text": "where the “+” operator stands for the “sum” in the mathematical expression."
},
{
"code": null,
"e": 11970,
"s": 11320,
"text": "Many more examples can be found in the documentation, including some of the most common operations such as matrix multiplication, min/max, max pool, convolution, cumulative sum. When the kernel is synthesized, Tile flattens the tensors and transforms indices into pointer offsets. The calculation is split into tiles that fit into memory, with a size that is optimized based on the available hardware. The tiles are then laid out in the GPU memory to optimize SIMDs instructions such as multiplications and accumulations. Finally, the kernels are written out as if they were created by a human user, and passed on to OpenCL for the actual execution."
}
] |
Convert.ToInt64 Method in C# | Convert a specified value to a 64-bit signed integer using Convert.ToInt64 Method.
Let us take a double value.
double doubleNum = 193.834;
Now, convert it to Int64 i.e. long.
long res;
res = Convert.ToInt32(doubleNum);
Live Demo
using System;
public class Demo {
public static void Main() {
double doubleNum = 193.834;
long res;
res = Convert.ToInt32(doubleNum);
Console.WriteLine("Converted {0} to {1}", doubleNum, res);
}
}
Converted 193.834 to 194 | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "Convert a specified value to a 64-bit signed integer using Convert.ToInt64 Method."
},
{
"code": null,
"e": 1173,
"s": 1145,
"text": "Let us take a double value."
},
{
"code": null,
"e": 1201,
"s": 1173,
"text": "double doubleNum = 193.834;"
},
{
"code": null,
"e": 1237,
"s": 1201,
"text": "Now, convert it to Int64 i.e. long."
},
{
"code": null,
"e": 1281,
"s": 1237,
"text": "long res;\nres = Convert.ToInt32(doubleNum);"
},
{
"code": null,
"e": 1292,
"s": 1281,
"text": " Live Demo"
},
{
"code": null,
"e": 1519,
"s": 1292,
"text": "using System;\npublic class Demo {\n public static void Main() {\n double doubleNum = 193.834;\n long res;\n res = Convert.ToInt32(doubleNum);\n Console.WriteLine(\"Converted {0} to {1}\", doubleNum, res);\n }\n}"
},
{
"code": null,
"e": 1544,
"s": 1519,
"text": "Converted 193.834 to 194"
}
] |
How to assign the result of a MySQL query into a variable? | Use @anyVariableName to assign the result of a query into a variable. Let us first create a table −
mysql> create table DemoTable1864
(
Id int,
FirstName varchar(20),
LastName varchar(20)
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1864 values(101,'Chris','Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1864 values(102,'David','Miller');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1864 values(103,'Adam','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1864 values(104,'John','Doe');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1864;
This will produce the following output −
+------+-----------+----------+
| Id | FirstName | LastName |
+------+-----------+----------+
| 101 | Chris | Brown |
| 102 | David | Miller |
| 103 | Adam | Smith |
| 104 | John | Doe |
+------+-----------+----------+
4 rows in set (0.00 sec)
Here is the query to assign the result of a query into a variable −
mysql> select @fName:=FirstName,@lName:=LastName
from DemoTable1864
where Id=103;
This will produce the following output −
+-------------------+------------------+
| @fName:=FirstName | @lName:=LastName |
+-------------------+------------------+
| Adam | Smith |
+-------------------+------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "Use @anyVariableName to assign the result of a query into a variable. Let us first create a table −"
},
{
"code": null,
"e": 1315,
"s": 1162,
"text": "mysql> create table DemoTable1864\n (\n Id int,\n FirstName varchar(20),\n LastName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1371,
"s": 1315,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1760,
"s": 1371,
"text": "mysql> insert into DemoTable1864 values(101,'Chris','Brown');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1864 values(102,'David','Miller');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1864 values(103,'Adam','Smith');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1864 values(104,'John','Doe');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1820,
"s": 1760,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1857,
"s": 1820,
"text": "mysql> select * from DemoTable1864;"
},
{
"code": null,
"e": 1898,
"s": 1857,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2179,
"s": 1898,
"text": "+------+-----------+----------+\n| Id | FirstName | LastName |\n+------+-----------+----------+\n| 101 | Chris | Brown |\n| 102 | David | Miller |\n| 103 | Adam | Smith |\n| 104 | John | Doe |\n+------+-----------+----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2247,
"s": 2179,
"text": "Here is the query to assign the result of a query into a variable −"
},
{
"code": null,
"e": 2339,
"s": 2247,
"text": "mysql> select @fName:=FirstName,@lName:=LastName\n from DemoTable1864\n where Id=103;"
},
{
"code": null,
"e": 2380,
"s": 2339,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2609,
"s": 2380,
"text": "+-------------------+------------------+\n| @fName:=FirstName | @lName:=LastName |\n+-------------------+------------------+\n| Adam | Smith |\n+-------------------+------------------+\n1 row in set (0.00 sec)"
}
] |
Billion-scale semantic similarity search with FAISS+SBERT | by Mathew Alexander | Towards Data Science | Semantic search is an information retrieval system that focuses on the meaning of the sentences rather than the conventional keyword matching. Even though there are many text embeddings that can be used for this purpose, scaling this up to build low latency APIs that can fetch data from a huge collection of data is something that is seldom discussed. In this article, I will discuss how we can implement a minimal semantic search engine using SOTA sentence embeddings (sentence transformer) and FAISS.
It is a framework or set of models that give dense vector representations of sentences or paragraphs. These models are transformer networks(BERT, RoBERTa, etc.) which are fine-tuned specifically for the task of Semantic textual similarity as the BERT doesn’t perform well out of the box for these tasks. Given below is the performance of different models in the STS benchmark
We can see that the Sentence transformer models outperform the other models by a large margin.
But if you look at the leaderboard by papers with code and GLUE, you would see many models above 90. So why do we need Sentence transformers?.
Well, In those models, the semantic Textual similarity is considered as a regression task. This means whenever we need to calculate the similarity score between two sentences, we need to pass them together into the model and the model outputs the numerical score between them. While this works well for the benchmarking test, it scales badly for a real-life use case, and here are the reasons.
When you need to search over say 10 k documents, you would need to perform 10k separate inference computations, its not possible to compute the embeddings separately and calculate just the cosine similarity. See the author’s explanation.The maximum sequence length (The total number of words/tokens the model can take at one pass) is shared between two documents, which causes the representations to be diluted due to chunking
When you need to search over say 10 k documents, you would need to perform 10k separate inference computations, its not possible to compute the embeddings separately and calculate just the cosine similarity. See the author’s explanation.
The maximum sequence length (The total number of words/tokens the model can take at one pass) is shared between two documents, which causes the representations to be diluted due to chunking
Faiss is a C++ based library built by Facebook AI with a complete wrapper in python, to index vectorized data and to perform efficient searches on them. Faiss offers different indexes based on the following factors
search time
search quality
memory used per index vector
training time
need for external data for unsupervised training
So choosing the right index will be a trade-off between these factors.
First, let us install and load the required libraries
!pip install faiss-cpu!pip install -U sentence-transformersimport numpy as npimport torchimport osimport pandas as pdimport faissimport timefrom sentence_transformers import SentenceTransformer
Loading the dataset with a million datapoints
I used a dataset from Kaggle that contains news headlines published over a period of seventeen years.
df=pd.read_csv("abcnews-date-text.csv")data=df.headline_text.to_list()
Loading the pre-trained model and performing the inference
model = SentenceTransformer('distilbert-base-nli-mean-tokens')encoded_data = model.encode(data)
We can choose different indexing options based on our use case by referring to the guide.
Let's define the index and add data to it
index = faiss.IndexIDMap(faiss.IndexFlatIP(768))index.add_with_ids(encoded_data, np.array(range(0, len(data))))
Serializing the index
faiss.write_index(index, 'abc_news')
The serialized index can be then exported into any machine for hosting the search engine
Deserializing the index
index = faiss.read_index('abc_news')
Let us first build a wrapper function for search
def search(query): t=time.time() query_vector = model.encode([query]) k = 5 top_k = index.search(query_vector, k) print('totaltime: {}'.format(time.time()-t)) return [data[_id] for _id in top_k[1].tolist()[0]]
performing the search
query=str(input())results=search(query)print('results :')for result in results: print('\t',result)
Now let's take a look at the search results and response time
1.5 seconds is all it takes to perform an intelligent meaning-based search on a dataset of million text documents with just the CPU backend.
First, let's uninstall the CPU version of Faiss and reinstall the GPU version
!pip uninstall faiss-cpu!pip install faiss-gpu
Then follow the same procedure, but at the end move the index to GPU.
res = faiss.StandardGpuResources()gpu_index = faiss.index_cpu_to_gpu(res, 0, index)
Now let's place this inside the search function and perform the search with the GPU.
That’s right, you can get the results within 0.02 sec with a GPU ( Tesla T4 is used in this experiment) which is 75 times faster than a CPU backend
Because the NumPy doesn’t come with native serialization functions, hence the only way is to convert it into a JSON and then save the JSON object, but then the size will increase by a factor of five. For example, a million data points encoded into a 768-dimensional vector space with normal indexing will be about 3GB, converting it into JSON will make it 15GB, which a normal machine can’t hold on it’s RAM. So we will have to run a million computational inference each time we perform a search, which is not practical.
This is a basic implementation and a lot needs to be still done both on the language model part and the indexing part. There are different indexing options from which the right one should be chosen based on the use case, size of the data and the compute power available. Also, the sentence embedding used here is just fine-tuned on some public datasets, fine-tuning them on the domain-specific dataset would improve the embeddings and hence the search results.
[1] Nils Reimers and Iryna Gurevych. “Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation.” arXiv (2020): 2004.09813.
[2]Johnson, Jeff and Douze, Matthijs and J{\’e}gou, Herv{\’e}. “Billion-scale similarity search with GPUs” arXiv preprint arXiv:1702.08734. | [
{
"code": null,
"e": 676,
"s": 172,
"text": "Semantic search is an information retrieval system that focuses on the meaning of the sentences rather than the conventional keyword matching. Even though there are many text embeddings that can be used for this purpose, scaling this up to build low latency APIs that can fetch data from a huge collection of data is something that is seldom discussed. In this article, I will discuss how we can implement a minimal semantic search engine using SOTA sentence embeddings (sentence transformer) and FAISS."
},
{
"code": null,
"e": 1052,
"s": 676,
"text": "It is a framework or set of models that give dense vector representations of sentences or paragraphs. These models are transformer networks(BERT, RoBERTa, etc.) which are fine-tuned specifically for the task of Semantic textual similarity as the BERT doesn’t perform well out of the box for these tasks. Given below is the performance of different models in the STS benchmark"
},
{
"code": null,
"e": 1147,
"s": 1052,
"text": "We can see that the Sentence transformer models outperform the other models by a large margin."
},
{
"code": null,
"e": 1290,
"s": 1147,
"text": "But if you look at the leaderboard by papers with code and GLUE, you would see many models above 90. So why do we need Sentence transformers?."
},
{
"code": null,
"e": 1684,
"s": 1290,
"text": "Well, In those models, the semantic Textual similarity is considered as a regression task. This means whenever we need to calculate the similarity score between two sentences, we need to pass them together into the model and the model outputs the numerical score between them. While this works well for the benchmarking test, it scales badly for a real-life use case, and here are the reasons."
},
{
"code": null,
"e": 2111,
"s": 1684,
"text": "When you need to search over say 10 k documents, you would need to perform 10k separate inference computations, its not possible to compute the embeddings separately and calculate just the cosine similarity. See the author’s explanation.The maximum sequence length (The total number of words/tokens the model can take at one pass) is shared between two documents, which causes the representations to be diluted due to chunking"
},
{
"code": null,
"e": 2349,
"s": 2111,
"text": "When you need to search over say 10 k documents, you would need to perform 10k separate inference computations, its not possible to compute the embeddings separately and calculate just the cosine similarity. See the author’s explanation."
},
{
"code": null,
"e": 2539,
"s": 2349,
"text": "The maximum sequence length (The total number of words/tokens the model can take at one pass) is shared between two documents, which causes the representations to be diluted due to chunking"
},
{
"code": null,
"e": 2754,
"s": 2539,
"text": "Faiss is a C++ based library built by Facebook AI with a complete wrapper in python, to index vectorized data and to perform efficient searches on them. Faiss offers different indexes based on the following factors"
},
{
"code": null,
"e": 2766,
"s": 2754,
"text": "search time"
},
{
"code": null,
"e": 2781,
"s": 2766,
"text": "search quality"
},
{
"code": null,
"e": 2810,
"s": 2781,
"text": "memory used per index vector"
},
{
"code": null,
"e": 2824,
"s": 2810,
"text": "training time"
},
{
"code": null,
"e": 2873,
"s": 2824,
"text": "need for external data for unsupervised training"
},
{
"code": null,
"e": 2944,
"s": 2873,
"text": "So choosing the right index will be a trade-off between these factors."
},
{
"code": null,
"e": 2998,
"s": 2944,
"text": "First, let us install and load the required libraries"
},
{
"code": null,
"e": 3192,
"s": 2998,
"text": "!pip install faiss-cpu!pip install -U sentence-transformersimport numpy as npimport torchimport osimport pandas as pdimport faissimport timefrom sentence_transformers import SentenceTransformer"
},
{
"code": null,
"e": 3238,
"s": 3192,
"text": "Loading the dataset with a million datapoints"
},
{
"code": null,
"e": 3340,
"s": 3238,
"text": "I used a dataset from Kaggle that contains news headlines published over a period of seventeen years."
},
{
"code": null,
"e": 3411,
"s": 3340,
"text": "df=pd.read_csv(\"abcnews-date-text.csv\")data=df.headline_text.to_list()"
},
{
"code": null,
"e": 3470,
"s": 3411,
"text": "Loading the pre-trained model and performing the inference"
},
{
"code": null,
"e": 3566,
"s": 3470,
"text": "model = SentenceTransformer('distilbert-base-nli-mean-tokens')encoded_data = model.encode(data)"
},
{
"code": null,
"e": 3656,
"s": 3566,
"text": "We can choose different indexing options based on our use case by referring to the guide."
},
{
"code": null,
"e": 3698,
"s": 3656,
"text": "Let's define the index and add data to it"
},
{
"code": null,
"e": 3810,
"s": 3698,
"text": "index = faiss.IndexIDMap(faiss.IndexFlatIP(768))index.add_with_ids(encoded_data, np.array(range(0, len(data))))"
},
{
"code": null,
"e": 3832,
"s": 3810,
"text": "Serializing the index"
},
{
"code": null,
"e": 3869,
"s": 3832,
"text": "faiss.write_index(index, 'abc_news')"
},
{
"code": null,
"e": 3958,
"s": 3869,
"text": "The serialized index can be then exported into any machine for hosting the search engine"
},
{
"code": null,
"e": 3982,
"s": 3958,
"text": "Deserializing the index"
},
{
"code": null,
"e": 4019,
"s": 3982,
"text": "index = faiss.read_index('abc_news')"
},
{
"code": null,
"e": 4068,
"s": 4019,
"text": "Let us first build a wrapper function for search"
},
{
"code": null,
"e": 4290,
"s": 4068,
"text": "def search(query): t=time.time() query_vector = model.encode([query]) k = 5 top_k = index.search(query_vector, k) print('totaltime: {}'.format(time.time()-t)) return [data[_id] for _id in top_k[1].tolist()[0]]"
},
{
"code": null,
"e": 4312,
"s": 4290,
"text": "performing the search"
},
{
"code": null,
"e": 4413,
"s": 4312,
"text": "query=str(input())results=search(query)print('results :')for result in results: print('\\t',result)"
},
{
"code": null,
"e": 4475,
"s": 4413,
"text": "Now let's take a look at the search results and response time"
},
{
"code": null,
"e": 4616,
"s": 4475,
"text": "1.5 seconds is all it takes to perform an intelligent meaning-based search on a dataset of million text documents with just the CPU backend."
},
{
"code": null,
"e": 4694,
"s": 4616,
"text": "First, let's uninstall the CPU version of Faiss and reinstall the GPU version"
},
{
"code": null,
"e": 4741,
"s": 4694,
"text": "!pip uninstall faiss-cpu!pip install faiss-gpu"
},
{
"code": null,
"e": 4811,
"s": 4741,
"text": "Then follow the same procedure, but at the end move the index to GPU."
},
{
"code": null,
"e": 4895,
"s": 4811,
"text": "res = faiss.StandardGpuResources()gpu_index = faiss.index_cpu_to_gpu(res, 0, index)"
},
{
"code": null,
"e": 4980,
"s": 4895,
"text": "Now let's place this inside the search function and perform the search with the GPU."
},
{
"code": null,
"e": 5128,
"s": 4980,
"text": "That’s right, you can get the results within 0.02 sec with a GPU ( Tesla T4 is used in this experiment) which is 75 times faster than a CPU backend"
},
{
"code": null,
"e": 5649,
"s": 5128,
"text": "Because the NumPy doesn’t come with native serialization functions, hence the only way is to convert it into a JSON and then save the JSON object, but then the size will increase by a factor of five. For example, a million data points encoded into a 768-dimensional vector space with normal indexing will be about 3GB, converting it into JSON will make it 15GB, which a normal machine can’t hold on it’s RAM. So we will have to run a million computational inference each time we perform a search, which is not practical."
},
{
"code": null,
"e": 6110,
"s": 5649,
"text": "This is a basic implementation and a lot needs to be still done both on the language model part and the indexing part. There are different indexing options from which the right one should be chosen based on the use case, size of the data and the compute power available. Also, the sentence embedding used here is just fine-tuned on some public datasets, fine-tuning them on the domain-specific dataset would improve the embeddings and hence the search results."
},
{
"code": null,
"e": 6257,
"s": 6110,
"text": "[1] Nils Reimers and Iryna Gurevych. “Making Monolingual Sentence Embeddings Multilingual using Knowledge Distillation.” arXiv (2020): 2004.09813."
}
] |
Tryit Editor v3.7 | Tryit: Using the animation-fill-mode property | [] |
How to use grid for images in bootstrap card ? - GeeksforGeeks | 29 Jan, 2020
Images can be added to the Bootstrap card by simply using an img tag. But we cannot use the same method directly to place an Image Grid into the Bootstrap Card as it will be lead to a misaligned design. Therefore, to get a per-flow to place image Grid into Bootstrap Card. The perfectly aligned grid we need to add some CSS to our HTML code.
Approach: First set the value display: grid; of the div wrapping all the images to transform it into to a grid layout. Then set the value grid-template-columns: auto; of the grid container to specify the number of columns in the grid layout. Now set the value width: 100%; of the image to get a perfect grid.
Below examples illustrate the above approach:
Example 1: Image grid with 2 columns i.e. 2×2 Image grid.
<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card { width: 20rem; margin: 2rem; } .image-grid-container { display: grid; /* For 2 columns */ grid-template-columns: auto auto; } img { width: 100%; } </style></body> <body> <div class="container"> <div class="card"> <div class="image-grid-container"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"> </div> <div class="card-body"> <h4 class="card-title">Developer Guy</h4> <p class="card-text"> Developer Guy love to develop front-end and back-end </p> <a href="#" class="btn btn-primary"> See Profile </a> </div> </div> </div></body> </html>
Output:
Example 2: Image grid with 3 columns i.e. 3×3 Image grid.
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Cards</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card { width: 20rem; margin: 2rem; } .image-grid-container { display: grid; /* For 3 columns */ grid-template-columns: auto auto auto; } img { width: 100%; } </style></head> <body> <div class="container"> <div class="card"> <div class="image-grid-container"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"> </div> <div class="card-body"> <h4 class="card-title"> Developer Guy </h4> <p class="card-text"> Developer Guy love to develop front-end and back-end </p> <a href="#" class="btn btn-primary"> See Profile </a> </div> </div> </div></body> </html>
Output:
Bootstrap-4
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Create a Homepage for Restaurant using HTML , CSS and Bootstrap
Tailwind CSS vs Bootstrap
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": 24956,
"s": 24928,
"text": "\n29 Jan, 2020"
},
{
"code": null,
"e": 25298,
"s": 24956,
"text": "Images can be added to the Bootstrap card by simply using an img tag. But we cannot use the same method directly to place an Image Grid into the Bootstrap Card as it will be lead to a misaligned design. Therefore, to get a per-flow to place image Grid into Bootstrap Card. The perfectly aligned grid we need to add some CSS to our HTML code."
},
{
"code": null,
"e": 25607,
"s": 25298,
"text": "Approach: First set the value display: grid; of the div wrapping all the images to transform it into to a grid layout. Then set the value grid-template-columns: auto; of the grid container to specify the number of columns in the grid layout. Now set the value width: 100%; of the image to get a perfect grid."
},
{
"code": null,
"e": 25653,
"s": 25607,
"text": "Below examples illustrate the above approach:"
},
{
"code": null,
"e": 25711,
"s": 25653,
"text": "Example 1: Image grid with 2 columns i.e. 2×2 Image grid."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card { width: 20rem; margin: 2rem; } .image-grid-container { display: grid; /* For 2 columns */ grid-template-columns: auto auto; } img { width: 100%; } </style></body> <body> <div class=\"container\"> <div class=\"card\"> <div class=\"image-grid-container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\"> </div> <div class=\"card-body\"> <h4 class=\"card-title\">Developer Guy</h4> <p class=\"card-text\"> Developer Guy love to develop front-end and back-end </p> <a href=\"#\" class=\"btn btn-primary\"> See Profile </a> </div> </div> </div></body> </html>",
"e": 27624,
"s": 25711,
"text": null
},
{
"code": null,
"e": 27632,
"s": 27624,
"text": "Output:"
},
{
"code": null,
"e": 27690,
"s": 27632,
"text": "Example 2: Image grid with 3 columns i.e. 3×3 Image grid."
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <title>Bootstrap Cards</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card { width: 20rem; margin: 2rem; } .image-grid-container { display: grid; /* For 3 columns */ grid-template-columns: auto auto auto; } img { width: 100%; } </style></head> <body> <div class=\"container\"> <div class=\"card\"> <div class=\"image-grid-container\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\"> </div> <div class=\"card-body\"> <h4 class=\"card-title\"> Developer Guy </h4> <p class=\"card-text\"> Developer Guy love to develop front-end and back-end </p> <a href=\"#\" class=\"btn btn-primary\"> See Profile </a> </div> </div> </div></body> </html>",
"e": 30188,
"s": 27690,
"text": null
},
{
"code": null,
"e": 30196,
"s": 30188,
"text": "Output:"
},
{
"code": null,
"e": 30208,
"s": 30196,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 30223,
"s": 30208,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 30230,
"s": 30223,
"text": "Picked"
},
{
"code": null,
"e": 30240,
"s": 30230,
"text": "Bootstrap"
},
{
"code": null,
"e": 30257,
"s": 30240,
"text": "Web Technologies"
},
{
"code": null,
"e": 30284,
"s": 30257,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30382,
"s": 30284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30391,
"s": 30382,
"text": "Comments"
},
{
"code": null,
"e": 30404,
"s": 30391,
"text": "Old Comments"
},
{
"code": null,
"e": 30445,
"s": 30404,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30508,
"s": 30445,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30541,
"s": 30508,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 30605,
"s": 30541,
"text": "Create a Homepage for Restaurant using HTML , CSS and Bootstrap"
},
{
"code": null,
"e": 30631,
"s": 30605,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 30673,
"s": 30631,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30706,
"s": 30673,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30768,
"s": 30706,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30811,
"s": 30768,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Using PyTorch Lightning Flash and FiftyOne to Build Computer Vision Models, Fast | by Eric Hofesmann | Towards Data Science | Open-source tools have made significant advances in recent years to fill many of the same needs as end-to-end platform services. They can be incredibly useful for everything from model architecture development, to dataset curation, to model training and deployment. With enough digging, you can find an open-source tool that is able to support most portions of the data and model lifecycle. Tight integrations between tools are the best way to enable near-seamless workflows. This post delves into a new integration between the model prototyping and training framework, PyTorch Lightning Flash, and the dataset visualization and model analysis tool, FiftyOne.
Lightning Flash is a new framework built atop PyTorch Lighting and provides a collection of tasks for fast prototyping, baselining, fine-tuning, and solving business and scientific problems with deep learning. Even though Flash is easy to pick up no matter the amount of experience you have with deep learning, you can modify the existing tasks with Lightning and PyTorch to find the right level of abstraction for you. To speed things up even more, Flash code is scalable with built-in support for distributed training and inference on any hardware.
Flash makes it really easy to train your first model, but to continue improving it you will need to know how your model performs and how you can improve it. FiftyOne is an open-source tool for building high-quality datasets and computer vision models developed by Voxel51. It provides the building blocks for optimizing your dataset analysis pipeline, allowing you to get hands-on with your data, including visualizing complex labels, evaluating your models, exploring scenarios of interest, identifying failure modes, finding annotation mistakes, curating training datasets, and much more.
With Flash + FiftyOne, you can load datasets, train models, and analyze results for all of the following computer vision tasks:
Image Classification
Image Object Detection
Image Semantic Segmentation
Video Classification
Embeddings Visualization
The tight integration between Flash and FiftyOne allows you to execute an end-to-end workflow of loading a dataset, training a model on it, and visualizing/analyzing its predictions, all with just a few simple blocks of code
While it has always been easy to develop datasets with FiftyOne, the integration with PyTorch Lightning Flash now allows you to put those datasets to work by loading them into Flash and training tasks directly.
Flash provides the tools needed to grab a model for your task and start finetuning it on your data with as little code as possible and, most importantly, without needing to be an expert in the field.
Visualization of image and video data is always a challenge due to the complexity and size of modern datasets. FiftyOne was designed to provide a user-friendly view into your datasets and labels (including annotations and model predictions) which is now accessible by Flash models in one additional line of code.
To follow along with the examples in this post, you will need to install relevant packages. Primarily, you will need to install PyTorch Lightning Flash and FiftyOne.
pip install fiftyone lightning-flash
For the embeddings visualization workflow, you will also need to install the dimensionality reduction package, umap-learn:
pip install umap-learn
Most model development workflows with these tools follow the same general structure:
Load a dataset into FiftyOneCreate a Flash datamodule from the datasetFinetune a taskGenerate predictions from a modelAdd the predictions back to the dataset and visualize them
Load a dataset into FiftyOne
Create a Flash datamodule from the dataset
Finetune a task
Generate predictions from a model
Add the predictions back to the dataset and visualize them
This section shows a concrete example of using this integration between PyTorch Lightning Flash and FiftyOne to train and evaluate an image object detection model.
From here, you now have your predictions back in your dataset and can run an evaluation to generate confusion matrices, PR curves, and metrics like accuracy and mAP. In particular, you are able to identify and see individual true/false positive/negative results that allow you to understand where your model performs well and where it performs poorly. Improving your model based on common failure modes is the more surefire way to develop better models.
This workflow is unique in that it takes pretrained models and uses them to generate embedding vectors for every image in your dataset. You can then compute a visualization of these embeddings in a low dimensional space to find clusters of data. This functionality can lead to invaluable findings for the purposes of hard sample mining, data pre-annotation, sample recommendation for annotation, and much more.
With the notion of interactive plots, you are able to click on or circle regions of these embeddings and automatically update your session to view and tag the corresponding samples.
You can view similar workflows for other tasks like classification and segmentation here.
Over the years, impressive developments have come from the open-source community, especially in the field of machine learning. While individual tools can be great at solving specific problems, it is the tight integrations between tools that lead to powerful workflows. The new integration between PyTorch Lightning Flash and FiftyOne provides a new and easy way to develop datasets, train models, and analyze results.
(This post was co-authored by the PyTorch Lightning and Voxel51 teams) | [
{
"code": null,
"e": 832,
"s": 172,
"text": "Open-source tools have made significant advances in recent years to fill many of the same needs as end-to-end platform services. They can be incredibly useful for everything from model architecture development, to dataset curation, to model training and deployment. With enough digging, you can find an open-source tool that is able to support most portions of the data and model lifecycle. Tight integrations between tools are the best way to enable near-seamless workflows. This post delves into a new integration between the model prototyping and training framework, PyTorch Lightning Flash, and the dataset visualization and model analysis tool, FiftyOne."
},
{
"code": null,
"e": 1383,
"s": 832,
"text": "Lightning Flash is a new framework built atop PyTorch Lighting and provides a collection of tasks for fast prototyping, baselining, fine-tuning, and solving business and scientific problems with deep learning. Even though Flash is easy to pick up no matter the amount of experience you have with deep learning, you can modify the existing tasks with Lightning and PyTorch to find the right level of abstraction for you. To speed things up even more, Flash code is scalable with built-in support for distributed training and inference on any hardware."
},
{
"code": null,
"e": 1974,
"s": 1383,
"text": "Flash makes it really easy to train your first model, but to continue improving it you will need to know how your model performs and how you can improve it. FiftyOne is an open-source tool for building high-quality datasets and computer vision models developed by Voxel51. It provides the building blocks for optimizing your dataset analysis pipeline, allowing you to get hands-on with your data, including visualizing complex labels, evaluating your models, exploring scenarios of interest, identifying failure modes, finding annotation mistakes, curating training datasets, and much more."
},
{
"code": null,
"e": 2102,
"s": 1974,
"text": "With Flash + FiftyOne, you can load datasets, train models, and analyze results for all of the following computer vision tasks:"
},
{
"code": null,
"e": 2123,
"s": 2102,
"text": "Image Classification"
},
{
"code": null,
"e": 2146,
"s": 2123,
"text": "Image Object Detection"
},
{
"code": null,
"e": 2174,
"s": 2146,
"text": "Image Semantic Segmentation"
},
{
"code": null,
"e": 2195,
"s": 2174,
"text": "Video Classification"
},
{
"code": null,
"e": 2220,
"s": 2195,
"text": "Embeddings Visualization"
},
{
"code": null,
"e": 2445,
"s": 2220,
"text": "The tight integration between Flash and FiftyOne allows you to execute an end-to-end workflow of loading a dataset, training a model on it, and visualizing/analyzing its predictions, all with just a few simple blocks of code"
},
{
"code": null,
"e": 2656,
"s": 2445,
"text": "While it has always been easy to develop datasets with FiftyOne, the integration with PyTorch Lightning Flash now allows you to put those datasets to work by loading them into Flash and training tasks directly."
},
{
"code": null,
"e": 2856,
"s": 2656,
"text": "Flash provides the tools needed to grab a model for your task and start finetuning it on your data with as little code as possible and, most importantly, without needing to be an expert in the field."
},
{
"code": null,
"e": 3169,
"s": 2856,
"text": "Visualization of image and video data is always a challenge due to the complexity and size of modern datasets. FiftyOne was designed to provide a user-friendly view into your datasets and labels (including annotations and model predictions) which is now accessible by Flash models in one additional line of code."
},
{
"code": null,
"e": 3335,
"s": 3169,
"text": "To follow along with the examples in this post, you will need to install relevant packages. Primarily, you will need to install PyTorch Lightning Flash and FiftyOne."
},
{
"code": null,
"e": 3372,
"s": 3335,
"text": "pip install fiftyone lightning-flash"
},
{
"code": null,
"e": 3495,
"s": 3372,
"text": "For the embeddings visualization workflow, you will also need to install the dimensionality reduction package, umap-learn:"
},
{
"code": null,
"e": 3518,
"s": 3495,
"text": "pip install umap-learn"
},
{
"code": null,
"e": 3603,
"s": 3518,
"text": "Most model development workflows with these tools follow the same general structure:"
},
{
"code": null,
"e": 3780,
"s": 3603,
"text": "Load a dataset into FiftyOneCreate a Flash datamodule from the datasetFinetune a taskGenerate predictions from a modelAdd the predictions back to the dataset and visualize them"
},
{
"code": null,
"e": 3809,
"s": 3780,
"text": "Load a dataset into FiftyOne"
},
{
"code": null,
"e": 3852,
"s": 3809,
"text": "Create a Flash datamodule from the dataset"
},
{
"code": null,
"e": 3868,
"s": 3852,
"text": "Finetune a task"
},
{
"code": null,
"e": 3902,
"s": 3868,
"text": "Generate predictions from a model"
},
{
"code": null,
"e": 3961,
"s": 3902,
"text": "Add the predictions back to the dataset and visualize them"
},
{
"code": null,
"e": 4125,
"s": 3961,
"text": "This section shows a concrete example of using this integration between PyTorch Lightning Flash and FiftyOne to train and evaluate an image object detection model."
},
{
"code": null,
"e": 4579,
"s": 4125,
"text": "From here, you now have your predictions back in your dataset and can run an evaluation to generate confusion matrices, PR curves, and metrics like accuracy and mAP. In particular, you are able to identify and see individual true/false positive/negative results that allow you to understand where your model performs well and where it performs poorly. Improving your model based on common failure modes is the more surefire way to develop better models."
},
{
"code": null,
"e": 4990,
"s": 4579,
"text": "This workflow is unique in that it takes pretrained models and uses them to generate embedding vectors for every image in your dataset. You can then compute a visualization of these embeddings in a low dimensional space to find clusters of data. This functionality can lead to invaluable findings for the purposes of hard sample mining, data pre-annotation, sample recommendation for annotation, and much more."
},
{
"code": null,
"e": 5172,
"s": 4990,
"text": "With the notion of interactive plots, you are able to click on or circle regions of these embeddings and automatically update your session to view and tag the corresponding samples."
},
{
"code": null,
"e": 5262,
"s": 5172,
"text": "You can view similar workflows for other tasks like classification and segmentation here."
},
{
"code": null,
"e": 5680,
"s": 5262,
"text": "Over the years, impressive developments have come from the open-source community, especially in the field of machine learning. While individual tools can be great at solving specific problems, it is the tight integrations between tools that lead to powerful workflows. The new integration between PyTorch Lightning Flash and FiftyOne provides a new and easy way to develop datasets, train models, and analyze results."
}
] |
How to check whether a number is prime or not using Python? | Principle used in following solution to this problem is to divide given number with all from 3 its square root, a number's square root is largest possible factor beyond which it is not necessary to check if it is divisible by any other number to decide that it is prime number.
The function returns false for all numbers divisible by 2 and less than 2. For others return value of all) function will be false if it is divisible by any number upto its square root and true if it is not divisible by any number
def is_prime(a):
if a < 2:
return False
elif a!=2 and a % 2 == 0:
return False
else:
return all (a % i for i in range(3, int(a**0.5)+1) )
num=int(input('enter a number'))
if is_prime(num)==True:
print ("{} is a prime number".format(num))
else:
print ("{} is not a prime number".format(num))
Sample run of above program −
enter a number24
24 is not a prime number
enter a number47
47 is a prime number | [
{
"code": null,
"e": 1340,
"s": 1062,
"text": "Principle used in following solution to this problem is to divide given number with all from 3 its square root, a number's square root is largest possible factor beyond which it is not necessary to check if it is divisible by any other number to decide that it is prime number."
},
{
"code": null,
"e": 1570,
"s": 1340,
"text": "The function returns false for all numbers divisible by 2 and less than 2. For others return value of all) function will be false if it is divisible by any number upto its square root and true if it is not divisible by any number"
},
{
"code": null,
"e": 1905,
"s": 1570,
"text": "def is_prime(a):\n if a < 2:\n return False\n elif a!=2 and a % 2 == 0:\n return False\n else:\n return all (a % i for i in range(3, int(a**0.5)+1) )\nnum=int(input('enter a number'))\nif is_prime(num)==True:\n print (\"{} is a prime number\".format(num))\nelse:\n print (\"{} is not a prime number\".format(num))"
},
{
"code": null,
"e": 1935,
"s": 1905,
"text": "Sample run of above program −"
},
{
"code": null,
"e": 2015,
"s": 1935,
"text": "enter a number24\n24 is not a prime number\nenter a number47\n47 is a prime number"
}
] |
How to declare and initialize a dictionary in C#? | Dictionary is a collection of keys and values in C#. Dictionary is included in the System.Collection.Generics namespace.
To declare and initialize a Dictionary −
IDictionary d = new Dictionary();
Above, types of key and value are set while declaring a dictionary object. An int is a type of key and string is a type of value. Both will get stored in a dictionary object named d.
Let us now see an example −
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1,97);
d.Add(2,89);
d.Add(3,77);
d.Add(4,88);
// Dictionary elements
Console.WriteLine("Dictionary elements: "+d.Count);
}
}
Dictionary elements: 4 | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "Dictionary is a collection of keys and values in C#. Dictionary is included in the System.Collection.Generics namespace."
},
{
"code": null,
"e": 1224,
"s": 1183,
"text": "To declare and initialize a Dictionary −"
},
{
"code": null,
"e": 1258,
"s": 1224,
"text": "IDictionary d = new Dictionary();"
},
{
"code": null,
"e": 1441,
"s": 1258,
"text": "Above, types of key and value are set while declaring a dictionary object. An int is a type of key and string is a type of value. Both will get stored in a dictionary object named d."
},
{
"code": null,
"e": 1469,
"s": 1441,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 1480,
"s": 1469,
"text": " Live Demo"
},
{
"code": null,
"e": 1811,
"s": 1480,
"text": "using System;\nusing System.Collections.Generic;\n\npublic class Demo {\n public static void Main() {\n IDictionary<int, int> d = new Dictionary<int, int>();\n d.Add(1,97);\n d.Add(2,89);\n d.Add(3,77);\n d.Add(4,88);\n\n // Dictionary elements\n Console.WriteLine(\"Dictionary elements: \"+d.Count);\n }\n}"
},
{
"code": null,
"e": 1834,
"s": 1811,
"text": "Dictionary elements: 4"
}
] |
What is a parameterized constructor in C# programs? | In a constructor you can also add parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation.
The following is an example −
// class
class Demo
Parameterized constructor with a prarameter rank −
public Demo(int rank) {
Console.WriteLine("RANK = {0}", rank);
}
Here is the complete example displaying how to work with parameterized constructor in C# −
Live Demo
using System;
namespace Demo {
class Line {
private double length; // Length of a line
public Line(double len) { //Parameterized constructor
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line(10.0);
Console.WriteLine("Length of line : {0}", line.getLength());
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}
Object is being created, length = 10
Length of line : 10
Length of line : 6 | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "In a constructor you can also add parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation."
},
{
"code": null,
"e": 1286,
"s": 1256,
"text": "The following is an example −"
},
{
"code": null,
"e": 1306,
"s": 1286,
"text": "// class\nclass Demo"
},
{
"code": null,
"e": 1357,
"s": 1306,
"text": "Parameterized constructor with a prarameter rank −"
},
{
"code": null,
"e": 1422,
"s": 1357,
"text": "public Demo(int rank) {\nConsole.WriteLine(\"RANK = {0}\", rank);\n}"
},
{
"code": null,
"e": 1513,
"s": 1422,
"text": "Here is the complete example displaying how to work with parameterized constructor in C# −"
},
{
"code": null,
"e": 1524,
"s": 1513,
"text": " Live Demo"
},
{
"code": null,
"e": 2255,
"s": 1524,
"text": "using System;\n\nnamespace Demo {\n class Line {\n private double length; // Length of a line\n \n public Line(double len) { //Parameterized constructor\n Console.WriteLine(\"Object is being created, length = {0}\", len);\n length = len;\n }\n\n public void setLength( double len ) {\n length = len;\n }\n\n public double getLength() {\n return length;\n }\n\n static void Main(string[] args) {\n Line line = new Line(10.0);\n Console.WriteLine(\"Length of line : {0}\", line.getLength());\n\n // set line length\n line.setLength(6.0);\n Console.WriteLine(\"Length of line : {0}\", line.getLength());\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2331,
"s": 2255,
"text": "Object is being created, length = 10\nLength of line : 10\nLength of line : 6"
}
] |
Pre-Processing in OCR!!!. A basic explanation of the most widely... | by Susmith Reddy | Towards Data Science | Welcome to part II, in the series about working of an OCR system. In the previous post, we briefly discussed the different phases of an OCR system.
Among all the phases of OCR, Preprocessing and Segmentation are the most important phases, as the accuracy of the OCR system highly depends upon how well Preprocessing and Segmentation are performed. So, here we are going to learn some of the most basic and commonly used preprocessing techniques on an image.
The main objective of the Preprocessing phase is To make as easy as possible for the OCR system to distinguish a character/word from the background.
Some of the most basic and important Preprocessing techniques are:-
1) Binarization2) Skew Correction3) Noise Removal4) Thinning and Skeletonization
Before discussing these techniques, let’s understand how an OCR system comprehends an image. For an OCR system, an Image is a multidimensional array (2D array if the image is grayscale (or) binary, 3D array if the image is coloured). Each cell in the matrix is called a pixel and it can store 8-bit integer which means the pixel range is 0–255.
Let’s go through each preprocessing technique mentioned above one-by-one
Binarization: In layman’s terms Binarization means converting a coloured image into an image which consists of only black and white pixels (Black pixel value=0 and White pixel value=255). As a basic rule, this can be done by fixing a threshold (normally threshold=127, as it is exactly half of the pixel range 0–255). If the pixel value is greater than the threshold, it is considered as a white pixel, else considered as a black pixel.
Binarization: In layman’s terms Binarization means converting a coloured image into an image which consists of only black and white pixels (Black pixel value=0 and White pixel value=255). As a basic rule, this can be done by fixing a threshold (normally threshold=127, as it is exactly half of the pixel range 0–255). If the pixel value is greater than the threshold, it is considered as a white pixel, else considered as a black pixel.
But this strategy may not always give us desired results. In the cases where lighting conditions are not uniform in the image, this method fails.
So, the crucial part of binarization is determining the threshold. This can be done by using various techniques.
→ Local Maxima and Minima Method :
C(i,j) is the threshold for a defined size of locality in the image (like a 10x10 size part). Using this strategy we’ll have different threshold values for different parts of the image, depending on the surrounding lighting conditions but the transition is not that smooth.
→ Otsu’s Binarization: This method gives a threshold for the whole image considering the various characteristics of the whole image (like lighting conditions, contrast, sharpness etc) and that threshold is used for Binarizing image.This can be accomplished using OpenCV python in the following way:
ret, imgf = cv2.threshold(img, 0, 255,cv2.THRESH_BINARY,cv2.THRESH_OTSU) #imgf contains Binary image
-> Adaptive Thresholding: This method gives a threshold for a small part of the image depending on the characteristics of its locality and neighbours i.e there is no single fixed threshold for the whole image but every small part of the image has a different threshold depending upon the locality and also gives smooth transition.
imgf = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) #imgf contains Binary image
2. Skew Correction: While scanning a document, it might be slightly skewed (image aligned at a certain angle with horizontal) sometimes. While extracting the information from the scanned image, detecting & correcting the skew is crucial.Several techniques are used for skew correction.
→ Projection profile method→ Hough transformation method→ Topline method→ Scanline method
However, the projection profile method is the simplest, easiest and most widely used way to determine skew in documents.
In this method, First, we’ll take the binary image, then
project it horizontally (taking the sum of pixels along rows of the image matrix) to get a histogram of pixels along the height of the image i.e count of foreground pixels for every row.
Now the image is rotated at various angles (at a small interval of angles called Delta) and the difference between the peaks will be calculated (Variance can also be used as one of the metrics). The angle at which the maximum difference between peaks (or Variance) is found, that corresponding angle will be the Skew angle for the image.
After finding the Skew angle, we can correct the skewness by rotating the image through an angle equal to the skew angle in the opposite direction of skew.
import sysimport matplotlib.pyplot as pltimport numpy as npfrom PIL import Image as imfrom scipy.ndimage import interpolation as interinput_file = sys.argv[1]img = im.open(input_file)# convert to binarywd, ht = img.sizepix = np.array(img.convert('1').getdata(), np.uint8)bin_img = 1 - (pix.reshape((ht, wd)) / 255.0)plt.imshow(bin_img, cmap='gray')plt.savefig('binary.png')def find_score(arr, angle): data = inter.rotate(arr, angle, reshape=False, order=0) hist = np.sum(data, axis=1) score = np.sum((hist[1:] - hist[:-1]) ** 2) return hist, scoredelta = 1limit = 5angles = np.arange(-limit, limit+delta, delta)scores = []for angle in angles: hist, score = find_score(bin_img, angle) scores.append(score)best_score = max(scores)best_angle = angles[scores.index(best_score)]print('Best angle: {}'.formate(best_angle))# correct skewdata = inter.rotate(bin_img, best_angle, reshape=False, order=0)img = im.fromarray((255 * data).astype("uint8")).convert("RGB")img.save('skew_corrected.png')
3. Noise Removal: The main objective of the Noise removal stage is to smoothen the image by removing small dots/patches which have high intensity than the rest of the image. Noise removal can be performed for both Coloured and Binary images.One way of performing Noise removal by using OpenCV fastNlMeansDenoisingColored function.
import numpy as np import cv2 from matplotlib import pyplot as plt # Reading image from folder where it is stored img = cv2.imread('bear.png') # denoising of image saving it into dst image dst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 15) # Plotting of source and destination image plt.subplot(121), plt.imshow(img) plt.subplot(122), plt.imshow(dst) plt.show()
More about Noise removal & Image smoothening techniques can be found in this wonderful article
4. Thinning and Skeletonization: This is an optional preprocessing task which depends on the context in which the OCR is being used. → If we are using the OCR system for the printed text, No need of performing this task because the printed text always has a uniform stroke width. → If we are using the OCR system for handwritten text, this task has to be performed since different writers have a different style of writing and hence different stroke width. So to make the width of strokes uniform, we have to perform Thinning and Skeletonization.
This can be performed using OpenCV in the following way
import cv2import numpy as npimg = cv2.imread('j.png',0)kernel = np.ones((5,5),np.uint8)erosion = cv2.erode(img,kernel,iterations = 1)
In the above code, Thinning of the image depends upon kernel size and no.of iterations.
In this article, we have seen some of the basic and most widely used Preprocessing techniques which gives us a basic idea of what’s happening inside the OCR system. An example of preprocessing workflow can be seen in the below image.
I hope you got an essence of how Preprocessing is performed in the OCR.
In part-III, we’ll see the Segmentation techniques used by the OCR system.
Happy Learning !!!!
Any doubts, Suggestions & Corrections are Welcome. 😃
[1] Shafii, M., Sid-Ahmed, M. Skew detection and correction based on an axes-parallel bounding box. IJDAR 18, 59–71 (2015). https://doi.org/10.1007/s10032-014-0230-y
[2] Jyotsna, S. Chauhan, E. Sharma and A. Doegar, “Binarization techniques for degraded document images — A review,” 2016 5th International Conference on Reliability, Infocom Technologies and Optimization (Trends and Future Directions) (ICRITO), Noida, 2016, pp. 163–166, doi: 10.1109/ICRITO.2016.7784945.
[3] A. Papandreou and B. Gatos, “A Novel Skew Detection Technique Based on Vertical Projections,” 2011 International Conference on Document Analysis and Recognition, Beijing, 2011, pp. 384–388, doi: 10.1109/ICDAR.2011.85.
[4] K. Lin, T. H. Li, S. Liu and G. Li, “Real Photographs Denoising With Noise Domain Adaptation and Attentive Generative Adversarial Network,” 2019 IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW), Long Beach, CA, USA, 2019, pp. 1717–1721, doi: 10.1109/CVPRW.2019.00221.
[5] Choudhary, Amit & Rishi, Rahul & Savita, Ahlawat. (2013). A New Character Segmentation Approach for Off-Line Cursive Handwritten Words. Procedia Computer Science. 17. 88–95. 10.1016/j.procs.2013.05.013. | [
{
"code": null,
"e": 320,
"s": 172,
"text": "Welcome to part II, in the series about working of an OCR system. In the previous post, we briefly discussed the different phases of an OCR system."
},
{
"code": null,
"e": 630,
"s": 320,
"text": "Among all the phases of OCR, Preprocessing and Segmentation are the most important phases, as the accuracy of the OCR system highly depends upon how well Preprocessing and Segmentation are performed. So, here we are going to learn some of the most basic and commonly used preprocessing techniques on an image."
},
{
"code": null,
"e": 779,
"s": 630,
"text": "The main objective of the Preprocessing phase is To make as easy as possible for the OCR system to distinguish a character/word from the background."
},
{
"code": null,
"e": 847,
"s": 779,
"text": "Some of the most basic and important Preprocessing techniques are:-"
},
{
"code": null,
"e": 928,
"s": 847,
"text": "1) Binarization2) Skew Correction3) Noise Removal4) Thinning and Skeletonization"
},
{
"code": null,
"e": 1273,
"s": 928,
"text": "Before discussing these techniques, let’s understand how an OCR system comprehends an image. For an OCR system, an Image is a multidimensional array (2D array if the image is grayscale (or) binary, 3D array if the image is coloured). Each cell in the matrix is called a pixel and it can store 8-bit integer which means the pixel range is 0–255."
},
{
"code": null,
"e": 1346,
"s": 1273,
"text": "Let’s go through each preprocessing technique mentioned above one-by-one"
},
{
"code": null,
"e": 1783,
"s": 1346,
"text": "Binarization: In layman’s terms Binarization means converting a coloured image into an image which consists of only black and white pixels (Black pixel value=0 and White pixel value=255). As a basic rule, this can be done by fixing a threshold (normally threshold=127, as it is exactly half of the pixel range 0–255). If the pixel value is greater than the threshold, it is considered as a white pixel, else considered as a black pixel."
},
{
"code": null,
"e": 2220,
"s": 1783,
"text": "Binarization: In layman’s terms Binarization means converting a coloured image into an image which consists of only black and white pixels (Black pixel value=0 and White pixel value=255). As a basic rule, this can be done by fixing a threshold (normally threshold=127, as it is exactly half of the pixel range 0–255). If the pixel value is greater than the threshold, it is considered as a white pixel, else considered as a black pixel."
},
{
"code": null,
"e": 2366,
"s": 2220,
"text": "But this strategy may not always give us desired results. In the cases where lighting conditions are not uniform in the image, this method fails."
},
{
"code": null,
"e": 2479,
"s": 2366,
"text": "So, the crucial part of binarization is determining the threshold. This can be done by using various techniques."
},
{
"code": null,
"e": 2514,
"s": 2479,
"text": "→ Local Maxima and Minima Method :"
},
{
"code": null,
"e": 2788,
"s": 2514,
"text": "C(i,j) is the threshold for a defined size of locality in the image (like a 10x10 size part). Using this strategy we’ll have different threshold values for different parts of the image, depending on the surrounding lighting conditions but the transition is not that smooth."
},
{
"code": null,
"e": 3087,
"s": 2788,
"text": "→ Otsu’s Binarization: This method gives a threshold for the whole image considering the various characteristics of the whole image (like lighting conditions, contrast, sharpness etc) and that threshold is used for Binarizing image.This can be accomplished using OpenCV python in the following way:"
},
{
"code": null,
"e": 3188,
"s": 3087,
"text": "ret, imgf = cv2.threshold(img, 0, 255,cv2.THRESH_BINARY,cv2.THRESH_OTSU) #imgf contains Binary image"
},
{
"code": null,
"e": 3519,
"s": 3188,
"text": "-> Adaptive Thresholding: This method gives a threshold for a small part of the image depending on the characteristics of its locality and neighbours i.e there is no single fixed threshold for the whole image but every small part of the image has a different threshold depending upon the locality and also gives smooth transition."
},
{
"code": null,
"e": 3639,
"s": 3519,
"text": "imgf = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) #imgf contains Binary image"
},
{
"code": null,
"e": 3925,
"s": 3639,
"text": "2. Skew Correction: While scanning a document, it might be slightly skewed (image aligned at a certain angle with horizontal) sometimes. While extracting the information from the scanned image, detecting & correcting the skew is crucial.Several techniques are used for skew correction."
},
{
"code": null,
"e": 4015,
"s": 3925,
"text": "→ Projection profile method→ Hough transformation method→ Topline method→ Scanline method"
},
{
"code": null,
"e": 4136,
"s": 4015,
"text": "However, the projection profile method is the simplest, easiest and most widely used way to determine skew in documents."
},
{
"code": null,
"e": 4193,
"s": 4136,
"text": "In this method, First, we’ll take the binary image, then"
},
{
"code": null,
"e": 4380,
"s": 4193,
"text": "project it horizontally (taking the sum of pixels along rows of the image matrix) to get a histogram of pixels along the height of the image i.e count of foreground pixels for every row."
},
{
"code": null,
"e": 4718,
"s": 4380,
"text": "Now the image is rotated at various angles (at a small interval of angles called Delta) and the difference between the peaks will be calculated (Variance can also be used as one of the metrics). The angle at which the maximum difference between peaks (or Variance) is found, that corresponding angle will be the Skew angle for the image."
},
{
"code": null,
"e": 4874,
"s": 4718,
"text": "After finding the Skew angle, we can correct the skewness by rotating the image through an angle equal to the skew angle in the opposite direction of skew."
},
{
"code": null,
"e": 5880,
"s": 4874,
"text": "import sysimport matplotlib.pyplot as pltimport numpy as npfrom PIL import Image as imfrom scipy.ndimage import interpolation as interinput_file = sys.argv[1]img = im.open(input_file)# convert to binarywd, ht = img.sizepix = np.array(img.convert('1').getdata(), np.uint8)bin_img = 1 - (pix.reshape((ht, wd)) / 255.0)plt.imshow(bin_img, cmap='gray')plt.savefig('binary.png')def find_score(arr, angle): data = inter.rotate(arr, angle, reshape=False, order=0) hist = np.sum(data, axis=1) score = np.sum((hist[1:] - hist[:-1]) ** 2) return hist, scoredelta = 1limit = 5angles = np.arange(-limit, limit+delta, delta)scores = []for angle in angles: hist, score = find_score(bin_img, angle) scores.append(score)best_score = max(scores)best_angle = angles[scores.index(best_score)]print('Best angle: {}'.formate(best_angle))# correct skewdata = inter.rotate(bin_img, best_angle, reshape=False, order=0)img = im.fromarray((255 * data).astype(\"uint8\")).convert(\"RGB\")img.save('skew_corrected.png')"
},
{
"code": null,
"e": 6211,
"s": 5880,
"text": "3. Noise Removal: The main objective of the Noise removal stage is to smoothen the image by removing small dots/patches which have high intensity than the rest of the image. Noise removal can be performed for both Coloured and Binary images.One way of performing Noise removal by using OpenCV fastNlMeansDenoisingColored function."
},
{
"code": null,
"e": 6586,
"s": 6211,
"text": "import numpy as np import cv2 from matplotlib import pyplot as plt # Reading image from folder where it is stored img = cv2.imread('bear.png') # denoising of image saving it into dst image dst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 15) # Plotting of source and destination image plt.subplot(121), plt.imshow(img) plt.subplot(122), plt.imshow(dst) plt.show()"
},
{
"code": null,
"e": 6681,
"s": 6586,
"text": "More about Noise removal & Image smoothening techniques can be found in this wonderful article"
},
{
"code": null,
"e": 7230,
"s": 6681,
"text": "4. Thinning and Skeletonization: This is an optional preprocessing task which depends on the context in which the OCR is being used. → If we are using the OCR system for the printed text, No need of performing this task because the printed text always has a uniform stroke width. → If we are using the OCR system for handwritten text, this task has to be performed since different writers have a different style of writing and hence different stroke width. So to make the width of strokes uniform, we have to perform Thinning and Skeletonization."
},
{
"code": null,
"e": 7286,
"s": 7230,
"text": "This can be performed using OpenCV in the following way"
},
{
"code": null,
"e": 7420,
"s": 7286,
"text": "import cv2import numpy as npimg = cv2.imread('j.png',0)kernel = np.ones((5,5),np.uint8)erosion = cv2.erode(img,kernel,iterations = 1)"
},
{
"code": null,
"e": 7508,
"s": 7420,
"text": "In the above code, Thinning of the image depends upon kernel size and no.of iterations."
},
{
"code": null,
"e": 7742,
"s": 7508,
"text": "In this article, we have seen some of the basic and most widely used Preprocessing techniques which gives us a basic idea of what’s happening inside the OCR system. An example of preprocessing workflow can be seen in the below image."
},
{
"code": null,
"e": 7814,
"s": 7742,
"text": "I hope you got an essence of how Preprocessing is performed in the OCR."
},
{
"code": null,
"e": 7889,
"s": 7814,
"text": "In part-III, we’ll see the Segmentation techniques used by the OCR system."
},
{
"code": null,
"e": 7909,
"s": 7889,
"text": "Happy Learning !!!!"
},
{
"code": null,
"e": 7962,
"s": 7909,
"text": "Any doubts, Suggestions & Corrections are Welcome. 😃"
},
{
"code": null,
"e": 8128,
"s": 7962,
"text": "[1] Shafii, M., Sid-Ahmed, M. Skew detection and correction based on an axes-parallel bounding box. IJDAR 18, 59–71 (2015). https://doi.org/10.1007/s10032-014-0230-y"
},
{
"code": null,
"e": 8434,
"s": 8128,
"text": "[2] Jyotsna, S. Chauhan, E. Sharma and A. Doegar, “Binarization techniques for degraded document images — A review,” 2016 5th International Conference on Reliability, Infocom Technologies and Optimization (Trends and Future Directions) (ICRITO), Noida, 2016, pp. 163–166, doi: 10.1109/ICRITO.2016.7784945."
},
{
"code": null,
"e": 8656,
"s": 8434,
"text": "[3] A. Papandreou and B. Gatos, “A Novel Skew Detection Technique Based on Vertical Projections,” 2011 International Conference on Document Analysis and Recognition, Beijing, 2011, pp. 384–388, doi: 10.1109/ICDAR.2011.85."
},
{
"code": null,
"e": 8960,
"s": 8656,
"text": "[4] K. Lin, T. H. Li, S. Liu and G. Li, “Real Photographs Denoising With Noise Domain Adaptation and Attentive Generative Adversarial Network,” 2019 IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW), Long Beach, CA, USA, 2019, pp. 1717–1721, doi: 10.1109/CVPRW.2019.00221."
}
] |
Mensuration 3D- Hollow sphere | 12 Jun, 2020
In this article we shall calculate the volume, Curved surface area (CSA) and Total surface area of a hollow sphere or a spherical shell. Below shown is a diagram of a hollow sphere.
As we can see in the figure, the outer radius of hollow sphere is ‘R’ and the inner radius is ‘r’.
Volume of hollow sphere :Volume of a 3D figure is defined as the capacity of the figure or the amount of the content it can hold. The volume of hollow sphere is equal to the volume of inner sphere subtracted from the volume of the outer sphere. It can be calculated as –
We know that volume of sphere,
= 4/3 πR3
Thus volume of hollow sphere= volume of outer sphere- volume of inner sphere
= 4/3 πR3-4/3 πr3
= 4/3 π(R3-r3)
Curved surface area (CSA) :The Curved surface area of hollow sphere is the area of the paper that can completely cover the surface of the hollow sphere. It is equal to the CSA of inner sphere subtracted from the CSA of outer sphere.
CSA of hollow sphere,
= CSA of outer sphere - CSA of inner sphere
= 4 πR2 - 4 πr2
= 4 π(R2-r2)
Total surface area of hollow sphere :The total surface area of a hollow sphere is equal to the CSA of hollow sphere as a hollow sphere has only one surface that constitutes it.Thus CSA=TSA for a hollow sphere
Example-1:Calculate the volume and TSA of hollow sphere with outer and inner radii 5cm and 3cm respectively.
Explanation :
Given outer radius = R = 5cm
Inner radius = r = 3cm
Volume = 4/3 π(R3-r3)
= 4/3*3.14*(125-27)
= 410.29 cm3
TSA = 4 π(R2-r2) = 4*3.14*(25-9)
= 200.96 cm2
Example-2:Water is being poured into hollow sphere of outer radius 10 cm and inner radius 5 cm at the rate of 10 cm3/s. Calculate the time required to fill the hollow sphere.
Explanation :
Outer radius = R = 10 cm
Inner radius = r = 5 cm
Volume of hollow sphere = 4/3*3.14*(1000-125)
= 3500 cm3
Rate at which water is being poured = 10 cm3/s
Time required = Volume of sphere/Rate of pouring water
= 3500/10 = 350 s
Aptitude
placement
Engineering Mathematics
Placements
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Propositional Logic and Predicate Logic
Activation Functions
Logic Notations in LaTeX
Modular Arithmetic
Mathematics | Introduction of Set theory
SDE SHEET - A Complete Guide for SDE Preparation
Must Do Coding Questions Company-wise
Numbers
TCS Placement Paper | MCQ 1
Top 20 Puzzles Commonly Asked During SDE Interviews | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "In this article we shall calculate the volume, Curved surface area (CSA) and Total surface area of a hollow sphere or a spherical shell. Below shown is a diagram of a hollow sphere."
},
{
"code": null,
"e": 309,
"s": 210,
"text": "As we can see in the figure, the outer radius of hollow sphere is ‘R’ and the inner radius is ‘r’."
},
{
"code": null,
"e": 580,
"s": 309,
"text": "Volume of hollow sphere :Volume of a 3D figure is defined as the capacity of the figure or the amount of the content it can hold. The volume of hollow sphere is equal to the volume of inner sphere subtracted from the volume of the outer sphere. It can be calculated as –"
},
{
"code": null,
"e": 611,
"s": 580,
"text": "We know that volume of sphere,"
},
{
"code": null,
"e": 622,
"s": 611,
"text": "= 4/3 πR3 "
},
{
"code": null,
"e": 699,
"s": 622,
"text": "Thus volume of hollow sphere= volume of outer sphere- volume of inner sphere"
},
{
"code": null,
"e": 733,
"s": 699,
"text": "= 4/3 πR3-4/3 πr3\n= 4/3 π(R3-r3) "
},
{
"code": null,
"e": 966,
"s": 733,
"text": "Curved surface area (CSA) :The Curved surface area of hollow sphere is the area of the paper that can completely cover the surface of the hollow sphere. It is equal to the CSA of inner sphere subtracted from the CSA of outer sphere."
},
{
"code": null,
"e": 1062,
"s": 966,
"text": "CSA of hollow sphere,\n= CSA of outer sphere - CSA of inner sphere\n= 4 πR2 - 4 πr2\n= 4 π(R2-r2) "
},
{
"code": null,
"e": 1271,
"s": 1062,
"text": "Total surface area of hollow sphere :The total surface area of a hollow sphere is equal to the CSA of hollow sphere as a hollow sphere has only one surface that constitutes it.Thus CSA=TSA for a hollow sphere"
},
{
"code": null,
"e": 1380,
"s": 1271,
"text": "Example-1:Calculate the volume and TSA of hollow sphere with outer and inner radii 5cm and 3cm respectively."
},
{
"code": null,
"e": 1394,
"s": 1380,
"text": "Explanation :"
},
{
"code": null,
"e": 1550,
"s": 1394,
"text": "Given outer radius = R = 5cm\nInner radius = r = 3cm\n\nVolume = 4/3 π(R3-r3)\n= 4/3*3.14*(125-27)\n= 410.29 cm3\n\nTSA = 4 π(R2-r2) = 4*3.14*(25-9)\n= 200.96 cm2 "
},
{
"code": null,
"e": 1725,
"s": 1550,
"text": "Example-2:Water is being poured into hollow sphere of outer radius 10 cm and inner radius 5 cm at the rate of 10 cm3/s. Calculate the time required to fill the hollow sphere."
},
{
"code": null,
"e": 1739,
"s": 1725,
"text": "Explanation :"
},
{
"code": null,
"e": 1968,
"s": 1739,
"text": "Outer radius = R = 10 cm\nInner radius = r = 5 cm\n\nVolume of hollow sphere = 4/3*3.14*(1000-125)\n= 3500 cm3\n\nRate at which water is being poured = 10 cm3/s\nTime required = Volume of sphere/Rate of pouring water\n= 3500/10 = 350 s "
},
{
"code": null,
"e": 1977,
"s": 1968,
"text": "Aptitude"
},
{
"code": null,
"e": 1987,
"s": 1977,
"text": "placement"
},
{
"code": null,
"e": 2011,
"s": 1987,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 2022,
"s": 2011,
"text": "Placements"
},
{
"code": null,
"e": 2120,
"s": 2022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2179,
"s": 2120,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 2200,
"s": 2179,
"text": "Activation Functions"
},
{
"code": null,
"e": 2225,
"s": 2200,
"text": "Logic Notations in LaTeX"
},
{
"code": null,
"e": 2244,
"s": 2225,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 2285,
"s": 2244,
"text": "Mathematics | Introduction of Set theory"
},
{
"code": null,
"e": 2334,
"s": 2285,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 2372,
"s": 2334,
"text": "Must Do Coding Questions Company-wise"
},
{
"code": null,
"e": 2380,
"s": 2372,
"text": "Numbers"
},
{
"code": null,
"e": 2408,
"s": 2380,
"text": "TCS Placement Paper | MCQ 1"
}
] |
Python | Sort given list of strings by part of string | 11 May, 2020
Given a list of string, the task is to sort the list by part of the string which is separated by some character. In this scenario, we are considering the string to be separated by space, which means it has to be sorted by second part of each string.
Given below are a few methods to solve the given task.
Method #1: Using sort
# Python code to demonstrate to sort list # containing string by part of string # Initialising listini_list = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"] # printing initial listprint ("initial list", str(ini_list)) # code to sort listini_list.sort(key = lambda x: x.split()[1]) # printing resultprint ("result", str(ini_list))
initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
result ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
Method #2: Using sorted
# Python code to demonstrate to sort list # containing string by part of string # Initialising listini_list = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"] # printing initial listprint ("initial list", str(ini_list)) # code to sort listres = sorted(ini_list, key = lambda x: x.split()[1]) # printing resultprint ("result", res)
initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
result ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
Python list-programs
Python string-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 303,
"s": 53,
"text": "Given a list of string, the task is to sort the list by part of the string which is separated by some character. In this scenario, we are considering the string to be separated by space, which means it has to be sorted by second part of each string."
},
{
"code": null,
"e": 358,
"s": 303,
"text": "Given below are a few methods to solve the given task."
},
{
"code": null,
"e": 380,
"s": 358,
"text": "Method #1: Using sort"
},
{
"code": "# Python code to demonstrate to sort list # containing string by part of string # Initialising listini_list = [\"GeeksForGeeks abc\", \"manjeet xab\", \"akshat bac\"] # printing initial listprint (\"initial list\", str(ini_list)) # code to sort listini_list.sort(key = lambda x: x.split()[1]) # printing resultprint (\"result\", str(ini_list))",
"e": 722,
"s": 380,
"text": null
},
{
"code": null,
"e": 845,
"s": 722,
"text": "initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']\nresult ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']\n"
},
{
"code": null,
"e": 870,
"s": 845,
"text": " Method #2: Using sorted"
},
{
"code": "# Python code to demonstrate to sort list # containing string by part of string # Initialising listini_list = [\"GeeksForGeeks abc\", \"manjeet xab\", \"akshat bac\"] # printing initial listprint (\"initial list\", str(ini_list)) # code to sort listres = sorted(ini_list, key = lambda x: x.split()[1]) # printing resultprint (\"result\", res)",
"e": 1211,
"s": 870,
"text": null
},
{
"code": null,
"e": 1334,
"s": 1211,
"text": "initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']\nresult ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']\n"
},
{
"code": null,
"e": 1355,
"s": 1334,
"text": "Python list-programs"
},
{
"code": null,
"e": 1378,
"s": 1355,
"text": "Python string-programs"
},
{
"code": null,
"e": 1390,
"s": 1378,
"text": "Python-sort"
},
{
"code": null,
"e": 1397,
"s": 1390,
"text": "Python"
},
{
"code": null,
"e": 1413,
"s": 1397,
"text": "Python Programs"
},
{
"code": null,
"e": 1511,
"s": 1413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1553,
"s": 1511,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1575,
"s": 1553,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1610,
"s": 1575,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1636,
"s": 1610,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1668,
"s": 1636,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1711,
"s": 1668,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1733,
"s": 1711,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1772,
"s": 1733,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1810,
"s": 1772,
"text": "Python | Convert a list to dictionary"
}
] |
Python Program for Detect Cycle in a Directed Graph | In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a directed graph, we need to check whether the graph contains a cycle or not. The output should be true if the given graph contains at least one cycle, otherwise false.
Now let’s observe the solution in the implementation below −
Live Demo
# collections module
from collections import defaultdict
# class for creation of graphs
class Graph():
# constructor
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def isCyclicUtil(self, v, visited, recStack):
# Marking current node visited and addition to recursion stack
visited[v] = True
recStack[v] = True
# if any neighbour is visited and in recStack then graph is cyclic in nature
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.isCyclicUtil(neighbour, visited, recStack) == True:
return True
elif recStack[neighbour] == True:
return True
# pop the node after the end of recursion
recStack[v] = False
return False
# Returns true if graph is cyclic
def isCyclic(self):
visited = [False] * self.V
recStack = [False] * self.V
for node in range(self.V):
if visited[node] == False:
if self.isCyclicUtil(node, visited, recStack) == True:
return True
return False
g = Graph(4)
g.addEdge(0, 3)
g.addEdge(0, 2)
g.addEdge(3, 2)
g.addEdge(2, 0)
g.addEdge(1, 3)
g.addEdge(2, 1)
if g.isCyclic() == 1:
print ("Graph is cyclic in nature")
else:
print ("Graph is non-cyclic in nature")
Graph is cyclic in nature
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program to Detect Cycle in a Directed Graph | [
{
"code": null,
"e": 1275,
"s": 1187,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1477,
"s": 1275,
"text": "Problem statement − We are given a directed graph, we need to check whether the graph contains a cycle or not. The output should be true if the given graph contains at least one cycle, otherwise false."
},
{
"code": null,
"e": 1538,
"s": 1477,
"text": "Now let’s observe the solution in the implementation below −"
},
{
"code": null,
"e": 1549,
"s": 1538,
"text": " Live Demo"
},
{
"code": null,
"e": 2937,
"s": 1549,
"text": "# collections module\nfrom collections import defaultdict\n# class for creation of graphs\nclass Graph():\n # constructor\n def __init__(self, vertices):\n self.graph = defaultdict(list)\n self.V = vertices\n def addEdge(self, u, v):\n self.graph[u].append(v)\n def isCyclicUtil(self, v, visited, recStack):\n # Marking current node visited and addition to recursion stack\n visited[v] = True\n recStack[v] = True\n # if any neighbour is visited and in recStack then graph is cyclic in nature\n for neighbour in self.graph[v]:\n if visited[neighbour] == False:\n if self.isCyclicUtil(neighbour, visited, recStack) == True:\n return True\n elif recStack[neighbour] == True:\n return True\n # pop the node after the end of recursion\n recStack[v] = False\n return False\n # Returns true if graph is cyclic\n def isCyclic(self):\n visited = [False] * self.V\n recStack = [False] * self.V\n for node in range(self.V):\n if visited[node] == False:\n if self.isCyclicUtil(node, visited, recStack) == True:\n return True\n return False\ng = Graph(4)\ng.addEdge(0, 3)\ng.addEdge(0, 2)\ng.addEdge(3, 2)\ng.addEdge(2, 0)\ng.addEdge(1, 3)\ng.addEdge(2, 1)\nif g.isCyclic() == 1:\n print (\"Graph is cyclic in nature\")\nelse:\n print (\"Graph is non-cyclic in nature\")"
},
{
"code": null,
"e": 2963,
"s": 2937,
"text": "Graph is cyclic in nature"
},
{
"code": null,
"e": 3064,
"s": 2963,
"text": "All the variables are declared in the local scope and their references are seen in the figure above."
},
{
"code": null,
"e": 3172,
"s": 3064,
"text": "In this article, we have learned about how we can make a Python Program to Detect Cycle in a Directed Graph"
}
] |
Hashtable elements() Method in Java | 28 Jun, 2018
The java.util.Hashtable.elements() method of Hashtable class in Java is used to get the enumeration of the values present in the hashtable.
Syntax:
Enumeration enu = Hash_table.elements()
Parameters: The method does not take any parameters.
Return value: The method returns an enumeration of the values of the Hashtable.
Below programs are used to illustrate the working of the java.util.Hashtable.elements() method:Program 1:
// Java code to illustrate the elements() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting elements into the table hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Displaying the Hashtable System.out.println("The Table is: " + hash_table); // Creating an empty enumeration to store Enumeration enu = hash_table.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}
The Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The enumeration of values are:
Geeks
Geeks
You
4
Welcomes
Program 2 :
// Java code to illustrate the elements() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting elements into the table hash_table.put("Geeks", 10); hash_table.put("4", 15); hash_table.put("Geeks", 20); hash_table.put("Welcomes", 25); hash_table.put("You", 30); // Displaying the Hashtable System.out.println("The Table is: " + hash_table); // Creating an empty enumeration to store Enumeration enu = hash_table.elements(); System.out.println("The enumeration of values are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}
The Table is: {You=30, Welcomes=25, 4=15, Geeks=20}
The enumeration of values are:
30
25
15
20
Java - util package
Java-Collections
Java-HashTable
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2018"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "The java.util.Hashtable.elements() method of Hashtable class in Java is used to get the enumeration of the values present in the hashtable."
},
{
"code": null,
"e": 176,
"s": 168,
"text": "Syntax:"
},
{
"code": null,
"e": 216,
"s": 176,
"text": "Enumeration enu = Hash_table.elements()"
},
{
"code": null,
"e": 269,
"s": 216,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 349,
"s": 269,
"text": "Return value: The method returns an enumeration of the values of the Hashtable."
},
{
"code": null,
"e": 455,
"s": 349,
"text": "Below programs are used to illustrate the working of the java.util.Hashtable.elements() method:Program 1:"
},
{
"code": "// Java code to illustrate the elements() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting elements into the table hash_table.put(10, \"Geeks\"); hash_table.put(15, \"4\"); hash_table.put(20, \"Geeks\"); hash_table.put(25, \"Welcomes\"); hash_table.put(30, \"You\"); // Displaying the Hashtable System.out.println(\"The Table is: \" + hash_table); // Creating an empty enumeration to store Enumeration enu = hash_table.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}",
"e": 1366,
"s": 455,
"text": null
},
{
"code": null,
"e": 1487,
"s": 1366,
"text": "The Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nThe enumeration of values are:\nGeeks\nGeeks\nYou\n4\nWelcomes\n"
},
{
"code": null,
"e": 1499,
"s": 1487,
"text": "Program 2 :"
},
{
"code": "// Java code to illustrate the elements() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting elements into the table hash_table.put(\"Geeks\", 10); hash_table.put(\"4\", 15); hash_table.put(\"Geeks\", 20); hash_table.put(\"Welcomes\", 25); hash_table.put(\"You\", 30); // Displaying the Hashtable System.out.println(\"The Table is: \" + hash_table); // Creating an empty enumeration to store Enumeration enu = hash_table.elements(); System.out.println(\"The enumeration of values are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}",
"e": 2409,
"s": 1499,
"text": null
},
{
"code": null,
"e": 2505,
"s": 2409,
"text": "The Table is: {You=30, Welcomes=25, 4=15, Geeks=20}\nThe enumeration of values are:\n30\n25\n15\n20\n"
},
{
"code": null,
"e": 2525,
"s": 2505,
"text": "Java - util package"
},
{
"code": null,
"e": 2542,
"s": 2525,
"text": "Java-Collections"
},
{
"code": null,
"e": 2557,
"s": 2542,
"text": "Java-HashTable"
},
{
"code": null,
"e": 2562,
"s": 2557,
"text": "Java"
},
{
"code": null,
"e": 2567,
"s": 2562,
"text": "Java"
},
{
"code": null,
"e": 2584,
"s": 2567,
"text": "Java-Collections"
},
{
"code": null,
"e": 2682,
"s": 2584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2697,
"s": 2682,
"text": "Arrays in Java"
},
{
"code": null,
"e": 2741,
"s": 2697,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 2777,
"s": 2741,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 2828,
"s": 2777,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2853,
"s": 2828,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 2875,
"s": 2853,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 2906,
"s": 2875,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2925,
"s": 2906,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2955,
"s": 2925,
"text": "HashMap in Java with Examples"
}
] |
Difference between var and let in JavaScript | 04 Jul, 2022
var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. It can be said that a variable declared with var is defined throughout the program as compared to let. An example will clarify the difference even better
Example of var:
Input:
console.log(x);
var x=5;
console.log(x);
Output:
undefined
5
Example of let:
Input:
console.log(x);
let x=5;
console.log(x);
Output:
Error
Let’s see code in JavaScript: Code #1:
HTML
<html> <body> <script> // calling x after definition var x = 5; document.write(x, "\n"); // calling y after definition let y = 10; document.write(y, "\n"); // calling var z before definition will return undefined document.write(z, "\n"); var z = 2; // calling let a before definition will give error document.write(a); let a = 3; </script></body> </html>
Code #2: In the following code, clicking start will call a function that changes the color of the two headings every 0.5sec. The color of first heading is stored in a var and the second one is declared by using let. Both of them are then accessed outside the function block. Var will work but the variable declared using let will show an error because let is block scoped.
HTML
<!DOCTYPE html><html> <head> <title>Var vs Let</title></head> <body> <h1 id="var" style="color:black;">GeeksForGeeks</h1> <h1 id="let" style="color:black;">GeeksForGeeks</h1> <button id="btn" onclick="colour()">Start</button> <!-- executing function on button click --> <script type="text/javascript"> function colour() { setInterval(function() { if (document.getElementById('var').style.color == 'black') var col1 = 'blue'; else col1 = 'black'; // setting value of color 1 through var if (document.getElementById('let').style.color == 'black') { let col2 = 'red'; } else { col2 = 'black'; } // setting value of color 2 through let document.getElementById('var').style.color = col1; document.getElementById('let').style.color = col2; // changing color of h1 in html }, 500); } </script></body> </html>
Output:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Let us understand the differences in a tabular form -:
Syntax -:
var name = value;
Syntax -:
let name = value;
Example -:
var websitename = “geeksforgeeks”;
Example -:
let x = 69;
princeagrawal701
rajatdiptabiswas
mayank007rawa
sweetyty
SAKSHIKULSHRESHTHA
javascript-basics
JavaScript
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
JavaScript | Promises
How to get character array from string in JavaScript?
Node.js | fs.writeFileSync() Method
How to filter object array based on attributes? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 361,
"s": 53,
"text": "var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. It can be said that a variable declared with var is defined throughout the program as compared to let. An example will clarify the difference even better "
},
{
"code": null,
"e": 377,
"s": 361,
"text": "Example of var:"
},
{
"code": null,
"e": 445,
"s": 377,
"text": "Input:\nconsole.log(x);\nvar x=5;\nconsole.log(x);\nOutput:\nundefined\n5"
},
{
"code": null,
"e": 463,
"s": 447,
"text": "Example of let:"
},
{
"code": null,
"e": 525,
"s": 463,
"text": "Input:\nconsole.log(x);\nlet x=5;\nconsole.log(x);\nOutput:\nError"
},
{
"code": null,
"e": 567,
"s": 527,
"text": "Let’s see code in JavaScript: Code #1: "
},
{
"code": null,
"e": 572,
"s": 567,
"text": "HTML"
},
{
"code": "<html> <body> <script> // calling x after definition var x = 5; document.write(x, \"\\n\"); // calling y after definition let y = 10; document.write(y, \"\\n\"); // calling var z before definition will return undefined document.write(z, \"\\n\"); var z = 2; // calling let a before definition will give error document.write(a); let a = 3; </script></body> </html> ",
"e": 1047,
"s": 572,
"text": null
},
{
"code": null,
"e": 1423,
"s": 1049,
"text": "Code #2: In the following code, clicking start will call a function that changes the color of the two headings every 0.5sec. The color of first heading is stored in a var and the second one is declared by using let. Both of them are then accessed outside the function block. Var will work but the variable declared using let will show an error because let is block scoped. "
},
{
"code": null,
"e": 1428,
"s": 1423,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Var vs Let</title></head> <body> <h1 id=\"var\" style=\"color:black;\">GeeksForGeeks</h1> <h1 id=\"let\" style=\"color:black;\">GeeksForGeeks</h1> <button id=\"btn\" onclick=\"colour()\">Start</button> <!-- executing function on button click --> <script type=\"text/javascript\"> function colour() { setInterval(function() { if (document.getElementById('var').style.color == 'black') var col1 = 'blue'; else col1 = 'black'; // setting value of color 1 through var if (document.getElementById('let').style.color == 'black') { let col2 = 'red'; } else { col2 = 'black'; } // setting value of color 2 through let document.getElementById('var').style.color = col1; document.getElementById('let').style.color = col2; // changing color of h1 in html }, 500); } </script></body> </html>",
"e": 2524,
"s": 1428,
"text": null
},
{
"code": null,
"e": 2532,
"s": 2524,
"text": "Output:"
},
{
"code": null,
"e": 2753,
"s": 2534,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 2808,
"s": 2753,
"text": "Let us understand the differences in a tabular form -:"
},
{
"code": null,
"e": 2818,
"s": 2808,
"text": "Syntax -:"
},
{
"code": null,
"e": 2836,
"s": 2818,
"text": "var name = value;"
},
{
"code": null,
"e": 2846,
"s": 2836,
"text": "Syntax -:"
},
{
"code": null,
"e": 2864,
"s": 2846,
"text": "let name = value;"
},
{
"code": null,
"e": 2875,
"s": 2864,
"text": "Example -:"
},
{
"code": null,
"e": 2910,
"s": 2875,
"text": "var websitename = “geeksforgeeks”;"
},
{
"code": null,
"e": 2921,
"s": 2910,
"text": "Example -:"
},
{
"code": null,
"e": 2934,
"s": 2921,
"text": " let x = 69;"
},
{
"code": null,
"e": 2951,
"s": 2934,
"text": "princeagrawal701"
},
{
"code": null,
"e": 2968,
"s": 2951,
"text": "rajatdiptabiswas"
},
{
"code": null,
"e": 2982,
"s": 2968,
"text": "mayank007rawa"
},
{
"code": null,
"e": 2991,
"s": 2982,
"text": "sweetyty"
},
{
"code": null,
"e": 3010,
"s": 2991,
"text": "SAKSHIKULSHRESHTHA"
},
{
"code": null,
"e": 3028,
"s": 3010,
"text": "javascript-basics"
},
{
"code": null,
"e": 3039,
"s": 3028,
"text": "JavaScript"
},
{
"code": null,
"e": 3137,
"s": 3039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3198,
"s": 3137,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3270,
"s": 3198,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3310,
"s": 3270,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3352,
"s": 3310,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3393,
"s": 3352,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3439,
"s": 3393,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 3461,
"s": 3439,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 3515,
"s": 3461,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 3551,
"s": 3515,
"text": "Node.js | fs.writeFileSync() Method"
}
] |
Method Overloading in Scala | 27 Jan, 2019
Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. Scala can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameter list (i.e. the number of the parameters, the order of the parameters, and data types of the parameters) within the same class.
Overloaded methods are differentiated based on the number and type of the parameters passed as an argument to the methods.
We can not define more than one method with the same name, Order and the type of the arguments. It would be a compiler error.
The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type. It will throw a compile-time error.
If we need to do the same kind of operation in different ways i.e. for different inputs. In the example described below, we are doing the addition operation for different inputs. It is hard to find many different meaningful names for single action.
Method overloading can be done by changing:
The number of parameters in two methods.
The data types of the parameters of methods.
The Order of the parameters of methods.
Example:
// Scala program to demonstrate the function // overloading by changing the number // of parameters class GFG{ // function 1 with two parameters def fun(p:Int, q:Int) { var Sum = p + q; println("Sum in function 1 is:" + Sum); } // function 2 with three parameters def fun(p:Int, q:Int, r:Int) { var Sum = p + q + r; println("Sum in function 2 is:" + Sum); }}object Main { // Main function def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.fun(6, 8); obj.fun(5, 10, 58); }}
Output:
Sum in function 1 is:14
Sum in function 2 is:73
Example:
// Scala program to demonstrate the function // overloading by changing the data types // of the parameters class GFG{ // Adding three integer elements def fun(p:Int, q:Int, r:Int) { var Sum = p + q + r; println("Sum in function 1 is:"+Sum); } // Adding three double elements def fun(p:Double, q:Double, r:Double) { var Sum = p + q + r; println("Sum in function 2 is:"+Sum); }}object Main { // Main method def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.fun(6, 8, 10); obj.fun(5.9, 10.01, 58.7); }}
Output:
Sum in function 1 is:24
Sum in function 2 is:74.61
Example:
// Scala program to demonstrate the function // overloading by changing the // order of the parameters class GFG{ // Function 1 def fun(name:String, No:Int) { println("Name of the watch company is:" + name); println("Total number of watch :" + No); } // Function 2 def fun(No:Int, name:String ) { println("Name of the watch company is:" + name); println("Total number of watch :" + No); }}object Main { // Main Function def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.fun("Rolex", 10); obj.fun("Omega", 10); }}
Output:
Name of the watch company is:Rolex
Total number of watch :10
Name of the watch company is:Omega
Total number of watch :10
The compiler will give error as the return value alone is not sufficient for the compiler to figure out which function it has to call. Only if both methods have different parameter types (so, they have the different signature), then Method overloading is possible.Example:
// Example to show error when method signature is same // and return type is different. object Main { // Main method def main(args: Array[String]) { println("Sum in function 1 is:" + fun(6, 8) ); println("Sum in function 2 is:" + fun(6, 8) ); } // function 1 def fun(p:Int, q:Int) : Int = { var Sum: Int = p + q; return Sum; } // function 2 def fun(p:Int, q:Int) : Double = { var Sum: Double = p + q + 3.7; return Sum; } }
Compile-time Error:
prog.scala:10: error: ambiguous reference to overloaded definition,both method fun in object Main of type (p: Int, q: Int)Doubleand method fun in object Main of type (p: Int, q: Int)Intmatch argument types (Int,Int) and expected result type Anyprintln(“Sum in function 1 is:” + fun(6, 8) );^prog.scala:11: error: ambiguous reference to overloaded definition,both method fun in object Main of type (p: Int, q: Int)Doubleand method fun in object Main of type (p: Int, q: Int)Intmatch argument types (Int,Int) and expected result type Anyprintln(“Sum in function 2 is:” + fun(6, 8) );^prog.scala:22: error: method fun is defined twiceconflicting symbols both originated in file ‘prog.scala’def fun(p:Int, q:Int) : Double = {^three errors found
Scala
Scala-Method
Scala-OOPS
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2019"
},
{
"code": null,
"e": 533,
"s": 28,
"text": "Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. Scala can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameter list (i.e. the number of the parameters, the order of the parameters, and data types of the parameters) within the same class."
},
{
"code": null,
"e": 656,
"s": 533,
"text": "Overloaded methods are differentiated based on the number and type of the parameters passed as an argument to the methods."
},
{
"code": null,
"e": 782,
"s": 656,
"text": "We can not define more than one method with the same name, Order and the type of the arguments. It would be a compiler error."
},
{
"code": null,
"e": 996,
"s": 782,
"text": "The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type. It will throw a compile-time error."
},
{
"code": null,
"e": 1245,
"s": 996,
"text": "If we need to do the same kind of operation in different ways i.e. for different inputs. In the example described below, we are doing the addition operation for different inputs. It is hard to find many different meaningful names for single action."
},
{
"code": null,
"e": 1289,
"s": 1245,
"text": "Method overloading can be done by changing:"
},
{
"code": null,
"e": 1330,
"s": 1289,
"text": "The number of parameters in two methods."
},
{
"code": null,
"e": 1375,
"s": 1330,
"text": "The data types of the parameters of methods."
},
{
"code": null,
"e": 1415,
"s": 1375,
"text": "The Order of the parameters of methods."
},
{
"code": null,
"e": 1424,
"s": 1415,
"text": "Example:"
},
{
"code": "// Scala program to demonstrate the function // overloading by changing the number // of parameters class GFG{ // function 1 with two parameters def fun(p:Int, q:Int) { var Sum = p + q; println(\"Sum in function 1 is:\" + Sum); } // function 2 with three parameters def fun(p:Int, q:Int, r:Int) { var Sum = p + q + r; println(\"Sum in function 2 is:\" + Sum); }}object Main { // Main function def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.fun(6, 8); obj.fun(5, 10, 58); }}",
"e": 2035,
"s": 1424,
"text": null
},
{
"code": null,
"e": 2043,
"s": 2035,
"text": "Output:"
},
{
"code": null,
"e": 2092,
"s": 2043,
"text": "Sum in function 1 is:14\nSum in function 2 is:73\n"
},
{
"code": null,
"e": 2101,
"s": 2092,
"text": "Example:"
},
{
"code": "// Scala program to demonstrate the function // overloading by changing the data types // of the parameters class GFG{ // Adding three integer elements def fun(p:Int, q:Int, r:Int) { var Sum = p + q + r; println(\"Sum in function 1 is:\"+Sum); } // Adding three double elements def fun(p:Double, q:Double, r:Double) { var Sum = p + q + r; println(\"Sum in function 2 is:\"+Sum); }}object Main { // Main method def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.fun(6, 8, 10); obj.fun(5.9, 10.01, 58.7); }}",
"e": 2740,
"s": 2101,
"text": null
},
{
"code": null,
"e": 2748,
"s": 2740,
"text": "Output:"
},
{
"code": null,
"e": 2800,
"s": 2748,
"text": "Sum in function 1 is:24\nSum in function 2 is:74.61\n"
},
{
"code": null,
"e": 2809,
"s": 2800,
"text": "Example:"
},
{
"code": "// Scala program to demonstrate the function // overloading by changing the // order of the parameters class GFG{ // Function 1 def fun(name:String, No:Int) { println(\"Name of the watch company is:\" + name); println(\"Total number of watch :\" + No); } // Function 2 def fun(No:Int, name:String ) { println(\"Name of the watch company is:\" + name); println(\"Total number of watch :\" + No); }}object Main { // Main Function def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(); obj.fun(\"Rolex\", 10); obj.fun(\"Omega\", 10); }}",
"e": 3459,
"s": 2809,
"text": null
},
{
"code": null,
"e": 3467,
"s": 3459,
"text": "Output:"
},
{
"code": null,
"e": 3591,
"s": 3467,
"text": "Name of the watch company is:Rolex\nTotal number of watch :10\nName of the watch company is:Omega\nTotal number of watch :10\n\n"
},
{
"code": null,
"e": 3864,
"s": 3591,
"text": "The compiler will give error as the return value alone is not sufficient for the compiler to figure out which function it has to call. Only if both methods have different parameter types (so, they have the different signature), then Method overloading is possible.Example:"
},
{
"code": "// Example to show error when method signature is same // and return type is different. object Main { // Main method def main(args: Array[String]) { println(\"Sum in function 1 is:\" + fun(6, 8) ); println(\"Sum in function 2 is:\" + fun(6, 8) ); } // function 1 def fun(p:Int, q:Int) : Int = { var Sum: Int = p + q; return Sum; } // function 2 def fun(p:Int, q:Int) : Double = { var Sum: Double = p + q + 3.7; return Sum; } }",
"e": 4403,
"s": 3864,
"text": null
},
{
"code": null,
"e": 4423,
"s": 4403,
"text": "Compile-time Error:"
},
{
"code": null,
"e": 5164,
"s": 4423,
"text": "prog.scala:10: error: ambiguous reference to overloaded definition,both method fun in object Main of type (p: Int, q: Int)Doubleand method fun in object Main of type (p: Int, q: Int)Intmatch argument types (Int,Int) and expected result type Anyprintln(“Sum in function 1 is:” + fun(6, 8) );^prog.scala:11: error: ambiguous reference to overloaded definition,both method fun in object Main of type (p: Int, q: Int)Doubleand method fun in object Main of type (p: Int, q: Int)Intmatch argument types (Int,Int) and expected result type Anyprintln(“Sum in function 2 is:” + fun(6, 8) );^prog.scala:22: error: method fun is defined twiceconflicting symbols both originated in file ‘prog.scala’def fun(p:Int, q:Int) : Double = {^three errors found"
},
{
"code": null,
"e": 5170,
"s": 5164,
"text": "Scala"
},
{
"code": null,
"e": 5183,
"s": 5170,
"text": "Scala-Method"
},
{
"code": null,
"e": 5194,
"s": 5183,
"text": "Scala-OOPS"
},
{
"code": null,
"e": 5200,
"s": 5194,
"text": "Scala"
}
] |
How to set the Size of the ComboBox in C#? | 27 Jun, 2019
In Windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the size to your ComboBox by using Size Property. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the size of the ComboBox control as using the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the ComboBox control to set the size of the ComboBox.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the size of the ComboBox programmatically with the help of given syntax:
public System.Drawing.Size Size { get; set; }
Here, the Size indicates the height and width of the ComboBox in pixels. Following steps are used to set the size of the ComboBox:
Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class
ComboBox mybox = new ComboBox();
// Creating ComboBox using ComboBox class
ComboBox mybox = new ComboBox();
Step 2: After creating ComboBox, set the size of the ComboBox.// Set the size of the combobox
mybox.Size = new Size(216, 26);
// Set the size of the combobox
mybox.Size = new Size(216, 26);
Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form
this.Controls.Add(mybox);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select Your id"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Name = "My_Cobo_Box"; mybox.Items.Add(230); mybox.Items.Add(231); mybox.Items.Add(232); mybox.Items.Add(233); mybox.Items.Add(234); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:
// Add this ComboBox to form
this.Controls.Add(mybox);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = "Select Your id"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Name = "My_Cobo_Box"; mybox.Items.Add(230); mybox.Items.Add(231); mybox.Items.Add(232); mybox.Items.Add(233); mybox.Items.Add(234); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
Introduction to .NET Framework
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
Extension Method in C# | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jun, 2019"
},
{
"code": null,
"e": 400,
"s": 28,
"text": "In Windows forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. You are allowed to set the size to your ComboBox by using Size Property. You can set this property using two different methods:"
},
{
"code": null,
"e": 511,
"s": 400,
"text": "1. Design-Time: It is the easiest method to set the size of the ComboBox control as using the following steps:"
},
{
"code": null,
"e": 627,
"s": 511,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 808,
"s": 627,
"text": "Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 930,
"s": 808,
"text": "Step 3: After drag and drop you will go to the properties of the ComboBox control to set the size of the ComboBox.Output:"
},
{
"code": null,
"e": 938,
"s": 930,
"text": "Output:"
},
{
"code": null,
"e": 1103,
"s": 938,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the size of the ComboBox programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1149,
"s": 1103,
"text": "public System.Drawing.Size Size { get; set; }"
},
{
"code": null,
"e": 1280,
"s": 1149,
"text": "Here, the Size indicates the height and width of the ComboBox in pixels. Following steps are used to set the size of the ComboBox:"
},
{
"code": null,
"e": 1449,
"s": 1280,
"text": "Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n"
},
{
"code": null,
"e": 1525,
"s": 1449,
"text": "// Creating ComboBox using ComboBox class\nComboBox mybox = new ComboBox();\n"
},
{
"code": null,
"e": 1652,
"s": 1525,
"text": "Step 2: After creating ComboBox, set the size of the ComboBox.// Set the size of the combobox\nmybox.Size = new Size(216, 26);\n"
},
{
"code": null,
"e": 1717,
"s": 1652,
"text": "// Set the size of the combobox\nmybox.Size = new Size(216, 26);\n"
},
{
"code": null,
"e": 2965,
"s": 1717,
"text": "Step 3: And last add this combobox control to form using Add() method.// Add this ComboBox to form\nthis.Controls.Add(mybox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select Your id\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Name = \"My_Cobo_Box\"; mybox.Items.Add(230); mybox.Items.Add(231); mybox.Items.Add(232); mybox.Items.Add(233); mybox.Items.Add(234); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:"
},
{
"code": null,
"e": 3021,
"s": 2965,
"text": "// Add this ComboBox to form\nthis.Controls.Add(mybox);\n"
},
{
"code": null,
"e": 3030,
"s": 3021,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(222, 80); l.Size = new Size(99, 18); l.Text = \"Select Your id\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Name = \"My_Cobo_Box\"; mybox.Items.Add(230); mybox.Items.Add(231); mybox.Items.Add(232); mybox.Items.Add(233); mybox.Items.Add(234); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}",
"e": 4138,
"s": 3030,
"text": null
},
{
"code": null,
"e": 4146,
"s": 4138,
"text": "Output:"
},
{
"code": null,
"e": 4149,
"s": 4146,
"text": "C#"
},
{
"code": null,
"e": 4247,
"s": 4149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4275,
"s": 4247,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 4290,
"s": 4275,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4321,
"s": 4290,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4364,
"s": 4321,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4413,
"s": 4364,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4436,
"s": 4413,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 4476,
"s": 4436,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 4494,
"s": 4476,
"text": "C# | Constructors"
},
{
"code": null,
"e": 4516,
"s": 4494,
"text": "C# | Class and Object"
}
] |
Google Interview Questions | 23 Apr, 2019
As per Google’s official career page, there are two types of interviews, Phone/Hangout interviews and Onsite Interviews. Below is an excerpt for their official page.
For software engineering candidates, we want to understand your coding skills and technical areas of expertise, including tools or programming languages and general knowledge on topics like data structures and algorithms. There’s generally some back and forth in these discussions, just like there is on the job, because we like to push each other’s thinking and learn about different approaches. So be prepared to talk through your solutions in depth. Push your own boundaries and find the best answer—that’s probably how you work anyway.
Important Resources :
Recent Google Interview ExperiencesAll Google Practice QuestionsHow to prepare for Google KickStart
Recent Google Interview Experiences
All Google Practice Questions
How to prepare for Google KickStart
Practice Questions:
Find all triplets with zero sum
Generate all binary strings from given pattern
Count of strings that can be formed using a, b and c under given constraints
Find largest word in dictionary by deleting some characters of given string
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Find the longest substring with k unique characters in a given string
Find the two non-repeating elements in an array of repeating elements
Flood fill Algorithm – how to implement fill() in paint?
Meta Strings (Check if two strings can become same after a swap in one string)
Print all Jumping Numbers smaller than or equal to a given value
Sum of all the numbers that are formed from root to leaf paths
The Celebrity Problem
Unbounded Knapsack (Repetition of items allowed)
Medium Level
Backtracking | Set 7 (Sudoku)
Boggle | Set 2 (Using Trie)
Check if a Binary Tree contains duplicate subtrees of size 2 or more
Dynamic Programming | Set 33 (Find if a string is interleaved of two other stri
Connect nodes at same level
Count BST nodes that lie in a given range
Dynamic Programming | Set 11 (Egg Dropping Puzzle)
Dynamic Programming | Set 28 (Minimum insertions to form a palindrome)
Dynamic Programming | Set 31 (Optimal Strategy for a Game)
Dynamic Programming | Set 32 (Word Break Problem)
Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)
Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
How to print maximum number of A’s using given four keys
Inplace rotate square matrix by 90 degrees | Set 1
Maximum absolute difference between sum of two contiguous sub-arrays
Merge two BSTs with limited extra space
Merge Overlapping Intervals
Modular Exponentiation (Power in Modular Arithmetic)
Paper Cut into Minimum Number of Squares | Set 2
Sum of bit differences among all pairs
Hard Level
Allocate minimum number of pages
Given an array arr[], find the maximum j – i such that arr[j] > arr[i]
Given a sorted dictionary of an alien language, find order of characters
Hungarian Algorithm for Assignment Problem | Set 1 (Introduction)
Implement LRU Cache
Length of the longest valid substring
Median in a stream of integers (running integers)
Sum of bit differences among all pairs
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Word Break Problem using Backtracking
Google
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
TCS Digital Interview Questions
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
Amazon Interview Experience SDE-2 (3 Years Experienced)
TCS Ninja Interview Experience (2020 batch)
Write It Up: Share Your Interview Experiences
Samsung RnD Coding Round Questions
Nagarro Interview Experience
Amazon Interview Experience for SDE-1 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Apr, 2019"
},
{
"code": null,
"e": 220,
"s": 54,
"text": "As per Google’s official career page, there are two types of interviews, Phone/Hangout interviews and Onsite Interviews. Below is an excerpt for their official page."
},
{
"code": null,
"e": 760,
"s": 220,
"text": "For software engineering candidates, we want to understand your coding skills and technical areas of expertise, including tools or programming languages and general knowledge on topics like data structures and algorithms. There’s generally some back and forth in these discussions, just like there is on the job, because we like to push each other’s thinking and learn about different approaches. So be prepared to talk through your solutions in depth. Push your own boundaries and find the best answer—that’s probably how you work anyway."
},
{
"code": null,
"e": 782,
"s": 760,
"text": "Important Resources :"
},
{
"code": null,
"e": 882,
"s": 782,
"text": "Recent Google Interview ExperiencesAll Google Practice QuestionsHow to prepare for Google KickStart"
},
{
"code": null,
"e": 918,
"s": 882,
"text": "Recent Google Interview Experiences"
},
{
"code": null,
"e": 948,
"s": 918,
"text": "All Google Practice Questions"
},
{
"code": null,
"e": 984,
"s": 948,
"text": "How to prepare for Google KickStart"
},
{
"code": null,
"e": 1004,
"s": 984,
"text": "Practice Questions:"
},
{
"code": null,
"e": 1036,
"s": 1004,
"text": "Find all triplets with zero sum"
},
{
"code": null,
"e": 1083,
"s": 1036,
"text": "Generate all binary strings from given pattern"
},
{
"code": null,
"e": 1160,
"s": 1083,
"text": "Count of strings that can be formed using a, b and c under given constraints"
},
{
"code": null,
"e": 1236,
"s": 1160,
"text": "Find largest word in dictionary by deleting some characters of given string"
},
{
"code": null,
"e": 1295,
"s": 1236,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 1365,
"s": 1295,
"text": "Find the longest substring with k unique characters in a given string"
},
{
"code": null,
"e": 1435,
"s": 1365,
"text": "Find the two non-repeating elements in an array of repeating elements"
},
{
"code": null,
"e": 1492,
"s": 1435,
"text": "Flood fill Algorithm – how to implement fill() in paint?"
},
{
"code": null,
"e": 1571,
"s": 1492,
"text": "Meta Strings (Check if two strings can become same after a swap in one string)"
},
{
"code": null,
"e": 1636,
"s": 1571,
"text": "Print all Jumping Numbers smaller than or equal to a given value"
},
{
"code": null,
"e": 1699,
"s": 1636,
"text": "Sum of all the numbers that are formed from root to leaf paths"
},
{
"code": null,
"e": 1721,
"s": 1699,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 1770,
"s": 1721,
"text": "Unbounded Knapsack (Repetition of items allowed)"
},
{
"code": null,
"e": 1783,
"s": 1770,
"text": "Medium Level"
},
{
"code": null,
"e": 1813,
"s": 1783,
"text": "Backtracking | Set 7 (Sudoku)"
},
{
"code": null,
"e": 1841,
"s": 1813,
"text": "Boggle | Set 2 (Using Trie)"
},
{
"code": null,
"e": 1910,
"s": 1841,
"text": "Check if a Binary Tree contains duplicate subtrees of size 2 or more"
},
{
"code": null,
"e": 1990,
"s": 1910,
"text": "Dynamic Programming | Set 33 (Find if a string is interleaved of two other stri"
},
{
"code": null,
"e": 2018,
"s": 1990,
"text": "Connect nodes at same level"
},
{
"code": null,
"e": 2060,
"s": 2018,
"text": "Count BST nodes that lie in a given range"
},
{
"code": null,
"e": 2111,
"s": 2060,
"text": "Dynamic Programming | Set 11 (Egg Dropping Puzzle)"
},
{
"code": null,
"e": 2182,
"s": 2111,
"text": "Dynamic Programming | Set 28 (Minimum insertions to form a palindrome)"
},
{
"code": null,
"e": 2241,
"s": 2182,
"text": "Dynamic Programming | Set 31 (Optimal Strategy for a Game)"
},
{
"code": null,
"e": 2291,
"s": 2241,
"text": "Dynamic Programming | Set 32 (Word Break Problem)"
},
{
"code": null,
"e": 2367,
"s": 2291,
"text": "Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)"
},
{
"code": null,
"e": 2440,
"s": 2367,
"text": "Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’"
},
{
"code": null,
"e": 2497,
"s": 2440,
"text": "How to print maximum number of A’s using given four keys"
},
{
"code": null,
"e": 2548,
"s": 2497,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 2617,
"s": 2548,
"text": "Maximum absolute difference between sum of two contiguous sub-arrays"
},
{
"code": null,
"e": 2657,
"s": 2617,
"text": "Merge two BSTs with limited extra space"
},
{
"code": null,
"e": 2685,
"s": 2657,
"text": "Merge Overlapping Intervals"
},
{
"code": null,
"e": 2738,
"s": 2685,
"text": "Modular Exponentiation (Power in Modular Arithmetic)"
},
{
"code": null,
"e": 2787,
"s": 2738,
"text": "Paper Cut into Minimum Number of Squares | Set 2"
},
{
"code": null,
"e": 2826,
"s": 2787,
"text": "Sum of bit differences among all pairs"
},
{
"code": null,
"e": 2837,
"s": 2826,
"text": "Hard Level"
},
{
"code": null,
"e": 2870,
"s": 2837,
"text": "Allocate minimum number of pages"
},
{
"code": null,
"e": 2941,
"s": 2870,
"text": "Given an array arr[], find the maximum j – i such that arr[j] > arr[i]"
},
{
"code": null,
"e": 3014,
"s": 2941,
"text": "Given a sorted dictionary of an alien language, find order of characters"
},
{
"code": null,
"e": 3080,
"s": 3014,
"text": "Hungarian Algorithm for Assignment Problem | Set 1 (Introduction)"
},
{
"code": null,
"e": 3100,
"s": 3080,
"text": "Implement LRU Cache"
},
{
"code": null,
"e": 3138,
"s": 3100,
"text": "Length of the longest valid substring"
},
{
"code": null,
"e": 3188,
"s": 3138,
"text": "Median in a stream of integers (running integers)"
},
{
"code": null,
"e": 3227,
"s": 3188,
"text": "Sum of bit differences among all pairs"
},
{
"code": null,
"e": 3295,
"s": 3227,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 3333,
"s": 3295,
"text": "Word Break Problem using Backtracking"
},
{
"code": null,
"e": 3340,
"s": 3333,
"text": "Google"
},
{
"code": null,
"e": 3362,
"s": 3340,
"text": "Interview Experiences"
},
{
"code": null,
"e": 3369,
"s": 3362,
"text": "Google"
},
{
"code": null,
"e": 3467,
"s": 3369,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3537,
"s": 3467,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 3569,
"s": 3537,
"text": "TCS Digital Interview Questions"
},
{
"code": null,
"e": 3642,
"s": 3569,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 3680,
"s": 3642,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 3736,
"s": 3680,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 3780,
"s": 3736,
"text": "TCS Ninja Interview Experience (2020 batch)"
},
{
"code": null,
"e": 3826,
"s": 3780,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 3861,
"s": 3826,
"text": "Samsung RnD Coding Round Questions"
},
{
"code": null,
"e": 3890,
"s": 3861,
"text": "Nagarro Interview Experience"
}
] |
Date equals() method in Java with Examples | 02 Jan, 2019
The equals() method of Java Date class checks if two Dates are equal, based on millisecond difference.
Syntax:
public boolean equals(Object obj)
Parameters: The function accepts a single parameter obj which specifies the object to be compared with.
Return Value: The function gives 2 return values specified below:
true if the objects are equal.
false if the objects are not equal.
Exception: The function does not throws any exception.
Program below demonstrates the above mentioned function:
// Java code to demonstrate// equals() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c.set(Calendar.MONTH, 11); // set Date c.set(Calendar.DATE, 05); // set Year c.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c.getTime(); System.out.println("Date 1: " + dateOne); // creating a date of object // storing the current date Date currentDate = new Date(); System.out.println("Date 2: " + currentDate); System.out.println("Are both dates equal: " + currentDate.equals(dateOne)); }}
Date 1: Thu Dec 05 08:19:56 UTC 1996
Date 2: Wed Jan 02 08:19:56 UTC 2019
Are both dates equal: false
// Java code to demonstrate// equals() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c1 = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 11); // set Date c1.set(Calendar.DATE, 05); // set Year c1.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c1.getTime(); System.out.println("Date 1: " + dateOne); // creating a Calendar object Calendar c2 = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c2.set(Calendar.MONTH, 11); // set Date c2.set(Calendar.DATE, 05); // set Year c2.set(Calendar.YEAR, 1995); // creating a date object with specified time. Date dateTwo = c2.getTime(); System.out.println("Date 1: " + dateTwo); System.out.println("Are both dates equal: " + dateTwo.equals(dateOne)); }}
Date 1: Thu Dec 05 08:20:05 UTC 1996
Date 1: Tue Dec 05 08:20:05 UTC 1995
Are both dates equal: false
Java - util package
Java-Functions
Java-util-Date
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "The equals() method of Java Date class checks if two Dates are equal, based on millisecond difference."
},
{
"code": null,
"e": 139,
"s": 131,
"text": "Syntax:"
},
{
"code": null,
"e": 174,
"s": 139,
"text": "public boolean equals(Object obj)\n"
},
{
"code": null,
"e": 278,
"s": 174,
"text": "Parameters: The function accepts a single parameter obj which specifies the object to be compared with."
},
{
"code": null,
"e": 344,
"s": 278,
"text": "Return Value: The function gives 2 return values specified below:"
},
{
"code": null,
"e": 375,
"s": 344,
"text": "true if the objects are equal."
},
{
"code": null,
"e": 411,
"s": 375,
"text": "false if the objects are not equal."
},
{
"code": null,
"e": 466,
"s": 411,
"text": "Exception: The function does not throws any exception."
},
{
"code": null,
"e": 523,
"s": 466,
"text": "Program below demonstrates the above mentioned function:"
},
{
"code": "// Java code to demonstrate// equals() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c.set(Calendar.MONTH, 11); // set Date c.set(Calendar.DATE, 05); // set Year c.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c.getTime(); System.out.println(\"Date 1: \" + dateOne); // creating a date of object // storing the current date Date currentDate = new Date(); System.out.println(\"Date 2: \" + currentDate); System.out.println(\"Are both dates equal: \" + currentDate.equals(dateOne)); }}",
"e": 1438,
"s": 523,
"text": null
},
{
"code": null,
"e": 1541,
"s": 1438,
"text": "Date 1: Thu Dec 05 08:19:56 UTC 1996\nDate 2: Wed Jan 02 08:19:56 UTC 2019\nAre both dates equal: false\n"
},
{
"code": "// Java code to demonstrate// equals() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c1 = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 11); // set Date c1.set(Calendar.DATE, 05); // set Year c1.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c1.getTime(); System.out.println(\"Date 1: \" + dateOne); // creating a Calendar object Calendar c2 = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c2.set(Calendar.MONTH, 11); // set Date c2.set(Calendar.DATE, 05); // set Year c2.set(Calendar.YEAR, 1995); // creating a date object with specified time. Date dateTwo = c2.getTime(); System.out.println(\"Date 1: \" + dateTwo); System.out.println(\"Are both dates equal: \" + dateTwo.equals(dateOne)); }}",
"e": 2733,
"s": 1541,
"text": null
},
{
"code": null,
"e": 2836,
"s": 2733,
"text": "Date 1: Thu Dec 05 08:20:05 UTC 1996\nDate 1: Tue Dec 05 08:20:05 UTC 1995\nAre both dates equal: false\n"
},
{
"code": null,
"e": 2856,
"s": 2836,
"text": "Java - util package"
},
{
"code": null,
"e": 2871,
"s": 2856,
"text": "Java-Functions"
},
{
"code": null,
"e": 2886,
"s": 2871,
"text": "Java-util-Date"
},
{
"code": null,
"e": 2891,
"s": 2886,
"text": "Java"
},
{
"code": null,
"e": 2896,
"s": 2891,
"text": "Java"
},
{
"code": null,
"e": 2994,
"s": 2896,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3045,
"s": 2994,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3076,
"s": 3045,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3095,
"s": 3076,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3125,
"s": 3095,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3140,
"s": 3125,
"text": "Stream In Java"
},
{
"code": null,
"e": 3158,
"s": 3140,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3178,
"s": 3158,
"text": "Collections in Java"
},
{
"code": null,
"e": 3202,
"s": 3178,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3234,
"s": 3202,
"text": "Multidimensional Arrays in Java"
}
] |
Scala String hashCode() method with example | 03 Oct, 2019
The hashCode() method is utilized to find the hash code of the stated string.
Method Definition: int hashCode()Return Type: It returns an integer hash code of the string given.
Example #1:
// Scala program of int hashCode()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying hashCode method val result = "Nidhi".hashCode() // Displays output println(result) }}
75262122
Example #2:
// Scala program of int hashCode()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying hashCode method val result = " ".hashCode() // Displays output println(result) }}
32
Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
Scala Singleton and Companion Objects | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 106,
"s": 28,
"text": "The hashCode() method is utilized to find the hash code of the stated string."
},
{
"code": null,
"e": 205,
"s": 106,
"text": "Method Definition: int hashCode()Return Type: It returns an integer hash code of the string given."
},
{
"code": null,
"e": 217,
"s": 205,
"text": "Example #1:"
},
{
"code": "// Scala program of int hashCode()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying hashCode method val result = \"Nidhi\".hashCode() // Displays output println(result) }} ",
"e": 502,
"s": 217,
"text": null
},
{
"code": null,
"e": 512,
"s": 502,
"text": "75262122\n"
},
{
"code": null,
"e": 524,
"s": 512,
"text": "Example #2:"
},
{
"code": "// Scala program of int hashCode()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying hashCode method val result = \" \".hashCode() // Displays output println(result) }} ",
"e": 809,
"s": 524,
"text": null
},
{
"code": null,
"e": 813,
"s": 809,
"text": "32\n"
},
{
"code": null,
"e": 819,
"s": 813,
"text": "Scala"
},
{
"code": null,
"e": 832,
"s": 819,
"text": "Scala-Method"
},
{
"code": null,
"e": 846,
"s": 832,
"text": "Scala-Strings"
},
{
"code": null,
"e": 852,
"s": 846,
"text": "Scala"
},
{
"code": null,
"e": 950,
"s": 852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 976,
"s": 950,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 998,
"s": 976,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 1051,
"s": 998,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 1063,
"s": 1051,
"text": "Scala Lists"
},
{
"code": null,
"e": 1082,
"s": 1063,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1097,
"s": 1082,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1116,
"s": 1097,
"text": "Scala Constructors"
},
{
"code": null,
"e": 1161,
"s": 1116,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 1188,
"s": 1161,
"text": "Lambda Expression in Scala"
}
] |
Convert Set to String in Python | 15 Oct, 2020
In this article, we will discuss how to convert a set to a string in Python. It can done using two ways –
Method 1: Using str()We will convert a Set into a String in Python using the str() function.
Syntax : str(object, encoding = ’utf-8?, errors = ’strict’)
Parameters :
object : The object whose string representation is to be returned.
encoding : Encoding of the given object.
errors : Response when decoding fails.
Returns : String version of the given object
Example 1 :
# create a sets = {'a', 'b', 'c', 'd'}print("Initially")print("The datatype of s : " + str(type(s)))print("Contents of s : ", s) # convert Set to Strings = str(s)print("\nAfter the conversion")print("The datatype of s : " + str(type(s)))print("Contents of s : " + s)
Output :
Initially
The datatype of s : <class 'set'>
Contents of s : {'c', 'd', 'a', 'b'}
After the conversion
The datatype of s : <class 'str'>
Contents of s : {'c', 'd', 'a', 'b'}
Example 2 :
# create a sets = {'g', 'e', 'e', 'k', 's'}print("Initially")print("The datatype of s : " + str(type(s)))print("Contents of s : ", s) # convert Set to Strings = str(s)print("\nAfter the conversion")print("The datatype of s : " + str(type(s)))print("Contents of s : " + s)
Output :
Initially
The datatype of s : <class 'set'>
Contents of s : {'k', 'g', 's', 'e'}
After the conversion
The datatype of s : <class 'str'>
Contents of s : {'k', 'g', 's', 'e'}
Method 2: Using Join()
The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.
Syntax:
string_name.join(iterable)
# create a sets = {'a', 'b', 'c', 'd'}print("Initially")print("The datatype of s : " + str(type(s)))print("Contents of s : ", s) # convert Set to StringS = ', '.join(s)print("The datatype of s : " + str(type(S)))print("Contents of s : ", S)
Output:
Initially
The datatype of s : <class 'set'>
Contents of s : {'c', 'd', 'a', 'b'}
The datatype of s : <class 'str'>
Contents of s : c, d, a, b
python-set
python-string
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "In this article, we will discuss how to convert a set to a string in Python. It can done using two ways –"
},
{
"code": null,
"e": 227,
"s": 134,
"text": "Method 1: Using str()We will convert a Set into a String in Python using the str() function."
},
{
"code": null,
"e": 287,
"s": 227,
"text": "Syntax : str(object, encoding = ’utf-8?, errors = ’strict’)"
},
{
"code": null,
"e": 300,
"s": 287,
"text": "Parameters :"
},
{
"code": null,
"e": 367,
"s": 300,
"text": "object : The object whose string representation is to be returned."
},
{
"code": null,
"e": 408,
"s": 367,
"text": "encoding : Encoding of the given object."
},
{
"code": null,
"e": 447,
"s": 408,
"text": "errors : Response when decoding fails."
},
{
"code": null,
"e": 492,
"s": 447,
"text": "Returns : String version of the given object"
},
{
"code": null,
"e": 504,
"s": 492,
"text": "Example 1 :"
},
{
"code": "# create a sets = {'a', 'b', 'c', 'd'}print(\"Initially\")print(\"The datatype of s : \" + str(type(s)))print(\"Contents of s : \", s) # convert Set to Strings = str(s)print(\"\\nAfter the conversion\")print(\"The datatype of s : \" + str(type(s)))print(\"Contents of s : \" + s)",
"e": 772,
"s": 504,
"text": null
},
{
"code": null,
"e": 781,
"s": 772,
"text": "Output :"
},
{
"code": null,
"e": 957,
"s": 781,
"text": "Initially\nThe datatype of s : <class 'set'>\nContents of s : {'c', 'd', 'a', 'b'}\n\nAfter the conversion\nThe datatype of s : <class 'str'>\nContents of s : {'c', 'd', 'a', 'b'}\n"
},
{
"code": null,
"e": 969,
"s": 957,
"text": "Example 2 :"
},
{
"code": "# create a sets = {'g', 'e', 'e', 'k', 's'}print(\"Initially\")print(\"The datatype of s : \" + str(type(s)))print(\"Contents of s : \", s) # convert Set to Strings = str(s)print(\"\\nAfter the conversion\")print(\"The datatype of s : \" + str(type(s)))print(\"Contents of s : \" + s)",
"e": 1242,
"s": 969,
"text": null
},
{
"code": null,
"e": 1251,
"s": 1242,
"text": "Output :"
},
{
"code": null,
"e": 1427,
"s": 1251,
"text": "Initially\nThe datatype of s : <class 'set'>\nContents of s : {'k', 'g', 's', 'e'}\n\nAfter the conversion\nThe datatype of s : <class 'str'>\nContents of s : {'k', 'g', 's', 'e'}\n"
},
{
"code": null,
"e": 1450,
"s": 1427,
"text": "Method 2: Using Join()"
},
{
"code": null,
"e": 1577,
"s": 1450,
"text": "The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator."
},
{
"code": null,
"e": 1585,
"s": 1577,
"text": "Syntax:"
},
{
"code": null,
"e": 1613,
"s": 1585,
"text": "string_name.join(iterable) "
},
{
"code": "# create a sets = {'a', 'b', 'c', 'd'}print(\"Initially\")print(\"The datatype of s : \" + str(type(s)))print(\"Contents of s : \", s) # convert Set to StringS = ', '.join(s)print(\"The datatype of s : \" + str(type(S)))print(\"Contents of s : \", S)",
"e": 1856,
"s": 1613,
"text": null
},
{
"code": null,
"e": 1864,
"s": 1856,
"text": "Output:"
},
{
"code": null,
"e": 2008,
"s": 1864,
"text": "Initially\nThe datatype of s : <class 'set'>\nContents of s : {'c', 'd', 'a', 'b'}\nThe datatype of s : <class 'str'>\nContents of s : c, d, a, b"
},
{
"code": null,
"e": 2019,
"s": 2008,
"text": "python-set"
},
{
"code": null,
"e": 2033,
"s": 2019,
"text": "python-string"
},
{
"code": null,
"e": 2040,
"s": 2033,
"text": "Python"
},
{
"code": null,
"e": 2051,
"s": 2040,
"text": "python-set"
},
{
"code": null,
"e": 2149,
"s": 2051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2181,
"s": 2149,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2208,
"s": 2181,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2229,
"s": 2208,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2252,
"s": 2229,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2308,
"s": 2252,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2339,
"s": 2308,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2381,
"s": 2339,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2423,
"s": 2381,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2462,
"s": 2423,
"text": "Python | Get unique values from a list"
}
] |
How to Drop Rows that Contain a Specific Value in Pandas? | 22 Nov, 2021
In this article, we will discuss how to drop rows that contain a specific value in Pandas. Dropping rows means removing values from the dataframe we can drop the specific value by using conditional or relational operators.
We can use the column_name function along with the operator to drop the specific value.
Syntax: dataframe[dataframe.column_name operator value]
where
dataframe is the input dataframe
column_name is the value of that column to be dropped
operator is the relational operator
value is the specific value to be dropped from the particular column
Python3
# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ "name": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], "marks": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94]}) # displayprint(data) print("---------------") # drop rows where value is 98# by using not equal operatorprint(data[data.marks != 98]) print("---------------")
Output:
By using this method we can drop multiple values present in the list, we are using isin() operator. This operator is used to check whether the given value is present in the list or not
Syntax: dataframe[dataframe.column_name.isin(list_of_values) == False]
where
dataframe is the input dataframe
column_name is to remove values in this column
list_of_values is the specific values to be removed
Python3
# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ "name": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], "marks": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94]}) # consider the listlist1 = [98, 82, 79] # drop rows from above listprint(data[data.marks.isin(list1) == False]) print("---------------") list2 = ['sravan', 'jyothika']# drop rows from above listprint(data[data.name.isin(list2) == False])
Output:
We can drop specific values from multiple columns by using relational operators.
Syntax: dataframe[(dataframe.column_name operator value ) relational_operator (dataframe.column_name operator value )]
where
dataframe is the input dataframe
column_nam eis the column
operator is the relational operator
Python3
# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ "name": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], "marks": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94]}) # drop specific values# where marks is 98 and name is sravanprint(data[(data.marks != 98) & (data.name != 'sravan')]) print("------------------") # drop specific values# where marks is 98 or name is sravanprint(data[(data.marks != 98) | (data.name != 'sravan')])
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 251,
"s": 28,
"text": "In this article, we will discuss how to drop rows that contain a specific value in Pandas. Dropping rows means removing values from the dataframe we can drop the specific value by using conditional or relational operators."
},
{
"code": null,
"e": 339,
"s": 251,
"text": "We can use the column_name function along with the operator to drop the specific value."
},
{
"code": null,
"e": 395,
"s": 339,
"text": "Syntax: dataframe[dataframe.column_name operator value]"
},
{
"code": null,
"e": 401,
"s": 395,
"text": "where"
},
{
"code": null,
"e": 434,
"s": 401,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 488,
"s": 434,
"text": "column_name is the value of that column to be dropped"
},
{
"code": null,
"e": 524,
"s": 488,
"text": "operator is the relational operator"
},
{
"code": null,
"e": 593,
"s": 524,
"text": "value is the specific value to be dropped from the particular column"
},
{
"code": null,
"e": 601,
"s": 593,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ \"name\": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], \"marks\": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94]}) # displayprint(data) print(\"---------------\") # drop rows where value is 98# by using not equal operatorprint(data[data.marks != 98]) print(\"---------------\")",
"e": 1269,
"s": 601,
"text": null
},
{
"code": null,
"e": 1277,
"s": 1269,
"text": "Output:"
},
{
"code": null,
"e": 1462,
"s": 1277,
"text": "By using this method we can drop multiple values present in the list, we are using isin() operator. This operator is used to check whether the given value is present in the list or not"
},
{
"code": null,
"e": 1533,
"s": 1462,
"text": "Syntax: dataframe[dataframe.column_name.isin(list_of_values) == False]"
},
{
"code": null,
"e": 1539,
"s": 1533,
"text": "where"
},
{
"code": null,
"e": 1572,
"s": 1539,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 1619,
"s": 1572,
"text": "column_name is to remove values in this column"
},
{
"code": null,
"e": 1671,
"s": 1619,
"text": "list_of_values is the specific values to be removed"
},
{
"code": null,
"e": 1679,
"s": 1671,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ \"name\": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], \"marks\": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94]}) # consider the listlist1 = [98, 82, 79] # drop rows from above listprint(data[data.marks.isin(list1) == False]) print(\"---------------\") list2 = ['sravan', 'jyothika']# drop rows from above listprint(data[data.name.isin(list2) == False])",
"e": 2446,
"s": 1679,
"text": null
},
{
"code": null,
"e": 2454,
"s": 2446,
"text": "Output:"
},
{
"code": null,
"e": 2535,
"s": 2454,
"text": "We can drop specific values from multiple columns by using relational operators."
},
{
"code": null,
"e": 2654,
"s": 2535,
"text": "Syntax: dataframe[(dataframe.column_name operator value ) relational_operator (dataframe.column_name operator value )]"
},
{
"code": null,
"e": 2660,
"s": 2654,
"text": "where"
},
{
"code": null,
"e": 2693,
"s": 2660,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 2719,
"s": 2693,
"text": "column_nam eis the column"
},
{
"code": null,
"e": 2755,
"s": 2719,
"text": "operator is the relational operator"
},
{
"code": null,
"e": 2763,
"s": 2755,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create dataframe with 4 columnsdata = pd.DataFrame({ \"name\": ['sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya', 'sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'java', 'java', 'python', 'python', 'python', 'html/php', 'html/php', 'html/php', 'php/js', 'php/js', 'php/js'], \"marks\": [98, 79, 89, 97, 82, 98, 90, 87, 78, 89, 93, 94]}) # drop specific values# where marks is 98 and name is sravanprint(data[(data.marks != 98) & (data.name != 'sravan')]) print(\"------------------\") # drop specific values# where marks is 98 or name is sravanprint(data[(data.marks != 98) | (data.name != 'sravan')])",
"e": 3552,
"s": 2763,
"text": null
},
{
"code": null,
"e": 3560,
"s": 3552,
"text": "Output:"
},
{
"code": null,
"e": 3585,
"s": 3560,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 3592,
"s": 3585,
"text": "Picked"
},
{
"code": null,
"e": 3616,
"s": 3592,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3630,
"s": 3616,
"text": "Python-pandas"
},
{
"code": null,
"e": 3637,
"s": 3630,
"text": "Python"
},
{
"code": null,
"e": 3735,
"s": 3637,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3767,
"s": 3735,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3794,
"s": 3767,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3825,
"s": 3794,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3848,
"s": 3825,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3869,
"s": 3848,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3925,
"s": 3869,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3967,
"s": 3925,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4009,
"s": 3967,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4048,
"s": 4009,
"text": "Python | Get unique values from a list"
}
] |
C Program to Check if a Given String is a Palindrome? | A palindrome is a word, number, phrase, or other sequences of characters which reads the same backward as forward. Words such as madam or racecar or the number 10801 are a palindrome.
For a given string if reversing the string gives the same string then we can say that the given string is a palindrome. Which means to check for the palindrome, we need to find whether the first and last, second and last-1, and so on elements are equal or not.
Input − naman
Output − string is a palindrome
Input − tutorials point
Output − string is not a palindrome
In C++ Program to Check if a Given String is a Palindrome. The entered string is copied to a new string, and then we compare the first letter with the last letter of string and second letter with second last letter and so on till the end of the string. If both of the letters have the same sequence of characters, i.e., they are identical then the string is a palindrome otherwise not.
#include <iostream>
#include<string.h>
using namespace std; {
int main(){
char string1[]={"naman"};
int i, length;
int flag = 0;
length = strlen(string1);
for(i=0;i < length ;i++){
if(string1[i] != string1[length-i-1]) {
flag = 1;
break;
}
}
if (flag==1){
printf(" string is not a palindrome");
} else {
printf(" string is a palindrome");
}
return 0;
}
}
string is a palindrome
Note - The program is case sensitive. | [
{
"code": null,
"e": 1371,
"s": 1187,
"text": "A palindrome is a word, number, phrase, or other sequences of characters which reads the same backward as forward. Words such as madam or racecar or the number 10801 are a palindrome."
},
{
"code": null,
"e": 1632,
"s": 1371,
"text": "For a given string if reversing the string gives the same string then we can say that the given string is a palindrome. Which means to check for the palindrome, we need to find whether the first and last, second and last-1, and so on elements are equal or not."
},
{
"code": null,
"e": 1647,
"s": 1632,
"text": "Input − naman "
},
{
"code": null,
"e": 1680,
"s": 1647,
"text": "Output − string is a palindrome "
},
{
"code": null,
"e": 1705,
"s": 1680,
"text": "Input − tutorials point "
},
{
"code": null,
"e": 1741,
"s": 1705,
"text": "Output − string is not a palindrome"
},
{
"code": null,
"e": 2127,
"s": 1741,
"text": "In C++ Program to Check if a Given String is a Palindrome. The entered string is copied to a new string, and then we compare the first letter with the last letter of string and second letter with second last letter and so on till the end of the string. If both of the letters have the same sequence of characters, i.e., they are identical then the string is a palindrome otherwise not."
},
{
"code": null,
"e": 2608,
"s": 2127,
"text": "#include <iostream>\n#include<string.h>\nusing namespace std; {\n int main(){\n char string1[]={\"naman\"};\n int i, length;\n int flag = 0;\n length = strlen(string1);\n for(i=0;i < length ;i++){\n if(string1[i] != string1[length-i-1]) {\n flag = 1;\n break;\n }\n }\n if (flag==1){\n printf(\" string is not a palindrome\");\n } else {\n printf(\" string is a palindrome\");\n }\n return 0;\n }\n}"
},
{
"code": null,
"e": 2631,
"s": 2608,
"text": "string is a palindrome"
},
{
"code": null,
"e": 2669,
"s": 2631,
"text": "Note - The program is case sensitive."
}
] |
How to create an unordered list with square bullets in HTML ? | 13 Jan, 2022
In this article, we will see how to create an unordered list with square bullets using HTML. To create an unordered list with square bullets, we will use CSS list-style-type: square property.
The list-style-type property in CSS specifies the appearance of the list item marker (such as a disc, character, or custom counter style).
Syntax:
list-style-type: disc|circle|square|decimal|lower-roman|upper-roman|
lower-greek|lower-latin|upper-latin|lower-alpha|upper-alpha|none|
inherit;
Approach: In the below example, we will create an unordered list items using <ul> and <li> tags and add CSS list-style-type: square style on <ul> element to make square bullets.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <title> How to create an unordered list with square bullets in HTML? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to create an unordered list <br>with square bullets in HTML? </h3> <p>Web Development Technologies - </p> <ul style="list-style-type:square"> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> <li>jQuery</li> </ul></body> </html>
Output:
HTML-Attributes
HTML-Questions
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 220,
"s": 28,
"text": "In this article, we will see how to create an unordered list with square bullets using HTML. To create an unordered list with square bullets, we will use CSS list-style-type: square property."
},
{
"code": null,
"e": 359,
"s": 220,
"text": "The list-style-type property in CSS specifies the appearance of the list item marker (such as a disc, character, or custom counter style)."
},
{
"code": null,
"e": 367,
"s": 359,
"text": "Syntax:"
},
{
"code": null,
"e": 511,
"s": 367,
"text": "list-style-type: disc|circle|square|decimal|lower-roman|upper-roman|\nlower-greek|lower-latin|upper-latin|lower-alpha|upper-alpha|none|\ninherit;"
},
{
"code": null,
"e": 689,
"s": 511,
"text": "Approach: In the below example, we will create an unordered list items using <ul> and <li> tags and add CSS list-style-type: square style on <ul> element to make square bullets."
},
{
"code": null,
"e": 698,
"s": 689,
"text": "Example:"
},
{
"code": null,
"e": 703,
"s": 698,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to create an unordered list with square bullets in HTML? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to create an unordered list <br>with square bullets in HTML? </h3> <p>Web Development Technologies - </p> <ul style=\"list-style-type:square\"> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> <li>jQuery</li> </ul></body> </html>",
"e": 1212,
"s": 703,
"text": null
},
{
"code": null,
"e": 1220,
"s": 1212,
"text": "Output:"
},
{
"code": null,
"e": 1236,
"s": 1220,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1251,
"s": 1236,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1256,
"s": 1251,
"text": "HTML"
},
{
"code": null,
"e": 1273,
"s": 1256,
"text": "Web Technologies"
},
{
"code": null,
"e": 1278,
"s": 1273,
"text": "HTML"
},
{
"code": null,
"e": 1376,
"s": 1278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1400,
"s": 1376,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1439,
"s": 1400,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1478,
"s": 1439,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1498,
"s": 1478,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1527,
"s": 1498,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1560,
"s": 1527,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1621,
"s": 1560,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1664,
"s": 1621,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1736,
"s": 1664,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Gallery Access in Flutter | 30 Aug, 2020
We can add images from the gallery using the image_picker package in Flutter. For this, you’ll need to use your real device.
Follow the below steps to display the images from the gallery:
Step 1: Create a new flutter application:
flutter create <YOUR_APP_NAME>
Step 2: Now, delete the code from the main.dart file to add your own code.
Step 3: Add the dependency to your pubspec.yaml file:
Step 4: Use the below code in the main.dart file :
main.dart
Dart
import 'dart:io';import 'package:flutter/material.dart';import 'package:image_picker/image_picker.dart'; void main() { runApp(new MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new GalleryAccess(), debugShowCheckedModeBanner: false, ); }} class GalleryAccess extends StatefulWidget { @override State<StatefulWidget> createState() { return new GalleryAccessState(); }} class GalleryAccessState extends State<GalleryAccess> { File galleryFile; @override Widget build(BuildContext context) { //display image selected from gallery imageSelectorGallery() async { galleryFile = await ImagePicker.pickImage( source: ImageSource.gallery, // maxHeight: 50.0, // maxWidth: 50.0, ); setState(() {}); } return new Scaffold( appBar: new AppBar( title: new Text('Gallery Access'), backgroundColor: Colors.green, actions: <Widget>[ Text("GFG",textScaleFactor: 3,) ], ), body: new Builder( builder: (BuildContext context) { return Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new RaisedButton( child: new Text('Select Image from Gallery'), onPressed: imageSelectorGallery, ), SizedBox( height: 200.0, width: 300.0, child: galleryFile == null ? Center(child: new Text('Sorry nothing selected!!')) : Center(child: new Image.file(galleryFile)), ) ], ), ); }, ), ); }}
Output:
When no image is selected, it will result:
When the button is pressed, it will ask for accessing photos, media, and files on your device as shown below:
When the permission is given to access photos and any image is selected from the gallery, it will be displayed on the screen as shown below:
Explanation:
import image_picker package in main.dart file.
for a gallery image, we have async function imageSelectorGallery() and await for gallery image.
the image will be displayed after loaded.
android
Flutter
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Custom Bottom Navigation Bar
Splash Screen in Flutter
Flutter - Asset Image
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Stack Widget
Flutter - Search Bar | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Aug, 2020"
},
{
"code": null,
"e": 179,
"s": 54,
"text": "We can add images from the gallery using the image_picker package in Flutter. For this, you’ll need to use your real device."
},
{
"code": null,
"e": 242,
"s": 179,
"text": "Follow the below steps to display the images from the gallery:"
},
{
"code": null,
"e": 285,
"s": 242,
"text": "Step 1: Create a new flutter application:"
},
{
"code": null,
"e": 317,
"s": 285,
"text": "flutter create <YOUR_APP_NAME>\n"
},
{
"code": null,
"e": 392,
"s": 317,
"text": "Step 2: Now, delete the code from the main.dart file to add your own code."
},
{
"code": null,
"e": 446,
"s": 392,
"text": "Step 3: Add the dependency to your pubspec.yaml file:"
},
{
"code": null,
"e": 497,
"s": 446,
"text": "Step 4: Use the below code in the main.dart file :"
},
{
"code": null,
"e": 507,
"s": 497,
"text": "main.dart"
},
{
"code": null,
"e": 512,
"s": 507,
"text": "Dart"
},
{
"code": "import 'dart:io';import 'package:flutter/material.dart';import 'package:image_picker/image_picker.dart'; void main() { runApp(new MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new GalleryAccess(), debugShowCheckedModeBanner: false, ); }} class GalleryAccess extends StatefulWidget { @override State<StatefulWidget> createState() { return new GalleryAccessState(); }} class GalleryAccessState extends State<GalleryAccess> { File galleryFile; @override Widget build(BuildContext context) { //display image selected from gallery imageSelectorGallery() async { galleryFile = await ImagePicker.pickImage( source: ImageSource.gallery, // maxHeight: 50.0, // maxWidth: 50.0, ); setState(() {}); } return new Scaffold( appBar: new AppBar( title: new Text('Gallery Access'), backgroundColor: Colors.green, actions: <Widget>[ Text(\"GFG\",textScaleFactor: 3,) ], ), body: new Builder( builder: (BuildContext context) { return Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new RaisedButton( child: new Text('Select Image from Gallery'), onPressed: imageSelectorGallery, ), SizedBox( height: 200.0, width: 300.0, child: galleryFile == null ? Center(child: new Text('Sorry nothing selected!!')) : Center(child: new Image.file(galleryFile)), ) ], ), ); }, ), ); }}",
"e": 2313,
"s": 512,
"text": null
},
{
"code": null,
"e": 2321,
"s": 2313,
"text": "Output:"
},
{
"code": null,
"e": 2364,
"s": 2321,
"text": "When no image is selected, it will result:"
},
{
"code": null,
"e": 2474,
"s": 2364,
"text": "When the button is pressed, it will ask for accessing photos, media, and files on your device as shown below:"
},
{
"code": null,
"e": 2615,
"s": 2474,
"text": "When the permission is given to access photos and any image is selected from the gallery, it will be displayed on the screen as shown below:"
},
{
"code": null,
"e": 2628,
"s": 2615,
"text": "Explanation:"
},
{
"code": null,
"e": 2675,
"s": 2628,
"text": "import image_picker package in main.dart file."
},
{
"code": null,
"e": 2771,
"s": 2675,
"text": "for a gallery image, we have async function imageSelectorGallery() and await for gallery image."
},
{
"code": null,
"e": 2813,
"s": 2771,
"text": "the image will be displayed after loaded."
},
{
"code": null,
"e": 2821,
"s": 2813,
"text": "android"
},
{
"code": null,
"e": 2829,
"s": 2821,
"text": "Flutter"
},
{
"code": null,
"e": 2834,
"s": 2829,
"text": "Dart"
},
{
"code": null,
"e": 2842,
"s": 2834,
"text": "Flutter"
},
{
"code": null,
"e": 2940,
"s": 2842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2972,
"s": 2940,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 3000,
"s": 2972,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 3039,
"s": 3000,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 3064,
"s": 3039,
"text": "Splash Screen in Flutter"
},
{
"code": null,
"e": 3086,
"s": 3064,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 3118,
"s": 3086,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 3157,
"s": 3118,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 3183,
"s": 3157,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 3206,
"s": 3183,
"text": "Flutter - Stack Widget"
}
] |
Writer flush() method in Java with Examples | 29 Jan, 2019
The flush() method of Writer Class in Java is used to flush the writer. By flushing the writer, it means to clear the writer of any element that may be or maybe not inside the writer. It neither accepts any parameter nor returns any value.
Syntax:
public void flush()
Parameters: This method do not accepts any parameter.
Return Value: This method do not returns any value. It just flushes the writer.
Below methods illustrates the working of flush() method:
Program 1:
// Java program to demonstrate// Writer flush() method import java.io.*; class GFG { public static void main(String[] args) { // The string to be written in the writer String str = "GeeksForGeeks"; try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Write the above string to this writer // This will put the string in the writer // till it is printed on the console writer.write(str); // Now clear the writer // using flush() method writer.flush(); } catch (Exception e) { System.out.println(e); } }}
GeeksForGeeks
Program 2:
// Java program to demonstrate// Writer flush() method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Write the char to this writer // This will put the char in the writer // till it is printed on the console writer.write(65); // Now clear the writer // using flush() method writer.flush(); } catch (Exception e) { System.out.println(e); } }}
A
Java-Functions
Java-IO package
Java-Writer
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jan, 2019"
},
{
"code": null,
"e": 294,
"s": 54,
"text": "The flush() method of Writer Class in Java is used to flush the writer. By flushing the writer, it means to clear the writer of any element that may be or maybe not inside the writer. It neither accepts any parameter nor returns any value."
},
{
"code": null,
"e": 302,
"s": 294,
"text": "Syntax:"
},
{
"code": null,
"e": 322,
"s": 302,
"text": "public void flush()"
},
{
"code": null,
"e": 376,
"s": 322,
"text": "Parameters: This method do not accepts any parameter."
},
{
"code": null,
"e": 456,
"s": 376,
"text": "Return Value: This method do not returns any value. It just flushes the writer."
},
{
"code": null,
"e": 513,
"s": 456,
"text": "Below methods illustrates the working of flush() method:"
},
{
"code": null,
"e": 524,
"s": 513,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Writer flush() method import java.io.*; class GFG { public static void main(String[] args) { // The string to be written in the writer String str = \"GeeksForGeeks\"; try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Write the above string to this writer // This will put the string in the writer // till it is printed on the console writer.write(str); // Now clear the writer // using flush() method writer.flush(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1244,
"s": 524,
"text": null
},
{
"code": null,
"e": 1259,
"s": 1244,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 1270,
"s": 1259,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Writer flush() method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a Writer instance Writer writer = new PrintWriter(System.out); // Write the char to this writer // This will put the char in the writer // till it is printed on the console writer.write(65); // Now clear the writer // using flush() method writer.flush(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1891,
"s": 1270,
"text": null
},
{
"code": null,
"e": 1894,
"s": 1891,
"text": "A\n"
},
{
"code": null,
"e": 1909,
"s": 1894,
"text": "Java-Functions"
},
{
"code": null,
"e": 1925,
"s": 1909,
"text": "Java-IO package"
},
{
"code": null,
"e": 1937,
"s": 1925,
"text": "Java-Writer"
},
{
"code": null,
"e": 1942,
"s": 1937,
"text": "Java"
},
{
"code": null,
"e": 1947,
"s": 1942,
"text": "Java"
},
{
"code": null,
"e": 2045,
"s": 1947,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2096,
"s": 2045,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2127,
"s": 2096,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2146,
"s": 2127,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2176,
"s": 2146,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2191,
"s": 2176,
"text": "Stream In Java"
},
{
"code": null,
"e": 2209,
"s": 2191,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2229,
"s": 2209,
"text": "Collections in Java"
},
{
"code": null,
"e": 2253,
"s": 2229,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2285,
"s": 2253,
"text": "Multidimensional Arrays in Java"
}
] |
Student Record System using Java Swing | 11 May, 2022
Consider a scenario of a school where everyday teachers, staff, authorities need to go through the records of their students for various purposes like searching for a particular student’s details. Manually going through records is a tedious job and also time-consuming. Hence, it is better to develop in-school software that allows users to insert, update, search, or delete records without manually going through documents every time a query arises.
In this article, we will see how to quickly create an application using Java Swing to perform operations like create, retrieve, and delete into the database using JDBC.
Before writing the code, a few things need to be kept in mind:
JDBC API: Java Database Connectivity Application Program Interface is a set of interfaces and classes using which you can write Java programs for accessing and manipulating databases. It acts as a communication between the application and the database.JDBC Driver: It enables a Java application to interact with the database. We need to set up different JDBC drivers for different databases.
JDBC API: Java Database Connectivity Application Program Interface is a set of interfaces and classes using which you can write Java programs for accessing and manipulating databases. It acts as a communication between the application and the database.
JDBC Driver: It enables a Java application to interact with the database. We need to set up different JDBC drivers for different databases.
Workflow of a Java application and database interaction through JDBC drivers
Steps to create the application:
1. First, open Netbeans and click on the File option from the menu bar.
2. Now create a new Java application by clicking on New Project -> Java -> Java Application and give a suitable project name and click finish.
3. Now create a new file by going to the File option again on the menu bar, then New File -> Swing GUI Forms -> JFrame Form, and give a suitable file name click finish.
4. After successful file creation, we will now be presented with the following screen. The 3 important parts of this window are:
Design: This is the area where we will create the design/template of our application.
Source: This is where the logic code of the program is written.
Palette: This component contains all the widgets which we need to drag and drop on the design area
Window displayed after successful Java file creation.
5. Now from the palette situated at the right-hand side of the window, start dragging the toolkit widgets.
Drag Components from palette to design area
6. Since we need to display all data in a tabulated form, drag the table widget from the palette onto the design area. Now to set the headings, right-click on the table, select Properties -> Model ->Add/delete Columns.
7. Now let us create the database to store the data. Open MySQL command client, enter password, and type in the following commands to create a new database, new table, and defining the attributes.
mysql> create database student;
Query OK, 1 row affected (0.14 sec)
mysql> use student;
Database changed
mysql> create table record(
-> rollno int(3),
-> name char(20),
-> class int(2),
-> section char(2),
-> address varchar(40));
Query OK, 0 rows affected (2.03 sec)
mysql> describe record;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| rollno | int(3) | YES | | NULL | |
| name | char(20) | YES | | NULL | |
| class | int(2) | YES | | NULL | |
| section | char(2) | YES | | NULL | |
| address | varchar(40) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
5 rows in set (0.03 sec)
Going back to NetBeans, we need to follow these steps for database connectivity:
8. We need to import libraries that are needed to set up a connection with the database and retrieve data which is done by – DriverManager Class, Connection Class, and Statement Class. Thus go to the menubar, under Tools->Libraries, and add MySQL JDBC connector. Note down the Library ClassPath and click OK. Now go to Projects toolbar and go to your application’s Libraries. Right-click and select Add Jar/Library and browse the Library classpath noted down previously.
Add Jar file
Add mysql connector
9. Go to Windows->Services->Databases and enter the required credentials of your MySQL username and password. After clicking test connection, if it’s successful, the connector logo appears connected.
Connection is initially broken
10. Now to type the code, double-click on jButton1 (Insert), you will be directed to the source tab. Here type in the following code.
Java
// Write the import code at topimport java.sql.*;import javax.swing.JOptionPane;import javax.swing.table.DefaultTableModel; public class SchoolRecord extends javax.swing.JFrame { Connection con = null; Statement stmt = null; ResultSet rs = null; // JButton1 Code starts from here try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student", "root", "root"); stmt = con.createStatement(); String rollno = jTextField1.getText(); String name = jTextField2.getText(); String class = jTextField3.getText(); String sec = jTextField4.getText(); String adr = jTextArea1.getText(); String INSERT = "INSERT INTO RECORD VALUES('" + rollno + "','" + name + "','" + class + "','" + sec + "','" + adr + "');"; stmt.executeUpdate(INSERT); JOptionPane.showMessageDialog( this, "Record Added Successfully"); jButton1.setEnabled(true); } catch (Exception e) { JOptionPane.showMessageDialog( this, "Error In Connectivity"); }
In the above code, the following things need to be kept in mind which are:
Connection Class: It acts as a connection session between the Java program and specific database application. It is through which we send SQL queries to the database.Statement Class: A Statement is an interface that represents a SQL statement.ResultSet: When you execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. A Connection object is needed to create a Statement object.JDBC Driver Registration: To open a connection to the database from Java application, the JDBC driver should be registered with the Device Manager. Hence we use forName() of language package. Here com.mysql.jdbc.Driver is the driver name for MySQL..getConnection(): It is used to establish a physical connection to the database by specifying the database name(student) , username(root) and password(root). This creates a connection object.Query Execution: createStatement() creates a statement type object that holds SQL queries. Then executeQuery/executeUpdate method executes the SQL statement. Here it is “INSERT INTO RECORD VALUES....”.Data Extraction: The above method creates a resultset object that contains the resultant data. (Now see the code below) rs is the variable that stores the resultant dataset and hence we use a .get<Type>() method to obtain data.while(rs.next()): (See code below) Since we need data containing multiple rows, we use a loop to access them. The next() method moves the cursor forward by one row.Closing open databases: We close all open databases to clean up the environment. Thus we use- rs.close() , stmt.close() and con.close() methods.
Connection Class: It acts as a connection session between the Java program and specific database application. It is through which we send SQL queries to the database.
Statement Class: A Statement is an interface that represents a SQL statement.
ResultSet: When you execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. A Connection object is needed to create a Statement object.
JDBC Driver Registration: To open a connection to the database from Java application, the JDBC driver should be registered with the Device Manager. Hence we use forName() of language package. Here com.mysql.jdbc.Driver is the driver name for MySQL.
.getConnection(): It is used to establish a physical connection to the database by specifying the database name(student) , username(root) and password(root). This creates a connection object.
Query Execution: createStatement() creates a statement type object that holds SQL queries. Then executeQuery/executeUpdate method executes the SQL statement. Here it is “INSERT INTO RECORD VALUES....”.
Data Extraction: The above method creates a resultset object that contains the resultant data. (Now see the code below) rs is the variable that stores the resultant dataset and hence we use a .get<Type>() method to obtain data.
while(rs.next()): (See code below) Since we need data containing multiple rows, we use a loop to access them. The next() method moves the cursor forward by one row.
Closing open databases: We close all open databases to clean up the environment. Thus we use- rs.close() , stmt.close() and con.close() methods.
11. Now to display all data, write the following code under the jButton2 ActionPerformed option which can be achieved by clicking twice on View Data Button in the design area.
Java
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student", "root", "root"); String query = "SELECT* FROM RECORD;"; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String rollno = rs.getString("rollno"); String name = rs.getString("name"); String class = rs.getString("class"); String sec = rs.getString("section"); String adr = rs.getString("address"); model.addRow( new Object[] { rollno, name, class, sec, adr }); } rs.close(); stmt.close(); con.close();}catch (Exception e) { JOptionPane.showMessageDialog(this, "Error In Connectivity");}
12. Now to clear all textfields, textareas and table content write the following code under the jButton3 ActionPerformed option which can be achieved by clicking twice on Clear Button in the design area.
Java
jTextField1.setText("");jTextField2.setText("");jTextField3.setText("");jTextField4.setText("");jTextArea1.setText("");DefaultTableModel dm = (DefaultTableModel)jTable1.getModel();dm.getDataVector().removeAllElements();jTable1.repaint();
13. Now to exit from the system, add the following statement under the jButton4 ActionPerformed option which can be achieved by clicking twice on Exit Button in the design area.
System.exit(0);
14. After code is typed, right-click anywhere on the screen and select the Run File option from the drop-down menu. The final output is shown below. Input necessary details and the application is ready!
Insert Data
View Data
Output:
varshagumber28
java-swing
mysql
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 480,
"s": 28,
"text": "Consider a scenario of a school where everyday teachers, staff, authorities need to go through the records of their students for various purposes like searching for a particular student’s details. Manually going through records is a tedious job and also time-consuming. Hence, it is better to develop in-school software that allows users to insert, update, search, or delete records without manually going through documents every time a query arises. "
},
{
"code": null,
"e": 649,
"s": 480,
"text": "In this article, we will see how to quickly create an application using Java Swing to perform operations like create, retrieve, and delete into the database using JDBC."
},
{
"code": null,
"e": 712,
"s": 649,
"text": "Before writing the code, a few things need to be kept in mind:"
},
{
"code": null,
"e": 1104,
"s": 712,
"text": "JDBC API: Java Database Connectivity Application Program Interface is a set of interfaces and classes using which you can write Java programs for accessing and manipulating databases. It acts as a communication between the application and the database.JDBC Driver: It enables a Java application to interact with the database. We need to set up different JDBC drivers for different databases."
},
{
"code": null,
"e": 1357,
"s": 1104,
"text": "JDBC API: Java Database Connectivity Application Program Interface is a set of interfaces and classes using which you can write Java programs for accessing and manipulating databases. It acts as a communication between the application and the database."
},
{
"code": null,
"e": 1497,
"s": 1357,
"text": "JDBC Driver: It enables a Java application to interact with the database. We need to set up different JDBC drivers for different databases."
},
{
"code": null,
"e": 1574,
"s": 1497,
"text": "Workflow of a Java application and database interaction through JDBC drivers"
},
{
"code": null,
"e": 1607,
"s": 1574,
"text": "Steps to create the application:"
},
{
"code": null,
"e": 1679,
"s": 1607,
"text": "1. First, open Netbeans and click on the File option from the menu bar."
},
{
"code": null,
"e": 1822,
"s": 1679,
"text": "2. Now create a new Java application by clicking on New Project -> Java -> Java Application and give a suitable project name and click finish."
},
{
"code": null,
"e": 1991,
"s": 1822,
"text": "3. Now create a new file by going to the File option again on the menu bar, then New File -> Swing GUI Forms -> JFrame Form, and give a suitable file name click finish."
},
{
"code": null,
"e": 2120,
"s": 1991,
"text": "4. After successful file creation, we will now be presented with the following screen. The 3 important parts of this window are:"
},
{
"code": null,
"e": 2206,
"s": 2120,
"text": "Design: This is the area where we will create the design/template of our application."
},
{
"code": null,
"e": 2270,
"s": 2206,
"text": "Source: This is where the logic code of the program is written."
},
{
"code": null,
"e": 2369,
"s": 2270,
"text": "Palette: This component contains all the widgets which we need to drag and drop on the design area"
},
{
"code": null,
"e": 2423,
"s": 2369,
"text": "Window displayed after successful Java file creation."
},
{
"code": null,
"e": 2530,
"s": 2423,
"text": "5. Now from the palette situated at the right-hand side of the window, start dragging the toolkit widgets."
},
{
"code": null,
"e": 2574,
"s": 2530,
"text": "Drag Components from palette to design area"
},
{
"code": null,
"e": 2793,
"s": 2574,
"text": "6. Since we need to display all data in a tabulated form, drag the table widget from the palette onto the design area. Now to set the headings, right-click on the table, select Properties -> Model ->Add/delete Columns."
},
{
"code": null,
"e": 2990,
"s": 2793,
"text": "7. Now let us create the database to store the data. Open MySQL command client, enter password, and type in the following commands to create a new database, new table, and defining the attributes."
},
{
"code": null,
"e": 3842,
"s": 2990,
"text": "mysql> create database student;\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> use student;\nDatabase changed\nmysql> create table record(\n -> rollno int(3),\n -> name char(20),\n -> class int(2),\n -> section char(2),\n -> address varchar(40));\nQuery OK, 0 rows affected (2.03 sec)\n\nmysql> describe record;\n+---------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+-------------+------+-----+---------+-------+\n| rollno | int(3) | YES | | NULL | |\n| name | char(20) | YES | | NULL | |\n| class | int(2) | YES | | NULL | |\n| section | char(2) | YES | | NULL | |\n| address | varchar(40) | YES | | NULL | |\n+---------+-------------+------+-----+---------+-------+\n5 rows in set (0.03 sec)"
},
{
"code": null,
"e": 3923,
"s": 3842,
"text": "Going back to NetBeans, we need to follow these steps for database connectivity:"
},
{
"code": null,
"e": 4395,
"s": 3923,
"text": "8. We need to import libraries that are needed to set up a connection with the database and retrieve data which is done by – DriverManager Class, Connection Class, and Statement Class. Thus go to the menubar, under Tools->Libraries, and add MySQL JDBC connector. Note down the Library ClassPath and click OK. Now go to Projects toolbar and go to your application’s Libraries. Right-click and select Add Jar/Library and browse the Library classpath noted down previously."
},
{
"code": null,
"e": 4408,
"s": 4395,
"text": "Add Jar file"
},
{
"code": null,
"e": 4428,
"s": 4408,
"text": "Add mysql connector"
},
{
"code": null,
"e": 4628,
"s": 4428,
"text": "9. Go to Windows->Services->Databases and enter the required credentials of your MySQL username and password. After clicking test connection, if it’s successful, the connector logo appears connected."
},
{
"code": null,
"e": 4659,
"s": 4628,
"text": "Connection is initially broken"
},
{
"code": null,
"e": 4793,
"s": 4659,
"text": "10. Now to type the code, double-click on jButton1 (Insert), you will be directed to the source tab. Here type in the following code."
},
{
"code": null,
"e": 4798,
"s": 4793,
"text": "Java"
},
{
"code": "// Write the import code at topimport java.sql.*;import javax.swing.JOptionPane;import javax.swing.table.DefaultTableModel; public class SchoolRecord extends javax.swing.JFrame { Connection con = null; Statement stmt = null; ResultSet rs = null; // JButton1 Code starts from here try { Class.forName(\"com.mysql.jdbc.Driver\"); Connection con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/student\", \"root\", \"root\"); stmt = con.createStatement(); String rollno = jTextField1.getText(); String name = jTextField2.getText(); String class = jTextField3.getText(); String sec = jTextField4.getText(); String adr = jTextArea1.getText(); String INSERT = \"INSERT INTO RECORD VALUES('\" + rollno + \"','\" + name + \"','\" + class + \"','\" + sec + \"','\" + adr + \"');\"; stmt.executeUpdate(INSERT); JOptionPane.showMessageDialog( this, \"Record Added Successfully\"); jButton1.setEnabled(true); } catch (Exception e) { JOptionPane.showMessageDialog( this, \"Error In Connectivity\"); }",
"e": 6004,
"s": 4798,
"text": null
},
{
"code": null,
"e": 6079,
"s": 6004,
"text": "In the above code, the following things need to be kept in mind which are:"
},
{
"code": null,
"e": 7705,
"s": 6079,
"text": "Connection Class: It acts as a connection session between the Java program and specific database application. It is through which we send SQL queries to the database.Statement Class: A Statement is an interface that represents a SQL statement.ResultSet: When you execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. A Connection object is needed to create a Statement object.JDBC Driver Registration: To open a connection to the database from Java application, the JDBC driver should be registered with the Device Manager. Hence we use forName() of language package. Here com.mysql.jdbc.Driver is the driver name for MySQL..getConnection(): It is used to establish a physical connection to the database by specifying the database name(student) , username(root) and password(root). This creates a connection object.Query Execution: createStatement() creates a statement type object that holds SQL queries. Then executeQuery/executeUpdate method executes the SQL statement. Here it is “INSERT INTO RECORD VALUES....”.Data Extraction: The above method creates a resultset object that contains the resultant data. (Now see the code below) rs is the variable that stores the resultant dataset and hence we use a .get<Type>() method to obtain data.while(rs.next()): (See code below) Since we need data containing multiple rows, we use a loop to access them. The next() method moves the cursor forward by one row.Closing open databases: We close all open databases to clean up the environment. Thus we use- rs.close() , stmt.close() and con.close() methods. "
},
{
"code": null,
"e": 7872,
"s": 7705,
"text": "Connection Class: It acts as a connection session between the Java program and specific database application. It is through which we send SQL queries to the database."
},
{
"code": null,
"e": 7951,
"s": 7872,
"text": "Statement Class: A Statement is an interface that represents a SQL statement."
},
{
"code": null,
"e": 8156,
"s": 7951,
"text": "ResultSet: When you execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. A Connection object is needed to create a Statement object."
},
{
"code": null,
"e": 8405,
"s": 8156,
"text": "JDBC Driver Registration: To open a connection to the database from Java application, the JDBC driver should be registered with the Device Manager. Hence we use forName() of language package. Here com.mysql.jdbc.Driver is the driver name for MySQL."
},
{
"code": null,
"e": 8598,
"s": 8405,
"text": ".getConnection(): It is used to establish a physical connection to the database by specifying the database name(student) , username(root) and password(root). This creates a connection object."
},
{
"code": null,
"e": 8800,
"s": 8598,
"text": "Query Execution: createStatement() creates a statement type object that holds SQL queries. Then executeQuery/executeUpdate method executes the SQL statement. Here it is “INSERT INTO RECORD VALUES....”."
},
{
"code": null,
"e": 9028,
"s": 8800,
"text": "Data Extraction: The above method creates a resultset object that contains the resultant data. (Now see the code below) rs is the variable that stores the resultant dataset and hence we use a .get<Type>() method to obtain data."
},
{
"code": null,
"e": 9193,
"s": 9028,
"text": "while(rs.next()): (See code below) Since we need data containing multiple rows, we use a loop to access them. The next() method moves the cursor forward by one row."
},
{
"code": null,
"e": 9339,
"s": 9193,
"text": "Closing open databases: We close all open databases to clean up the environment. Thus we use- rs.close() , stmt.close() and con.close() methods. "
},
{
"code": null,
"e": 9515,
"s": 9339,
"text": "11. Now to display all data, write the following code under the jButton2 ActionPerformed option which can be achieved by clicking twice on View Data Button in the design area."
},
{
"code": null,
"e": 9520,
"s": 9515,
"text": "Java"
},
{
"code": "DefaultTableModel model = (DefaultTableModel)jTable1.getModel();try { Class.forName(\"com.mysql.jdbc.Driver\"); Connection con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/student\", \"root\", \"root\"); String query = \"SELECT* FROM RECORD;\"; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String rollno = rs.getString(\"rollno\"); String name = rs.getString(\"name\"); String class = rs.getString(\"class\"); String sec = rs.getString(\"section\"); String adr = rs.getString(\"address\"); model.addRow( new Object[] { rollno, name, class, sec, adr }); } rs.close(); stmt.close(); con.close();}catch (Exception e) { JOptionPane.showMessageDialog(this, \"Error In Connectivity\");}",
"e": 10344,
"s": 9520,
"text": null
},
{
"code": null,
"e": 10550,
"s": 10346,
"text": "12. Now to clear all textfields, textareas and table content write the following code under the jButton3 ActionPerformed option which can be achieved by clicking twice on Clear Button in the design area."
},
{
"code": null,
"e": 10555,
"s": 10550,
"text": "Java"
},
{
"code": "jTextField1.setText(\"\");jTextField2.setText(\"\");jTextField3.setText(\"\");jTextField4.setText(\"\");jTextArea1.setText(\"\");DefaultTableModel dm = (DefaultTableModel)jTable1.getModel();dm.getDataVector().removeAllElements();jTable1.repaint();",
"e": 10796,
"s": 10555,
"text": null
},
{
"code": null,
"e": 10976,
"s": 10798,
"text": "13. Now to exit from the system, add the following statement under the jButton4 ActionPerformed option which can be achieved by clicking twice on Exit Button in the design area."
},
{
"code": null,
"e": 10992,
"s": 10976,
"text": "System.exit(0);"
},
{
"code": null,
"e": 11195,
"s": 10992,
"text": "14. After code is typed, right-click anywhere on the screen and select the Run File option from the drop-down menu. The final output is shown below. Input necessary details and the application is ready!"
},
{
"code": null,
"e": 11207,
"s": 11195,
"text": "Insert Data"
},
{
"code": null,
"e": 11217,
"s": 11207,
"text": "View Data"
},
{
"code": null,
"e": 11225,
"s": 11217,
"text": "Output:"
},
{
"code": null,
"e": 11240,
"s": 11225,
"text": "varshagumber28"
},
{
"code": null,
"e": 11251,
"s": 11240,
"text": "java-swing"
},
{
"code": null,
"e": 11257,
"s": 11251,
"text": "mysql"
},
{
"code": null,
"e": 11262,
"s": 11257,
"text": "Java"
},
{
"code": null,
"e": 11267,
"s": 11262,
"text": "Java"
}
] |
How to find common elements between two Vector using STL in C++? | 19 Mar, 2019
Given two vectors, find common elements between these two vectors using STL in C++.
Example:
Input:vec1 = {1, 45, 54, 71, 76, 12},vec2 = {1, 7, 5, 4, 6, 12}Output: {1, 12}
Input:vec1 = {1, 7, 5, 4, 6, 12},vec2 = {10, 12, 11}Output: {1, 4, 12}
Approach: Common elements can be found with the help of set_intersection() function provided in STL.
Syntax:
set_intersection (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
// C++ program to find common elements// between two Vectors using STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> vector1 = { 1, 45, 54, 71, 76, 12 }; vector<int> vector2 = { 1, 7, 5, 4, 6, 12 }; // Sort the vector sort(vector1.begin(), vector1.end()); sort(vector2.begin(), vector2.end()); // Print the vector cout << "First Vector: "; for (int i = 0; i < vector1.size(); i++) cout << vector1[i] << " "; cout << endl; cout << "Second Vector: "; for (int i = 0; i < vector2.size(); i++) cout << vector2[i] << " "; cout << endl; // Initialise a vector // to store the common values // and an iterator // to traverse this vector vector<int> v(vector1.size() + vector2.size()); vector<int>::iterator it, st; it = set_intersection(vector1.begin(), vector1.end(), vector2.begin(), vector2.end(), v.begin()); cout << "\nCommon elements:\n"; for (st = v.begin(); st != it; ++st) cout << *st << ", "; cout << '\n'; return 0;}
First Vector: 1 12 45 54 71 76
Second Vector: 1 4 5 6 7 12
Common elements:
1, 12,
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Mar, 2019"
},
{
"code": null,
"e": 112,
"s": 28,
"text": "Given two vectors, find common elements between these two vectors using STL in C++."
},
{
"code": null,
"e": 121,
"s": 112,
"text": "Example:"
},
{
"code": null,
"e": 200,
"s": 121,
"text": "Input:vec1 = {1, 45, 54, 71, 76, 12},vec2 = {1, 7, 5, 4, 6, 12}Output: {1, 12}"
},
{
"code": null,
"e": 271,
"s": 200,
"text": "Input:vec1 = {1, 7, 5, 4, 6, 12},vec2 = {10, 12, 11}Output: {1, 4, 12}"
},
{
"code": null,
"e": 372,
"s": 271,
"text": "Approach: Common elements can be found with the help of set_intersection() function provided in STL."
},
{
"code": null,
"e": 380,
"s": 372,
"text": "Syntax:"
},
{
"code": null,
"e": 535,
"s": 380,
"text": "set_intersection (InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2,\n OutputIterator result);\n"
},
{
"code": "// C++ program to find common elements// between two Vectors using STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> vector1 = { 1, 45, 54, 71, 76, 12 }; vector<int> vector2 = { 1, 7, 5, 4, 6, 12 }; // Sort the vector sort(vector1.begin(), vector1.end()); sort(vector2.begin(), vector2.end()); // Print the vector cout << \"First Vector: \"; for (int i = 0; i < vector1.size(); i++) cout << vector1[i] << \" \"; cout << endl; cout << \"Second Vector: \"; for (int i = 0; i < vector2.size(); i++) cout << vector2[i] << \" \"; cout << endl; // Initialise a vector // to store the common values // and an iterator // to traverse this vector vector<int> v(vector1.size() + vector2.size()); vector<int>::iterator it, st; it = set_intersection(vector1.begin(), vector1.end(), vector2.begin(), vector2.end(), v.begin()); cout << \"\\nCommon elements:\\n\"; for (st = v.begin(); st != it; ++st) cout << *st << \", \"; cout << '\\n'; return 0;}",
"e": 1708,
"s": 535,
"text": null
},
{
"code": null,
"e": 1795,
"s": 1708,
"text": "First Vector: 1 12 45 54 71 76 \nSecond Vector: 1 4 5 6 7 12 \n\nCommon elements:\n1, 12,\n"
},
{
"code": null,
"e": 1806,
"s": 1795,
"text": "cpp-vector"
},
{
"code": null,
"e": 1810,
"s": 1806,
"text": "STL"
},
{
"code": null,
"e": 1814,
"s": 1810,
"text": "C++"
},
{
"code": null,
"e": 1818,
"s": 1814,
"text": "STL"
},
{
"code": null,
"e": 1822,
"s": 1818,
"text": "CPP"
}
] |
Juspay Interview Experience | 08 Dec, 2021
Round 1: It was an online round hosted of Juspay on Talscale. It consisted of 3 coding question. The coding question goes like this:
Maximum Weight NodeGiven a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.The task is to find the node number of maximum weight node(Weight of the node is the sum of node numbers of all nodes pointing to that node).Note: The cells are named with an integer value from 0 to N-1. If there is no node pointing to the ith node then weight of the ith node is zero.Example 1:Input:N = 4
Edge[] = {2, 0, -1, 2}Output: 2Explanation:1 -> 0 -> 2 <- 3
weight of 0th cell = 1+2 = 3
weight of 1st cell = 0
(because there is no node
pointing to the 1st cell)
weight of 2nd cell = 0+3 = 3
weight of 3rd cell = 0
There are two cells which has maximum weight
(i.e 0 and 3) Cell 3 has maximum value.Example 2:Input:N = 1
Edge[] = {-1}Output:0Explanation:weight of 0th cell is 0.
There is only one node so
cell 0 has maximum weight.Largest Sum CycleGiven a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.The task is to calculate the sum of the largest sum cycle in the maze(Sum of a cycle is the sum of node number of all nodes in that cycle).Note: The cells are named with an integer value from 0 to N-1. If there is no cycle in the graph then return -1.Example 1:Input:N = 4
Edge[] = {1, 2, 0, -1}Output:3Explanation:There is only one cycle in the graph.
(i.e 0->1->2->0)
Sum of the node number in that cycle
= 0 + 1 + 2 = 3.Example 2:Input:N = 4
Edge[] = {2, 0, -1, 2}Output: -1Explanation:1 -> 0 -> 2 <- 3
There is no cycle in the graph.
Maximum Weight NodeGiven a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.The task is to find the node number of maximum weight node(Weight of the node is the sum of node numbers of all nodes pointing to that node).Note: The cells are named with an integer value from 0 to N-1. If there is no node pointing to the ith node then weight of the ith node is zero.Example 1:Input:N = 4
Edge[] = {2, 0, -1, 2}Output: 2Explanation:1 -> 0 -> 2 <- 3
weight of 0th cell = 1+2 = 3
weight of 1st cell = 0
(because there is no node
pointing to the 1st cell)
weight of 2nd cell = 0+3 = 3
weight of 3rd cell = 0
There are two cells which has maximum weight
(i.e 0 and 3) Cell 3 has maximum value.Example 2:Input:N = 1
Edge[] = {-1}Output:0Explanation:weight of 0th cell is 0.
There is only one node so
cell 0 has maximum weight.
Given a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).
You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.
The task is to find the node number of maximum weight node(Weight of the node is the sum of node numbers of all nodes pointing to that node).
Note: The cells are named with an integer value from 0 to N-1. If there is no node pointing to the ith node then weight of the ith node is zero.
Example 1:
Input:
N = 4
Edge[] = {2, 0, -1, 2}
Output:
2
Explanation:
1 -> 0 -> 2 <- 3
weight of 0th cell = 1+2 = 3
weight of 1st cell = 0
(because there is no node
pointing to the 1st cell)
weight of 2nd cell = 0+3 = 3
weight of 3rd cell = 0
There are two cells which has maximum weight
(i.e 0 and 3) Cell 3 has maximum value.
Example 2:
Input:
N = 1
Edge[] = {-1}
Output:
0
Explanation:
weight of 0th cell is 0.
There is only one node so
cell 0 has maximum weight.
Largest Sum CycleGiven a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.The task is to calculate the sum of the largest sum cycle in the maze(Sum of a cycle is the sum of node number of all nodes in that cycle).Note: The cells are named with an integer value from 0 to N-1. If there is no cycle in the graph then return -1.Example 1:Input:N = 4
Edge[] = {1, 2, 0, -1}Output:3Explanation:There is only one cycle in the graph.
(i.e 0->1->2->0)
Sum of the node number in that cycle
= 0 + 1 + 2 = 3.Example 2:Input:N = 4
Edge[] = {2, 0, -1, 2}Output: -1Explanation:1 -> 0 -> 2 <- 3
There is no cycle in the graph.
Given a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).
You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.
The task is to calculate the sum of the largest sum cycle in the maze(Sum of a cycle is the sum of node number of all nodes in that cycle).
Note: The cells are named with an integer value from 0 to N-1. If there is no cycle in the graph then return -1.
Example 1:
Input:
N = 4
Edge[] = {1, 2, 0, -1}
Output:
3
Explanation:
There is only one cycle in the graph.
(i.e 0->1->2->0)
Sum of the node number in that cycle
= 0 + 1 + 2 = 3.
Example 2:
Input:
N = 4
Edge[] = {2, 0, -1, 2}
Output:
-1
Explanation:
1 -> 0 -> 2 <- 3
There is no cycle in the graph.
Juspay
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
Amazon Interview Experience SDE-2 (3 Years Experienced)
TCS Ninja Interview Experience (2020 batch)
Write It Up: Share Your Interview Experiences
Samsung RnD Coding Round Questions
Nagarro Interview Experience
Amazon Interview Experience for SDE-1
Nagarro Interview Experience | On-Campus 2021 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 188,
"s": 54,
"text": "Round 1: It was an online round hosted of Juspay on Talscale. It consisted of 3 coding question. The coding question goes like this:"
},
{
"code": null,
"e": 2178,
"s": 188,
"text": "Maximum Weight NodeGiven a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.The task is to find the node number of maximum weight node(Weight of the node is the sum of node numbers of all nodes pointing to that node).Note: The cells are named with an integer value from 0 to N-1. If there is no node pointing to the ith node then weight of the ith node is zero.Example 1:Input:N = 4\nEdge[] = {2, 0, -1, 2}Output: 2Explanation:1 -> 0 -> 2 <- 3\nweight of 0th cell = 1+2 = 3\nweight of 1st cell = 0\n(because there is no node \npointing to the 1st cell)\nweight of 2nd cell = 0+3 = 3\nweight of 3rd cell = 0\nThere are two cells which has maximum weight\n(i.e 0 and 3) Cell 3 has maximum value.Example 2:Input:N = 1\nEdge[] = {-1}Output:0Explanation:weight of 0th cell is 0.\nThere is only one node so\ncell 0 has maximum weight.Largest Sum CycleGiven a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.The task is to calculate the sum of the largest sum cycle in the maze(Sum of a cycle is the sum of node number of all nodes in that cycle).Note: The cells are named with an integer value from 0 to N-1. If there is no cycle in the graph then return -1.Example 1:Input:N = 4\nEdge[] = {1, 2, 0, -1}Output:3Explanation:There is only one cycle in the graph.\n(i.e 0->1->2->0)\nSum of the node number in that cycle\n= 0 + 1 + 2 = 3.Example 2:Input:N = 4\nEdge[] = {2, 0, -1, 2}Output: -1Explanation:1 -> 0 -> 2 <- 3\nThere is no cycle in the graph."
},
{
"code": null,
"e": 3276,
"s": 2178,
"text": "Maximum Weight NodeGiven a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.The task is to find the node number of maximum weight node(Weight of the node is the sum of node numbers of all nodes pointing to that node).Note: The cells are named with an integer value from 0 to N-1. If there is no node pointing to the ith node then weight of the ith node is zero.Example 1:Input:N = 4\nEdge[] = {2, 0, -1, 2}Output: 2Explanation:1 -> 0 -> 2 <- 3\nweight of 0th cell = 1+2 = 3\nweight of 1st cell = 0\n(because there is no node \npointing to the 1st cell)\nweight of 2nd cell = 0+3 = 3\nweight of 3rd cell = 0\nThere are two cells which has maximum weight\n(i.e 0 and 3) Cell 3 has maximum value.Example 2:Input:N = 1\nEdge[] = {-1}Output:0Explanation:weight of 0th cell is 0.\nThere is only one node so\ncell 0 has maximum weight."
},
{
"code": null,
"e": 3432,
"s": 3276,
"text": "Given a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves)."
},
{
"code": null,
"e": 3616,
"s": 3432,
"text": "You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit."
},
{
"code": null,
"e": 3758,
"s": 3616,
"text": "The task is to find the node number of maximum weight node(Weight of the node is the sum of node numbers of all nodes pointing to that node)."
},
{
"code": null,
"e": 3903,
"s": 3758,
"text": "Note: The cells are named with an integer value from 0 to N-1. If there is no node pointing to the ith node then weight of the ith node is zero."
},
{
"code": null,
"e": 3914,
"s": 3903,
"text": "Example 1:"
},
{
"code": null,
"e": 3921,
"s": 3914,
"text": "Input:"
},
{
"code": null,
"e": 3950,
"s": 3921,
"text": "N = 4\nEdge[] = {2, 0, -1, 2}"
},
{
"code": null,
"e": 3959,
"s": 3950,
"text": "Output: "
},
{
"code": null,
"e": 3961,
"s": 3959,
"text": "2"
},
{
"code": null,
"e": 3974,
"s": 3961,
"text": "Explanation:"
},
{
"code": null,
"e": 4233,
"s": 3974,
"text": "1 -> 0 -> 2 <- 3\nweight of 0th cell = 1+2 = 3\nweight of 1st cell = 0\n(because there is no node \npointing to the 1st cell)\nweight of 2nd cell = 0+3 = 3\nweight of 3rd cell = 0\nThere are two cells which has maximum weight\n(i.e 0 and 3) Cell 3 has maximum value."
},
{
"code": null,
"e": 4244,
"s": 4233,
"text": "Example 2:"
},
{
"code": null,
"e": 4251,
"s": 4244,
"text": "Input:"
},
{
"code": null,
"e": 4271,
"s": 4251,
"text": "N = 1\nEdge[] = {-1}"
},
{
"code": null,
"e": 4279,
"s": 4271,
"text": "Output:"
},
{
"code": null,
"e": 4281,
"s": 4279,
"text": "0"
},
{
"code": null,
"e": 4294,
"s": 4281,
"text": "Explanation:"
},
{
"code": null,
"e": 4372,
"s": 4294,
"text": "weight of 0th cell is 0.\nThere is only one node so\ncell 0 has maximum weight."
},
{
"code": null,
"e": 5265,
"s": 4372,
"text": "Largest Sum CycleGiven a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit.The task is to calculate the sum of the largest sum cycle in the maze(Sum of a cycle is the sum of node number of all nodes in that cycle).Note: The cells are named with an integer value from 0 to N-1. If there is no cycle in the graph then return -1.Example 1:Input:N = 4\nEdge[] = {1, 2, 0, -1}Output:3Explanation:There is only one cycle in the graph.\n(i.e 0->1->2->0)\nSum of the node number in that cycle\n= 0 + 1 + 2 = 3.Example 2:Input:N = 4\nEdge[] = {2, 0, -1, 2}Output: -1Explanation:1 -> 0 -> 2 <- 3\nThere is no cycle in the graph."
},
{
"code": null,
"e": 5421,
"s": 5265,
"text": "Given a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves)."
},
{
"code": null,
"e": 5605,
"s": 5421,
"text": "You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn’t have an exit."
},
{
"code": null,
"e": 5745,
"s": 5605,
"text": "The task is to calculate the sum of the largest sum cycle in the maze(Sum of a cycle is the sum of node number of all nodes in that cycle)."
},
{
"code": null,
"e": 5858,
"s": 5745,
"text": "Note: The cells are named with an integer value from 0 to N-1. If there is no cycle in the graph then return -1."
},
{
"code": null,
"e": 5869,
"s": 5858,
"text": "Example 1:"
},
{
"code": null,
"e": 5876,
"s": 5869,
"text": "Input:"
},
{
"code": null,
"e": 5905,
"s": 5876,
"text": "N = 4\nEdge[] = {1, 2, 0, -1}"
},
{
"code": null,
"e": 5913,
"s": 5905,
"text": "Output:"
},
{
"code": null,
"e": 5915,
"s": 5913,
"text": "3"
},
{
"code": null,
"e": 5928,
"s": 5915,
"text": "Explanation:"
},
{
"code": null,
"e": 6037,
"s": 5928,
"text": "There is only one cycle in the graph.\n(i.e 0->1->2->0)\nSum of the node number in that cycle\n= 0 + 1 + 2 = 3."
},
{
"code": null,
"e": 6048,
"s": 6037,
"text": "Example 2:"
},
{
"code": null,
"e": 6055,
"s": 6048,
"text": "Input:"
},
{
"code": null,
"e": 6084,
"s": 6055,
"text": "N = 4\nEdge[] = {2, 0, -1, 2}"
},
{
"code": null,
"e": 6093,
"s": 6084,
"text": "Output: "
},
{
"code": null,
"e": 6096,
"s": 6093,
"text": "-1"
},
{
"code": null,
"e": 6109,
"s": 6096,
"text": "Explanation:"
},
{
"code": null,
"e": 6158,
"s": 6109,
"text": "1 -> 0 -> 2 <- 3\nThere is no cycle in the graph."
},
{
"code": null,
"e": 6165,
"s": 6158,
"text": "Juspay"
},
{
"code": null,
"e": 6187,
"s": 6165,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6285,
"s": 6187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6355,
"s": 6285,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 6428,
"s": 6355,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 6466,
"s": 6428,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 6522,
"s": 6466,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 6566,
"s": 6522,
"text": "TCS Ninja Interview Experience (2020 batch)"
},
{
"code": null,
"e": 6612,
"s": 6566,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 6647,
"s": 6612,
"text": "Samsung RnD Coding Round Questions"
},
{
"code": null,
"e": 6676,
"s": 6647,
"text": "Nagarro Interview Experience"
},
{
"code": null,
"e": 6714,
"s": 6676,
"text": "Amazon Interview Experience for SDE-1"
}
] |
Open-Source Reporting Tools Worth A Look | by Mike Wolfe | Towards Data Science | While thinking of the world of Reporting services, I wondered if there were any open-source Reporting tools. Being open-source would allow for more customization but was also a generally interesting topic. When I finally got to searching the web about it, I found it wasn’t just a single open-source Reporting Tool. Instead, there was quite a variety of options. There were lists of which tools were the best to use. Now, for the most part, quite a few of the Reporting services ended up over-lapping on lists. But some were more unique. I’m sure everyone has their own preferences.
Instead of going through all the options, I chose five to do more research on. However, this does not mean that these five are better than any other options. But it may be an interesting dive into some powerful and open-source tools.
SpagoBI
The first Business Intelligence suite we will be looking at is SpagoBI. It is an open-source suite with a variety of analytic tools. Not only does SpagoBI support reporting, but also Multidimensional analysis (OLAP), the creation of charts, SPIs, interactive cockpits, ad-hoc reporting, location intelligence (such as web mapping services), free inquiry, data mining, network analysis, ETL, collaboration, office automation, master data management, and even external analytical processes that can run in the background. For different user needs, SpagoBI has different main modules. This includes SpagoBI Server, Studio, Meta, SDK, and Applications. This allows business users, developers, decision-makers, and administrators to find a use for SpagoBI. It also supports a list of analytical engines and certified environments.
SpagoBI was written in Java, uses the Ext JS framework, and is open for studying, using, or even modifying the software for more customized usage. The suite uses a Mozilla Public License, which means the components can modify and redistribute modified copies.
In later updates, in 2017, SpagoBI evolved into KNOWAGE. This is a more modern and mature version of business intelligence, with more advanced analysis options and even big data. KNOWAGE advances the original options of SpagoBI, which caters to big data, smart intelligence, enterprise reporting, location intelligence, performance management, and predictive analysis. With KNOWAGE, there is both a community edition and an enterprise edition.
Another item of interest, more specifically interesting to me, is that a version of SpagoBI can be found on Docker Hub. As I’m trying to use Docker more often, you can expect to see more about SpagoBI using Docker here in the future. For now, you can use Docker to pull the SpagoBI version by using the following command:
sudo docker pull spagobilabs/spagobi
To Download from the KNOWAGE suite page, as the SpagoBI download will route you to KNOWAGE, you first make an account. Without an account, I found the download page just leads to a 404 Page Not Found. I did start making an account, but I admit I was a little impatient waiting to verify the account for registration. I would much rather try out the Docker version. But that will be for another day so that we can take a deeper dive. That will be when we can fully explore the features and not just the specifics.
As a note, I did end up receiving the verification email an hour or two after I attempted to sign up. Maybe I will revisit that later, but I would be more interested in seeing the Docker version for now anyway, so at least at this time I won’t try installing the regular version. If you decide to install KNOWAGE, but aware that the verification email during sign-up takes a while to receive, so you won’t be able to install KNOWAGE right away. Because I did not revisit, I can’t guarantee you still won’t get the 404 Page Not Found error, but if you tried it out feel free to let me know if in the comments if having an account helped the download to work.
Seal Report
Not a typical data visualization report, Seal Report is more of a tool that is written in C# using the .NET Framework. Seal Report is also open-source. The framework can be used to produce reports for any type of database, whether that source is SQL or NoSQL based. Seal Report focuses on being installed and building reports both quickly and easily. All the entities of Seal Report are stored in the Seal Repository, which includes data sources, devices, and reports. Seal Report’s main components include the Server Manager, the Report Designer, the Web Report Server, the Task Scheduler, and the Seal Report Scheduler. Together, these allow timed reports, such as daily reports.
The repository folders of Seal Report, necessary to run, include assemblies, databases, devices, logs, reports, security, settings, sources, table templates, special folders, sub-reports, and views. These all are used to create a simple but comprehensive report.
The main features include Dynamic SQL sources, LINQ queries, Native Pivot Tables, HTML 5 Charts, KPI and Widget Views, Full responsive HTML Rendering using Razor engine, Web Report Server, Report scheduler, Drill Down navigation and Sub Reports, Report Tasks, and Low TCO (total cost of ownership).
Again, I searched on Docker Hub to see if Seal Report was available. It seems that Seal Report is available on Docker to pull, however, I found issues. This is the command that Docker says to use:
sudo docker pull eesysite/seal-report
So, when you look at eesy/seal-report in Docker, there are no pulls. When I tried:
Considering there are no pulls, I am wondering if something was set up wrong, or if it just simply does not work.
To download normally, you are directed to the GitHub code. From there, you can directly download the source code. You can then run the executable file on the computer. From there, you can compile using Visual Studio when you open the Seal.sln solution file from the root directory of the tool.
While trying to learn how to use Seal Report, there are tutorials right on the Seal Report website. It first teaches you how to generate a report from a SQL Select statement. This is used to prepare a report in a few quick and easy steps. Once executed, you can save the report to the repository.
The next set of instructions shows how to create the first Data Source. It also instructs how to create, execute, and store the report. Once you have the source and report set up and ready, you can then publish.
There are two sets of instructions for publication, depending on where you want the report to be. The first is on Linux (Ubuntu). That would be applicable for me as that is what I use. The other is on Azure. With Azure, there are also instructions on how to Audit the database.
The final set of instructions is to set up the Seal Report Scheduler. This way, you will not have to manually create the reports each time. Instead, you can set up the scheduler to automatically generate a report at a particular time.
QueryTree
QueryTree is an open-source solution written in C#, ASP.NET, and JavaScript. The tool is targeted for ad hoc reporting and visualization. Found on GitHub, it can be run using the Source, or it can be run using Binaries or even Docker. QueryTree is geared to work with Microsoft SQL Server, MySQL, or a PostgreSQL database. This tool is geared for both technical and non-technical users. QueryTree makes it easy for non-technical users to select, filter, group, aggregate, and visualize data from the tables in the database. It can even create interactive charts to visualize the data without writing any code to do so.
QueryTree is a form of a drag-and-drop builder, which allows for non-technical users a variety of visualization options without writing any code. These reports can also be scheduled to generate for viewing on either the web or on mobile. The drag-and-drop builder includes and powerful and flexible interface that allows the queries to generate reports based on what the user selects. This also means that data sets can be joined, transformed, or simply viewed using QueryTree’s easy-to-use visualization tools.
When viewing the data, QueryTree includes a Sort tool and a Select tool, which can be used to organize the data or to remove any information that may not be consistent. There are also a few different chart options, so the user can select which chart they would like to view the data on. QueryTree also allows the charts to be exported as opposed to only being able to save the chart. This way, the data may be represented in other tools such as Excel or Word.
As reports are scheduled and generated, QueryTree also gives the ability to invite teammates to view those scheduled reports. QueryTree also allows secure encrypted connections to access the database and connects with read-only access, so the data would be safe. This way, reports can be shared with teammates for a better experience.
For more complex options, Query Tree offers an Advanced Report Builder. This includes the same functionality as the Simple Report Builder, but with more tools and options for customization. These reports are more complex, so may dig deeper into the database. Along with the standard drag-and-drop option, the Advanced Report Builder also utilizes a simple wizard to comprehensively visualize the desired data. Like the others we have discussed, QueryTree is open-source and free to use, but also comes with a customizable support plan for enterprise customers. For non-enterprise users, Github has community support on the QueryTree project.
As previously mentioned, QueryTree is available with Docker:
sudo docker pull d4software/querytree
QueryTree is another open-source ad-hoc reporting tool that I think would be interesting to use, so later down the road we’ll attempt using it further with Docker.
FineReport
FineReport is an open-source BI Reporting and Dashboard Software. Unlike some of the others, FineReport is a web-based tool. The design of it is modeled after Excel, so it is easy to work with for beginners. FineReport can be deployed locally or can be connected to corporate databases. Almost all database types are supported by FineReport. It is written in Java and free for personal use but looks like there may be fees when using FineReport for corporate purposes.
The detail for the reports and dashboard aims for innovative design patterns, fast data integration, cool data visualization (with dynamic and even 3D effects), small data entry, powerful decision-making platforms, and both easy deployment and integration. FineReport is written in Java, which means it can be implemented with different systems either through independent or embedded deployment.
FineReport can be used to visualize reports, dashboards, financial statements, developing purchase, sales, inventory systems, and more. The tool also has different use cases. One cause is business users, in which they may need to display reports of data, or FineReport can be used for fast and easy data entry. The next user case is middle-level managers. Supervisors such as this would need the ability to generate and display reports, export that analysis (for presentations such as in a PDF format or in Excel), or even for mandatory data attention in scenarios where certain data needs to be monitored and reviewed in a timely manner. This is where FineReport allows a scheduled report to be generated which can push the reports to the users through emails, or by other selected means. The final user case considered is senior management. In this case, managers need to be able to view data, such as with a dashboard, but they must also be able to visualize data anywhere, such as on mobile, and they must also be able to analyze data, such as with linkage or drilling.
FineReport was created as more of a professional big data BI and analytics platform. It specializes in analytics, so it is, therefore, more IT-centric. Although business users can use FineReport, the full functionality is centered for IT individuals. This is also because most users have basic SQL knowledge when using the reports. FineReport does have several different versions which are geared towards different individuals. As stated before, FineReport is centered around the typical IT user. FineBI is positioned to be used by more business users or data analysts. JDY is a no-code aPaaS (Application Platform as a Service) solution which can be used by both business users and IT to enhance productivity. However, JDY can be used by the entire staff, as there is no code involved. However, we are only looking at FineReport for now.
Like the others, there is a version of FineReport that can be found on Docker:
Now that we have that ready, maybe we’ll take a deeper dive into FineReport in the future.
ReportLab
ReportLab is an open-source engine used to create complex PDF documents and customized vector graphs. It is part of the standard Linux distributions, is embedded in a variety of different products, and even was selected to function as the print/export feature for Wikipedia. ReportLab is free to use and was also written in Python.
ReportLab is broken into three main layers. The first layer a graphics canvas API that “draws” PDF pages. The second layer is a charts and widgets library that can be used to create reusable data graphics. The final layer is the page layout engine, which is used to build documents from different elements such as headlines, paragraphs, fonts, tables, and vector graphs. The page layout engine is PLATYPUS (Page Layout and Typography Using Scripts). ReportLab also has a PLUS commercial product, which generates PDFs at a higher speed and also allows the use of ReportLab’s XML-based templating language RML. ReportLab PLUS also includes upgrades to the open-source library that enable a faster development cycle.
With just the standard ReportLab open-source engine, it is a free PDF toolkit, can automate document production, generate multiple PDFs quickly, has a Diagra charting toolkit, and reduce paperwork and print costs. The ReportLab Toolkit, which is the free version, is a library used to programmatically create PDF documents. The features of the toolkit are to create professional portable documents, use the real document layout engine (Platypus), flowable objects such as headlines or paragraphs, but ReportLab Toolkit also supports embedded Type-1 or TIF fonts, Asian, Hebrew, and Arabic characters, bitmap images in any popular format, vector graphics, it includes a library of reusable primitive shapes, an extensible widget library, a layered architecture written in Python, it also includes simple demos and more complex tools, allows for any data sources, fully available source code, strong community support, and is also platform-independent.
Because it is written in Python, you can install using the source code, or using pip from PYPI. Although available on Linux, ReportLab is cross-platform and is available on Windows, Mac OSX, Solaris, AIX, FreeBSD, and so on.
Unlike the other open-source tools on this list, ReportLab is not found on Docker. But because it can be installed using Pip from PYPI, we will install it that way:
sudo pip3 install reportlab
Even though ReportLab wasn’t found on Docker, you know I have a soft spot for my Python projects. So. expect to see more from me on using ReportLab in the future. It seems like a powerful toolkit, but I’m also enjoying the fact that it was written in Python.
Conclusion
In this article, we reviewed five different open-source engines/toolkits for reporting. Of the five, four of them had versions available on Docker. As I had stated in the beginning, this was not a breakdown of the “best” open-source engines. Instead, this was more of an educational breakdown to appease my own curiosity. The inspiration was just wondering if there were any open-source reporting tools, so I was pleasantly surprised to see that there were so many.
We learned about SpagoBI, Seal Report, QueryTree, FineReport, and ReportLab. Of all, only ReportLab was not found on Docker. However, ReportLab was also the only Python-driven toolkit and was available by installing with Pip, so don’t count that out just yet.
In our research, we only got general background information for each of the reporting tools. However, we didn’t get a chance to attempt generating reports with any of them yet. This is something I would be interested in doing. Now as a note, there are several “best open-source reporting tools” on the web, and although there is overlap for many, there are still many others that I did not list in this overview. This by no means is implying that these are the best five, they were just the five that I found a little bit more interest in learning more about. In the future, I plan to use at least a few of these reporting tools and to learn a little more about how to use them. What may be interesting is, after they have all been tried, revisit all tools I chose in a comparison format. If you use any open-source reporting tools that you think would be worth looking into, feel free to drop them in the comments and I’d be rather interested in looking. Overall, I thought it was interesting to see how similar and yet different these open-source reporting services can be, where some do seek to earn a profit through advanced features, yet while others remain free for use by all users including for company use.
Later on, we will be taking deeper dives into each on the list, but until then, cheers!
Read all my articles for free with my weekly newsletter, thanks!
Want to read all articles on Medium? Become a Medium member today!
Check out my recent articles: | [
{
"code": null,
"e": 755,
"s": 172,
"text": "While thinking of the world of Reporting services, I wondered if there were any open-source Reporting tools. Being open-source would allow for more customization but was also a generally interesting topic. When I finally got to searching the web about it, I found it wasn’t just a single open-source Reporting Tool. Instead, there was quite a variety of options. There were lists of which tools were the best to use. Now, for the most part, quite a few of the Reporting services ended up over-lapping on lists. But some were more unique. I’m sure everyone has their own preferences."
},
{
"code": null,
"e": 989,
"s": 755,
"text": "Instead of going through all the options, I chose five to do more research on. However, this does not mean that these five are better than any other options. But it may be an interesting dive into some powerful and open-source tools."
},
{
"code": null,
"e": 997,
"s": 989,
"text": "SpagoBI"
},
{
"code": null,
"e": 1823,
"s": 997,
"text": "The first Business Intelligence suite we will be looking at is SpagoBI. It is an open-source suite with a variety of analytic tools. Not only does SpagoBI support reporting, but also Multidimensional analysis (OLAP), the creation of charts, SPIs, interactive cockpits, ad-hoc reporting, location intelligence (such as web mapping services), free inquiry, data mining, network analysis, ETL, collaboration, office automation, master data management, and even external analytical processes that can run in the background. For different user needs, SpagoBI has different main modules. This includes SpagoBI Server, Studio, Meta, SDK, and Applications. This allows business users, developers, decision-makers, and administrators to find a use for SpagoBI. It also supports a list of analytical engines and certified environments."
},
{
"code": null,
"e": 2083,
"s": 1823,
"text": "SpagoBI was written in Java, uses the Ext JS framework, and is open for studying, using, or even modifying the software for more customized usage. The suite uses a Mozilla Public License, which means the components can modify and redistribute modified copies."
},
{
"code": null,
"e": 2527,
"s": 2083,
"text": "In later updates, in 2017, SpagoBI evolved into KNOWAGE. This is a more modern and mature version of business intelligence, with more advanced analysis options and even big data. KNOWAGE advances the original options of SpagoBI, which caters to big data, smart intelligence, enterprise reporting, location intelligence, performance management, and predictive analysis. With KNOWAGE, there is both a community edition and an enterprise edition."
},
{
"code": null,
"e": 2849,
"s": 2527,
"text": "Another item of interest, more specifically interesting to me, is that a version of SpagoBI can be found on Docker Hub. As I’m trying to use Docker more often, you can expect to see more about SpagoBI using Docker here in the future. For now, you can use Docker to pull the SpagoBI version by using the following command:"
},
{
"code": null,
"e": 2886,
"s": 2849,
"text": "sudo docker pull spagobilabs/spagobi"
},
{
"code": null,
"e": 3399,
"s": 2886,
"text": "To Download from the KNOWAGE suite page, as the SpagoBI download will route you to KNOWAGE, you first make an account. Without an account, I found the download page just leads to a 404 Page Not Found. I did start making an account, but I admit I was a little impatient waiting to verify the account for registration. I would much rather try out the Docker version. But that will be for another day so that we can take a deeper dive. That will be when we can fully explore the features and not just the specifics."
},
{
"code": null,
"e": 4057,
"s": 3399,
"text": "As a note, I did end up receiving the verification email an hour or two after I attempted to sign up. Maybe I will revisit that later, but I would be more interested in seeing the Docker version for now anyway, so at least at this time I won’t try installing the regular version. If you decide to install KNOWAGE, but aware that the verification email during sign-up takes a while to receive, so you won’t be able to install KNOWAGE right away. Because I did not revisit, I can’t guarantee you still won’t get the 404 Page Not Found error, but if you tried it out feel free to let me know if in the comments if having an account helped the download to work."
},
{
"code": null,
"e": 4069,
"s": 4057,
"text": "Seal Report"
},
{
"code": null,
"e": 4751,
"s": 4069,
"text": "Not a typical data visualization report, Seal Report is more of a tool that is written in C# using the .NET Framework. Seal Report is also open-source. The framework can be used to produce reports for any type of database, whether that source is SQL or NoSQL based. Seal Report focuses on being installed and building reports both quickly and easily. All the entities of Seal Report are stored in the Seal Repository, which includes data sources, devices, and reports. Seal Report’s main components include the Server Manager, the Report Designer, the Web Report Server, the Task Scheduler, and the Seal Report Scheduler. Together, these allow timed reports, such as daily reports."
},
{
"code": null,
"e": 5014,
"s": 4751,
"text": "The repository folders of Seal Report, necessary to run, include assemblies, databases, devices, logs, reports, security, settings, sources, table templates, special folders, sub-reports, and views. These all are used to create a simple but comprehensive report."
},
{
"code": null,
"e": 5313,
"s": 5014,
"text": "The main features include Dynamic SQL sources, LINQ queries, Native Pivot Tables, HTML 5 Charts, KPI and Widget Views, Full responsive HTML Rendering using Razor engine, Web Report Server, Report scheduler, Drill Down navigation and Sub Reports, Report Tasks, and Low TCO (total cost of ownership)."
},
{
"code": null,
"e": 5510,
"s": 5313,
"text": "Again, I searched on Docker Hub to see if Seal Report was available. It seems that Seal Report is available on Docker to pull, however, I found issues. This is the command that Docker says to use:"
},
{
"code": null,
"e": 5548,
"s": 5510,
"text": "sudo docker pull eesysite/seal-report"
},
{
"code": null,
"e": 5631,
"s": 5548,
"text": "So, when you look at eesy/seal-report in Docker, there are no pulls. When I tried:"
},
{
"code": null,
"e": 5745,
"s": 5631,
"text": "Considering there are no pulls, I am wondering if something was set up wrong, or if it just simply does not work."
},
{
"code": null,
"e": 6039,
"s": 5745,
"text": "To download normally, you are directed to the GitHub code. From there, you can directly download the source code. You can then run the executable file on the computer. From there, you can compile using Visual Studio when you open the Seal.sln solution file from the root directory of the tool."
},
{
"code": null,
"e": 6336,
"s": 6039,
"text": "While trying to learn how to use Seal Report, there are tutorials right on the Seal Report website. It first teaches you how to generate a report from a SQL Select statement. This is used to prepare a report in a few quick and easy steps. Once executed, you can save the report to the repository."
},
{
"code": null,
"e": 6548,
"s": 6336,
"text": "The next set of instructions shows how to create the first Data Source. It also instructs how to create, execute, and store the report. Once you have the source and report set up and ready, you can then publish."
},
{
"code": null,
"e": 6826,
"s": 6548,
"text": "There are two sets of instructions for publication, depending on where you want the report to be. The first is on Linux (Ubuntu). That would be applicable for me as that is what I use. The other is on Azure. With Azure, there are also instructions on how to Audit the database."
},
{
"code": null,
"e": 7061,
"s": 6826,
"text": "The final set of instructions is to set up the Seal Report Scheduler. This way, you will not have to manually create the reports each time. Instead, you can set up the scheduler to automatically generate a report at a particular time."
},
{
"code": null,
"e": 7071,
"s": 7061,
"text": "QueryTree"
},
{
"code": null,
"e": 7690,
"s": 7071,
"text": "QueryTree is an open-source solution written in C#, ASP.NET, and JavaScript. The tool is targeted for ad hoc reporting and visualization. Found on GitHub, it can be run using the Source, or it can be run using Binaries or even Docker. QueryTree is geared to work with Microsoft SQL Server, MySQL, or a PostgreSQL database. This tool is geared for both technical and non-technical users. QueryTree makes it easy for non-technical users to select, filter, group, aggregate, and visualize data from the tables in the database. It can even create interactive charts to visualize the data without writing any code to do so."
},
{
"code": null,
"e": 8202,
"s": 7690,
"text": "QueryTree is a form of a drag-and-drop builder, which allows for non-technical users a variety of visualization options without writing any code. These reports can also be scheduled to generate for viewing on either the web or on mobile. The drag-and-drop builder includes and powerful and flexible interface that allows the queries to generate reports based on what the user selects. This also means that data sets can be joined, transformed, or simply viewed using QueryTree’s easy-to-use visualization tools."
},
{
"code": null,
"e": 8662,
"s": 8202,
"text": "When viewing the data, QueryTree includes a Sort tool and a Select tool, which can be used to organize the data or to remove any information that may not be consistent. There are also a few different chart options, so the user can select which chart they would like to view the data on. QueryTree also allows the charts to be exported as opposed to only being able to save the chart. This way, the data may be represented in other tools such as Excel or Word."
},
{
"code": null,
"e": 8997,
"s": 8662,
"text": "As reports are scheduled and generated, QueryTree also gives the ability to invite teammates to view those scheduled reports. QueryTree also allows secure encrypted connections to access the database and connects with read-only access, so the data would be safe. This way, reports can be shared with teammates for a better experience."
},
{
"code": null,
"e": 9639,
"s": 8997,
"text": "For more complex options, Query Tree offers an Advanced Report Builder. This includes the same functionality as the Simple Report Builder, but with more tools and options for customization. These reports are more complex, so may dig deeper into the database. Along with the standard drag-and-drop option, the Advanced Report Builder also utilizes a simple wizard to comprehensively visualize the desired data. Like the others we have discussed, QueryTree is open-source and free to use, but also comes with a customizable support plan for enterprise customers. For non-enterprise users, Github has community support on the QueryTree project."
},
{
"code": null,
"e": 9700,
"s": 9639,
"text": "As previously mentioned, QueryTree is available with Docker:"
},
{
"code": null,
"e": 9738,
"s": 9700,
"text": "sudo docker pull d4software/querytree"
},
{
"code": null,
"e": 9902,
"s": 9738,
"text": "QueryTree is another open-source ad-hoc reporting tool that I think would be interesting to use, so later down the road we’ll attempt using it further with Docker."
},
{
"code": null,
"e": 9913,
"s": 9902,
"text": "FineReport"
},
{
"code": null,
"e": 10382,
"s": 9913,
"text": "FineReport is an open-source BI Reporting and Dashboard Software. Unlike some of the others, FineReport is a web-based tool. The design of it is modeled after Excel, so it is easy to work with for beginners. FineReport can be deployed locally or can be connected to corporate databases. Almost all database types are supported by FineReport. It is written in Java and free for personal use but looks like there may be fees when using FineReport for corporate purposes."
},
{
"code": null,
"e": 10778,
"s": 10382,
"text": "The detail for the reports and dashboard aims for innovative design patterns, fast data integration, cool data visualization (with dynamic and even 3D effects), small data entry, powerful decision-making platforms, and both easy deployment and integration. FineReport is written in Java, which means it can be implemented with different systems either through independent or embedded deployment."
},
{
"code": null,
"e": 11852,
"s": 10778,
"text": "FineReport can be used to visualize reports, dashboards, financial statements, developing purchase, sales, inventory systems, and more. The tool also has different use cases. One cause is business users, in which they may need to display reports of data, or FineReport can be used for fast and easy data entry. The next user case is middle-level managers. Supervisors such as this would need the ability to generate and display reports, export that analysis (for presentations such as in a PDF format or in Excel), or even for mandatory data attention in scenarios where certain data needs to be monitored and reviewed in a timely manner. This is where FineReport allows a scheduled report to be generated which can push the reports to the users through emails, or by other selected means. The final user case considered is senior management. In this case, managers need to be able to view data, such as with a dashboard, but they must also be able to visualize data anywhere, such as on mobile, and they must also be able to analyze data, such as with linkage or drilling."
},
{
"code": null,
"e": 12691,
"s": 11852,
"text": "FineReport was created as more of a professional big data BI and analytics platform. It specializes in analytics, so it is, therefore, more IT-centric. Although business users can use FineReport, the full functionality is centered for IT individuals. This is also because most users have basic SQL knowledge when using the reports. FineReport does have several different versions which are geared towards different individuals. As stated before, FineReport is centered around the typical IT user. FineBI is positioned to be used by more business users or data analysts. JDY is a no-code aPaaS (Application Platform as a Service) solution which can be used by both business users and IT to enhance productivity. However, JDY can be used by the entire staff, as there is no code involved. However, we are only looking at FineReport for now."
},
{
"code": null,
"e": 12770,
"s": 12691,
"text": "Like the others, there is a version of FineReport that can be found on Docker:"
},
{
"code": null,
"e": 12861,
"s": 12770,
"text": "Now that we have that ready, maybe we’ll take a deeper dive into FineReport in the future."
},
{
"code": null,
"e": 12871,
"s": 12861,
"text": "ReportLab"
},
{
"code": null,
"e": 13203,
"s": 12871,
"text": "ReportLab is an open-source engine used to create complex PDF documents and customized vector graphs. It is part of the standard Linux distributions, is embedded in a variety of different products, and even was selected to function as the print/export feature for Wikipedia. ReportLab is free to use and was also written in Python."
},
{
"code": null,
"e": 13917,
"s": 13203,
"text": "ReportLab is broken into three main layers. The first layer a graphics canvas API that “draws” PDF pages. The second layer is a charts and widgets library that can be used to create reusable data graphics. The final layer is the page layout engine, which is used to build documents from different elements such as headlines, paragraphs, fonts, tables, and vector graphs. The page layout engine is PLATYPUS (Page Layout and Typography Using Scripts). ReportLab also has a PLUS commercial product, which generates PDFs at a higher speed and also allows the use of ReportLab’s XML-based templating language RML. ReportLab PLUS also includes upgrades to the open-source library that enable a faster development cycle."
},
{
"code": null,
"e": 14868,
"s": 13917,
"text": "With just the standard ReportLab open-source engine, it is a free PDF toolkit, can automate document production, generate multiple PDFs quickly, has a Diagra charting toolkit, and reduce paperwork and print costs. The ReportLab Toolkit, which is the free version, is a library used to programmatically create PDF documents. The features of the toolkit are to create professional portable documents, use the real document layout engine (Platypus), flowable objects such as headlines or paragraphs, but ReportLab Toolkit also supports embedded Type-1 or TIF fonts, Asian, Hebrew, and Arabic characters, bitmap images in any popular format, vector graphics, it includes a library of reusable primitive shapes, an extensible widget library, a layered architecture written in Python, it also includes simple demos and more complex tools, allows for any data sources, fully available source code, strong community support, and is also platform-independent."
},
{
"code": null,
"e": 15093,
"s": 14868,
"text": "Because it is written in Python, you can install using the source code, or using pip from PYPI. Although available on Linux, ReportLab is cross-platform and is available on Windows, Mac OSX, Solaris, AIX, FreeBSD, and so on."
},
{
"code": null,
"e": 15258,
"s": 15093,
"text": "Unlike the other open-source tools on this list, ReportLab is not found on Docker. But because it can be installed using Pip from PYPI, we will install it that way:"
},
{
"code": null,
"e": 15286,
"s": 15258,
"text": "sudo pip3 install reportlab"
},
{
"code": null,
"e": 15545,
"s": 15286,
"text": "Even though ReportLab wasn’t found on Docker, you know I have a soft spot for my Python projects. So. expect to see more from me on using ReportLab in the future. It seems like a powerful toolkit, but I’m also enjoying the fact that it was written in Python."
},
{
"code": null,
"e": 15556,
"s": 15545,
"text": "Conclusion"
},
{
"code": null,
"e": 16022,
"s": 15556,
"text": "In this article, we reviewed five different open-source engines/toolkits for reporting. Of the five, four of them had versions available on Docker. As I had stated in the beginning, this was not a breakdown of the “best” open-source engines. Instead, this was more of an educational breakdown to appease my own curiosity. The inspiration was just wondering if there were any open-source reporting tools, so I was pleasantly surprised to see that there were so many."
},
{
"code": null,
"e": 16282,
"s": 16022,
"text": "We learned about SpagoBI, Seal Report, QueryTree, FineReport, and ReportLab. Of all, only ReportLab was not found on Docker. However, ReportLab was also the only Python-driven toolkit and was available by installing with Pip, so don’t count that out just yet."
},
{
"code": null,
"e": 17498,
"s": 16282,
"text": "In our research, we only got general background information for each of the reporting tools. However, we didn’t get a chance to attempt generating reports with any of them yet. This is something I would be interested in doing. Now as a note, there are several “best open-source reporting tools” on the web, and although there is overlap for many, there are still many others that I did not list in this overview. This by no means is implying that these are the best five, they were just the five that I found a little bit more interest in learning more about. In the future, I plan to use at least a few of these reporting tools and to learn a little more about how to use them. What may be interesting is, after they have all been tried, revisit all tools I chose in a comparison format. If you use any open-source reporting tools that you think would be worth looking into, feel free to drop them in the comments and I’d be rather interested in looking. Overall, I thought it was interesting to see how similar and yet different these open-source reporting services can be, where some do seek to earn a profit through advanced features, yet while others remain free for use by all users including for company use."
},
{
"code": null,
"e": 17586,
"s": 17498,
"text": "Later on, we will be taking deeper dives into each on the list, but until then, cheers!"
},
{
"code": null,
"e": 17651,
"s": 17586,
"text": "Read all my articles for free with my weekly newsletter, thanks!"
},
{
"code": null,
"e": 17718,
"s": 17651,
"text": "Want to read all articles on Medium? Become a Medium member today!"
}
] |
Groovy - put() | Associates the specified value with the specified key in this Map. If this Map previously contained a mapping for this key, the old value is replaced by the specified value.
Object put(Object key, Object value)
Key – The key to be put in the map
Value – The associated value for the key
The returned key-value pair which is inserted.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"]
mp.put("TopicID","1");
println(mp);
}
}
When we run the above program, we will get the following result −
[TopicName:Maps, TopicDescription:Methods in Maps, TopicID:1]
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2412,
"s": 2238,
"text": "Associates the specified value with the specified key in this Map. If this Map previously contained a mapping for this key, the old value is replaced by the specified value."
},
{
"code": null,
"e": 2450,
"s": 2412,
"text": "Object put(Object key, Object value)\n"
},
{
"code": null,
"e": 2485,
"s": 2450,
"text": "Key – The key to be put in the map"
},
{
"code": null,
"e": 2526,
"s": 2485,
"text": "Value – The associated value for the key"
},
{
"code": null,
"e": 2573,
"s": 2526,
"text": "The returned key-value pair which is inserted."
},
{
"code": null,
"e": 2627,
"s": 2573,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2818,
"s": 2627,
"text": "class Example { \n static void main(String[] args) { \n def mp = [\"TopicName\" : \"Maps\", \"TopicDescription\" : \"Methods in Maps\"] \n mp.put(\"TopicID\",\"1\");\n println(mp); \n } \n}"
},
{
"code": null,
"e": 2884,
"s": 2818,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2947,
"s": 2884,
"text": "[TopicName:Maps, TopicDescription:Methods in Maps, TopicID:1]\n"
},
{
"code": null,
"e": 2980,
"s": 2947,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2998,
"s": 2980,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 3033,
"s": 2998,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3051,
"s": 3033,
"text": " Packt Publishing"
},
{
"code": null,
"e": 3058,
"s": 3051,
"text": " Print"
},
{
"code": null,
"e": 3069,
"s": 3058,
"text": " Add Notes"
}
] |
How to create and store property file dynamically in Java? | The .propertiesis an extension in java which is used to store configurable application. It is represented by the Properties class in Java, you can store a properties file and read from it using the methods of this class. This class inherits the HashTable class.
To create a properties file −
Instantiate the Properties class.
Populate the created Properties object using the put() method.
Instantiate the FileOutputStream class by passing the path to store the file, as a parameter.
The Following Java program creates a properties file in the path D:/ExampleDirectory/
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class CreatingPropertiesFile {
public static void main(String args[]) throws IOException {
//Instantiating the properties file
Properties props = new Properties();
//Populating the properties file
props.put("Device_name", "OnePlus7");
props.put("Android_version", "9");
props.put("Model", "GM1901");
props.put("CPU", "Snapdragon855");
//Instantiating the FileInputStream for output file
String path = "D:\\ExampleDirectory\\myFile.properties";
FileOutputStream outputStrem = new FileOutputStream(path);
//Storing the properties file
props.store(outputStrem, "This is a sample properties file");
System.out.println("Properties file created......");
}
}
Properties file created......
If you observe the output file you can see the created contents as −
You can store the properties file in XMLformat using the storeToXML() method.
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class CreatingPropertiesFile {
public static void main(String args[]) throws IOException {
//Instantiating the properties file
Properties props = new Properties();
//Populating the properties file
props.put("Device_name", "OnePlus7");
props.put("Android_version", "9");
props.put("Model", "GM1901");
props.put("CPU", "Snapdragon855");
//Instantiating the FileInputStream for output file
String outputPath = "D:\\ExampleDirectory\\myFile.xml";
FileOutputStream outputStrem = new FileOutputStream(outputPath);
//Storing the properties file in XML format
props.storeToXML(outputStrem, "This is a sample properties file");
System.out.println("Properties file created......");
}
}
Properties file created......
If you observe the output file you can see the created contents as − | [
{
"code": null,
"e": 1324,
"s": 1062,
"text": "The .propertiesis an extension in java which is used to store configurable application. It is represented by the Properties class in Java, you can store a properties file and read from it using the methods of this class. This class inherits the HashTable class."
},
{
"code": null,
"e": 1354,
"s": 1324,
"text": "To create a properties file −"
},
{
"code": null,
"e": 1388,
"s": 1354,
"text": "Instantiate the Properties class."
},
{
"code": null,
"e": 1451,
"s": 1388,
"text": "Populate the created Properties object using the put() method."
},
{
"code": null,
"e": 1545,
"s": 1451,
"text": "Instantiate the FileOutputStream class by passing the path to store the file, as a parameter."
},
{
"code": null,
"e": 1631,
"s": 1545,
"text": "The Following Java program creates a properties file in the path D:/ExampleDirectory/"
},
{
"code": null,
"e": 2464,
"s": 1631,
"text": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Properties;\npublic class CreatingPropertiesFile {\n public static void main(String args[]) throws IOException {\n //Instantiating the properties file\n Properties props = new Properties();\n //Populating the properties file\n props.put(\"Device_name\", \"OnePlus7\");\n props.put(\"Android_version\", \"9\");\n props.put(\"Model\", \"GM1901\");\n props.put(\"CPU\", \"Snapdragon855\");\n //Instantiating the FileInputStream for output file\n String path = \"D:\\\\ExampleDirectory\\\\myFile.properties\";\n FileOutputStream outputStrem = new FileOutputStream(path);\n //Storing the properties file\n props.store(outputStrem, \"This is a sample properties file\");\n System.out.println(\"Properties file created......\");\n }\n}"
},
{
"code": null,
"e": 2494,
"s": 2464,
"text": "Properties file created......"
},
{
"code": null,
"e": 2563,
"s": 2494,
"text": "If you observe the output file you can see the created contents as −"
},
{
"code": null,
"e": 2641,
"s": 2563,
"text": "You can store the properties file in XMLformat using the storeToXML() method."
},
{
"code": null,
"e": 3498,
"s": 2641,
"text": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Properties;\npublic class CreatingPropertiesFile {\n public static void main(String args[]) throws IOException {\n //Instantiating the properties file\n Properties props = new Properties();\n //Populating the properties file\n props.put(\"Device_name\", \"OnePlus7\");\n props.put(\"Android_version\", \"9\");\n props.put(\"Model\", \"GM1901\");\n props.put(\"CPU\", \"Snapdragon855\");\n //Instantiating the FileInputStream for output file\n String outputPath = \"D:\\\\ExampleDirectory\\\\myFile.xml\";\n FileOutputStream outputStrem = new FileOutputStream(outputPath);\n //Storing the properties file in XML format\n props.storeToXML(outputStrem, \"This is a sample properties file\");\n System.out.println(\"Properties file created......\");\n }\n}"
},
{
"code": null,
"e": 3528,
"s": 3498,
"text": "Properties file created......"
},
{
"code": null,
"e": 3597,
"s": 3528,
"text": "If you observe the output file you can see the created contents as −"
}
] |
What does int argc, char *argv[] mean in C/C++? | argc stands for argument count and argv stands for argument values. These are variables passed to the main function when it starts executing. When we run a program we can give arguments to that program like −
$ ./a.out hello
Here hello is an argument to the executable. This can be accessed in your program. For example,
#include<iostream>
using namespace std;
int main(int argc, char** argv) {
cout << "This program has " << argc << " arguments:" << endl;
for (int i = 0; i < argc; ++i) {
cout << argv[i] << endl;
}
return 0;
}
When you compile and run this program like −
$ ./a.out hello people
This will give the output −
This program has 3 arguments
C:\Users\user\Desktop\hello.exe
hello
people
Note that the first argument is always the location of the executable executing. | [
{
"code": null,
"e": 1271,
"s": 1062,
"text": "argc stands for argument count and argv stands for argument values. These are variables passed to the main function when it starts executing. When we run a program we can give arguments to that program like −"
},
{
"code": null,
"e": 1287,
"s": 1271,
"text": "$ ./a.out hello"
},
{
"code": null,
"e": 1383,
"s": 1287,
"text": "Here hello is an argument to the executable. This can be accessed in your program. For example,"
},
{
"code": null,
"e": 1610,
"s": 1383,
"text": "#include<iostream>\nusing namespace std;\nint main(int argc, char** argv) {\n cout << \"This program has \" << argc << \" arguments:\" << endl;\n for (int i = 0; i < argc; ++i) {\n cout << argv[i] << endl;\n }\n return 0;\n}\n"
},
{
"code": null,
"e": 1655,
"s": 1610,
"text": "When you compile and run this program like −"
},
{
"code": null,
"e": 1678,
"s": 1655,
"text": "$ ./a.out hello people"
},
{
"code": null,
"e": 1706,
"s": 1678,
"text": "This will give the output −"
},
{
"code": null,
"e": 1735,
"s": 1706,
"text": "This program has 3 arguments"
},
{
"code": null,
"e": 1780,
"s": 1735,
"text": "C:\\Users\\user\\Desktop\\hello.exe\nhello\npeople"
},
{
"code": null,
"e": 1861,
"s": 1780,
"text": "Note that the first argument is always the location of the executable executing."
}
] |
Get current date/time in seconds - JavaScript? | At first, get the current date −
var currentDateTime = new Date();
To get the current date/time in seconds, use getTime()/1000.
Following is the code −
var currentDateTime = new Date();
console.log("The current date time is as follows:");
console.log(currentDateTime);
var resultInSeconds=currentDateTime.getTime() / 1000;
console.log("The current date time in seconds is as follows:")
console.log(resultInSeconds);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo285.js.
This will produce the following output on console −
The current date time is as follows:
2020-08-28T16:13:35.987Z
The current date time in seconds is as follows:
1598631215.987 | [
{
"code": null,
"e": 1095,
"s": 1062,
"text": "At first, get the current date −"
},
{
"code": null,
"e": 1129,
"s": 1095,
"text": "var currentDateTime = new Date();"
},
{
"code": null,
"e": 1190,
"s": 1129,
"text": "To get the current date/time in seconds, use getTime()/1000."
},
{
"code": null,
"e": 1214,
"s": 1190,
"text": "Following is the code −"
},
{
"code": null,
"e": 1478,
"s": 1214,
"text": "var currentDateTime = new Date();\nconsole.log(\"The current date time is as follows:\");\nconsole.log(currentDateTime);\nvar resultInSeconds=currentDateTime.getTime() / 1000;\nconsole.log(\"The current date time in seconds is as follows:\")\nconsole.log(resultInSeconds);"
},
{
"code": null,
"e": 1544,
"s": 1478,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1563,
"s": 1544,
"text": "node fileName.js.\n"
},
{
"code": null,
"e": 1597,
"s": 1563,
"text": "Here, my file name is demo285.js."
},
{
"code": null,
"e": 1649,
"s": 1597,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 1774,
"s": 1649,
"text": "The current date time is as follows:\n2020-08-28T16:13:35.987Z\nThe current date time in seconds is as follows:\n1598631215.987"
}
] |
crypt() function in PHP | The crypt() function is used to hash the string using using algorithms like DES, Blowfish, or MD5.
Note − This function behaves different on different operating systems.
The following are some constants used together with the crypt() function.
[CRYPT_STD_DES] - Standard DES-based hash with two character salt from the alphabet "./0-9A-Za-z".
[CRYPT_STD_DES] - Standard DES-based hash with two character salt from the alphabet "./0-9A-Za-z".
[CRYPT_EXT_DES] - Extended DES-based hash with a nine character salt consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt.
[CRYPT_EXT_DES] - Extended DES-based hash with a nine character salt consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt.
[CRYPT_MD5] - MD5 hashing with a 12 character salt starting with 1
[CRYPT_MD5] - MD5 hashing with a 12 character salt starting with 1
[CRYPT_BLOWFISH] - Blowfish hashing with a salt starting with 2a, 2x, or 2y, a two digit cost parameters "$", and 22 characters from the alphabet "./0-9A-Za-z".
[CRYPT_BLOWFISH] - Blowfish hashing with a salt starting with 2a, 2x, or 2y, a two digit cost parameters "$", and 22 characters from the alphabet "./0-9A-Za-z".
[CRYPT_SHA_256] - SHA-256 hash with a 16 character salt starting with 5.
[CRYPT_SHA_256] - SHA-256 hash with a 16 character salt starting with 5.
[CRYPT_SHA_512] - SHA-512 hash with a 16 character salt starting with 6.
[CRYPT_SHA_512] - SHA-512 hash with a 16 character salt starting with 6.
crypt(str, salt)
str − The string to be hashed. Required.
str − The string to be hashed. Required.
salt − Salt string to base the hashing on. Optional.
salt − Salt string to base the hashing on. Optional.
The crypt() function returns the encoded string or a string shorter than 13 characters and is guaranteed to differ from the salt on failure
The following is an example −
Live Demo
<?php
if (CRYPT_STD_DES == 1) {
echo "DES supported = ".crypt('demo','st')."\n";
} else {
echo "DES not supported!";
}
?>
The following is the output −
DES supported = st7zBedJadRn2 | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "The crypt() function is used to hash the string using using algorithms like DES, Blowfish, or MD5."
},
{
"code": null,
"e": 1232,
"s": 1161,
"text": "Note − This function behaves different on different operating systems."
},
{
"code": null,
"e": 1306,
"s": 1232,
"text": "The following are some constants used together with the crypt() function."
},
{
"code": null,
"e": 1405,
"s": 1306,
"text": "[CRYPT_STD_DES] - Standard DES-based hash with two character salt from the alphabet \"./0-9A-Za-z\"."
},
{
"code": null,
"e": 1504,
"s": 1405,
"text": "[CRYPT_STD_DES] - Standard DES-based hash with two character salt from the alphabet \"./0-9A-Za-z\"."
},
{
"code": null,
"e": 1661,
"s": 1504,
"text": "[CRYPT_EXT_DES] - Extended DES-based hash with a nine character salt consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt."
},
{
"code": null,
"e": 1818,
"s": 1661,
"text": "[CRYPT_EXT_DES] - Extended DES-based hash with a nine character salt consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt."
},
{
"code": null,
"e": 1885,
"s": 1818,
"text": "[CRYPT_MD5] - MD5 hashing with a 12 character salt starting with 1"
},
{
"code": null,
"e": 1952,
"s": 1885,
"text": "[CRYPT_MD5] - MD5 hashing with a 12 character salt starting with 1"
},
{
"code": null,
"e": 2113,
"s": 1952,
"text": "[CRYPT_BLOWFISH] - Blowfish hashing with a salt starting with 2a, 2x, or 2y, a two digit cost parameters \"$\", and 22 characters from the alphabet \"./0-9A-Za-z\"."
},
{
"code": null,
"e": 2274,
"s": 2113,
"text": "[CRYPT_BLOWFISH] - Blowfish hashing with a salt starting with 2a, 2x, or 2y, a two digit cost parameters \"$\", and 22 characters from the alphabet \"./0-9A-Za-z\"."
},
{
"code": null,
"e": 2347,
"s": 2274,
"text": "[CRYPT_SHA_256] - SHA-256 hash with a 16 character salt starting with 5."
},
{
"code": null,
"e": 2420,
"s": 2347,
"text": "[CRYPT_SHA_256] - SHA-256 hash with a 16 character salt starting with 5."
},
{
"code": null,
"e": 2493,
"s": 2420,
"text": "[CRYPT_SHA_512] - SHA-512 hash with a 16 character salt starting with 6."
},
{
"code": null,
"e": 2566,
"s": 2493,
"text": "[CRYPT_SHA_512] - SHA-512 hash with a 16 character salt starting with 6."
},
{
"code": null,
"e": 2583,
"s": 2566,
"text": "crypt(str, salt)"
},
{
"code": null,
"e": 2624,
"s": 2583,
"text": "str − The string to be hashed. Required."
},
{
"code": null,
"e": 2665,
"s": 2624,
"text": "str − The string to be hashed. Required."
},
{
"code": null,
"e": 2718,
"s": 2665,
"text": "salt − Salt string to base the hashing on. Optional."
},
{
"code": null,
"e": 2771,
"s": 2718,
"text": "salt − Salt string to base the hashing on. Optional."
},
{
"code": null,
"e": 2911,
"s": 2771,
"text": "The crypt() function returns the encoded string or a string shorter than 13 characters and is guaranteed to differ from the salt on failure"
},
{
"code": null,
"e": 2941,
"s": 2911,
"text": "The following is an example −"
},
{
"code": null,
"e": 2952,
"s": 2941,
"text": " Live Demo"
},
{
"code": null,
"e": 3080,
"s": 2952,
"text": "<?php\nif (CRYPT_STD_DES == 1) {\n echo \"DES supported = \".crypt('demo','st').\"\\n\";\n} else {\n echo \"DES not supported!\";\n}\n?>"
},
{
"code": null,
"e": 3110,
"s": 3080,
"text": "The following is the output −"
},
{
"code": null,
"e": 3140,
"s": 3110,
"text": "DES supported = st7zBedJadRn2"
}
] |
Draw Circle in Python using Turtle - GeeksforGeeks | 06 Aug, 2021
Turtle is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Turtle is a beginner-friendly way to learn Python by running some basic commands and viewing the turtle do it graphically. It is like a drawing board that allows you to draw over it. The turtle module can be used in both object-oriented and procedure-oriented ways.To draw, Python turtle provides many functions and methods i.e. forward, backward, etc. Some the commonly used methods are:
forward(x): moves the pen in the forward direction by x unit.
backward(x): moves the pen in the backward direction by x unit.
right(x): rotate the pen in the clockwise direction by an angle x.
left(x): rotate the pen in the anticlockwise direction by an angle x.
penup(): stop drawing of the turtle pen.
pendown(): start drawing of the turtle pen.
Now to draw a circle using turtle, we will use a predefined function in “turtle”.circle(radius): This function draws a circle of the given radius by taking the “turtle” position as the center.Example:
Python3
# Python program to demonstrate# circle drawing import turtle # Initializing the turtlet = turtle.Turtle() r = 50t.circle(r)
Output :
A tangent is a line that touches the circumference of a circle from outside at a point, provided that any extension of the line will not cause intersection with the circle. Now, think about a group of circles, that have a common tangent. The group of circles, having common tangent, are known as tangent circles.Example:
Python3
# Python program to demonstrate# tangent circle drawing import turtle t = turtle.Turtle() # radius for smallest circler = 10 # number of circlesn = 10 # loop for printing tangent circlesfor i in range(1, n + 1, 1): t.circle(r * i)
Output :
Spiral is a shape similar to a circle, except that the radius of the spiral gradually increases after every completed round.Example:
Python3
# Python program to demonstrate# spiral circle drawing import turtle t = turtle.Turtle() # taking radius of initial radiusr = 10 # Loop for printing spiral circlefor i in range(100): t.circle(r + i, 45)
Output :
The term concentric is used for a group of things having common. Now Circles having the same center are termed as Concentric Circle.
Python3
# Python program to demonstrate# concentric circle drawing import turtle t = turtle.Turtle() # radius of the circler = 10 # Loop for printing concentric circlesfor i in range(50): t.circle(r * i) t.up() t.sety((r * i)*(-1)) t.down()
Output :
rajeev0719singh
python-modules
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24213,
"s": 24185,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 24805,
"s": 24213,
"text": "Turtle is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Turtle is a beginner-friendly way to learn Python by running some basic commands and viewing the turtle do it graphically. It is like a drawing board that allows you to draw over it. The turtle module can be used in both object-oriented and procedure-oriented ways.To draw, Python turtle provides many functions and methods i.e. forward, backward, etc. Some the commonly used methods are:"
},
{
"code": null,
"e": 24867,
"s": 24805,
"text": "forward(x): moves the pen in the forward direction by x unit."
},
{
"code": null,
"e": 24931,
"s": 24867,
"text": "backward(x): moves the pen in the backward direction by x unit."
},
{
"code": null,
"e": 24998,
"s": 24931,
"text": "right(x): rotate the pen in the clockwise direction by an angle x."
},
{
"code": null,
"e": 25068,
"s": 24998,
"text": "left(x): rotate the pen in the anticlockwise direction by an angle x."
},
{
"code": null,
"e": 25109,
"s": 25068,
"text": "penup(): stop drawing of the turtle pen."
},
{
"code": null,
"e": 25153,
"s": 25109,
"text": "pendown(): start drawing of the turtle pen."
},
{
"code": null,
"e": 25355,
"s": 25153,
"text": "Now to draw a circle using turtle, we will use a predefined function in “turtle”.circle(radius): This function draws a circle of the given radius by taking the “turtle” position as the center.Example: "
},
{
"code": null,
"e": 25363,
"s": 25355,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# circle drawing import turtle # Initializing the turtlet = turtle.Turtle() r = 50t.circle(r)",
"e": 25497,
"s": 25363,
"text": null
},
{
"code": null,
"e": 25507,
"s": 25497,
"text": "Output : "
},
{
"code": null,
"e": 25831,
"s": 25509,
"text": "A tangent is a line that touches the circumference of a circle from outside at a point, provided that any extension of the line will not cause intersection with the circle. Now, think about a group of circles, that have a common tangent. The group of circles, having common tangent, are known as tangent circles.Example: "
},
{
"code": null,
"e": 25839,
"s": 25831,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# tangent circle drawing import turtle t = turtle.Turtle() # radius for smallest circler = 10 # number of circlesn = 10 # loop for printing tangent circlesfor i in range(1, n + 1, 1): t.circle(r * i)",
"e": 26082,
"s": 25839,
"text": null
},
{
"code": null,
"e": 26092,
"s": 26082,
"text": "Output : "
},
{
"code": null,
"e": 26228,
"s": 26094,
"text": "Spiral is a shape similar to a circle, except that the radius of the spiral gradually increases after every completed round.Example: "
},
{
"code": null,
"e": 26236,
"s": 26228,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# spiral circle drawing import turtle t = turtle.Turtle() # taking radius of initial radiusr = 10 # Loop for printing spiral circlefor i in range(100): t.circle(r + i, 45)",
"e": 26450,
"s": 26236,
"text": null
},
{
"code": null,
"e": 26461,
"s": 26450,
"text": "Output : "
},
{
"code": null,
"e": 26597,
"s": 26463,
"text": "The term concentric is used for a group of things having common. Now Circles having the same center are termed as Concentric Circle. "
},
{
"code": null,
"e": 26605,
"s": 26597,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# concentric circle drawing import turtle t = turtle.Turtle() # radius of the circler = 10 # Loop for printing concentric circlesfor i in range(50): t.circle(r * i) t.up() t.sety((r * i)*(-1)) t.down()",
"e": 26864,
"s": 26605,
"text": null
},
{
"code": null,
"e": 26874,
"s": 26864,
"text": "Output : "
},
{
"code": null,
"e": 26890,
"s": 26874,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 26905,
"s": 26890,
"text": "python-modules"
},
{
"code": null,
"e": 26921,
"s": 26905,
"text": "Python-projects"
},
{
"code": null,
"e": 26936,
"s": 26921,
"text": "python-utility"
},
{
"code": null,
"e": 26943,
"s": 26936,
"text": "Python"
},
{
"code": null,
"e": 27041,
"s": 26943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27050,
"s": 27041,
"text": "Comments"
},
{
"code": null,
"e": 27063,
"s": 27050,
"text": "Old Comments"
},
{
"code": null,
"e": 27081,
"s": 27063,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27116,
"s": 27081,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27138,
"s": 27116,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27170,
"s": 27138,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27200,
"s": 27170,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27242,
"s": 27200,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27285,
"s": 27242,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27311,
"s": 27285,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27355,
"s": 27311,
"text": "Reading and Writing to text files in Python"
}
] |
MFC - Date & Time Picker | The date and time picker control (CDateTimeCtrl) implements an intuitive and recognizable method of entering or selecting a specific date. The main interface of the control is similar in functionality to a combo box. However, if the user expands the control, a month calendar control appears (by default), allowing the user to specify a particular date. When a date is chosen, the month calendar control automatically disappears.
CloseMonthCal
Closes the current date and time picker control.
Create
Creates the date and time picker control and attaches it to the CDateTimeCtrl object.
GetDateTimePickerInfo
Retrieves information about the current date and time picker control.
GetIdealSize
Returns the ideal size of the date and time picker control that is required to display the current date or time.
GetMonthCalColor
Retrieves the color for a given portion of the month calendar within the date and time picker control.
GetMonthCalCtrl
Retrieves the CMonthCalCtrl object associated with the date and time picker control.
GetMonthCalFont
Retrieves the font currently used by the date and time picker control's child month calendar control.
GetMonthCalStyle
Gets the style of the current date and time picker control.
GetRange
Retrieves the current minimum and maximum allowed system times for a date and time picker control.
GetTime
Retrieves the currently selected time from a date and time picker control and puts it in a specified SYSTEMTIME structure.
SetFormat
Sets the display of a date and time picker control in accordance with a given format string.
SetMonthCalColor
Sets the color for a given portion of the month calendar within a date and time picker control.
SetMonthCalFont
Sets the font that the date and time picker control's child month calendar control will use.
SetMonthCalStyle
Sets the style of the current date and time picker control.
SetRange
Sets the style of the current date and time picker control.
SetTime
Sets the time in a date and time picker control.
Let us look into a simple example by creating a new MFC application.
Step 1 − Remove the Caption and set its ID to IDC_STATIC_TXT.
Step 2 − Add the value variable for text control.
Step 3 − Drag the Date Time Picker control.
Step 4 − Add a control variable for Date Time Picker.
Step 5 − Add the Event handler for Date Time Picker.
Step 6 − Here is the implementation of event handler.
void CMFCDateAndTimePickerDlg::OnDtnDatetimechangeDatetimepicker1(NMHDR *pNMHDR, LRESULT *pResult){
LPNMDATETIMECHANGE pDTChange = reinterpret_cast <LPNMDATETIMECHANGE>(pNMHDR);
// TODO: Add your control notification handler code here
GetDlgItemText(IDC_DATETIMEPICKER1, m_strValue);
UpdateData(FALSE);
*pResult = 0;
}
Step 7 − When you run the above application, you see the following output. Select any date, it will display on the Static Text Control.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2497,
"s": 2067,
"text": "The date and time picker control (CDateTimeCtrl) implements an intuitive and recognizable method of entering or selecting a specific date. The main interface of the control is similar in functionality to a combo box. However, if the user expands the control, a month calendar control appears (by default), allowing the user to specify a particular date. When a date is chosen, the month calendar control automatically disappears."
},
{
"code": null,
"e": 2511,
"s": 2497,
"text": "CloseMonthCal"
},
{
"code": null,
"e": 2560,
"s": 2511,
"text": "Closes the current date and time picker control."
},
{
"code": null,
"e": 2567,
"s": 2560,
"text": "Create"
},
{
"code": null,
"e": 2653,
"s": 2567,
"text": "Creates the date and time picker control and attaches it to the CDateTimeCtrl object."
},
{
"code": null,
"e": 2675,
"s": 2653,
"text": "GetDateTimePickerInfo"
},
{
"code": null,
"e": 2745,
"s": 2675,
"text": "Retrieves information about the current date and time picker control."
},
{
"code": null,
"e": 2758,
"s": 2745,
"text": "GetIdealSize"
},
{
"code": null,
"e": 2871,
"s": 2758,
"text": "Returns the ideal size of the date and time picker control that is required to display the current date or time."
},
{
"code": null,
"e": 2888,
"s": 2871,
"text": "GetMonthCalColor"
},
{
"code": null,
"e": 2991,
"s": 2888,
"text": "Retrieves the color for a given portion of the month calendar within the date and time picker control."
},
{
"code": null,
"e": 3007,
"s": 2991,
"text": "GetMonthCalCtrl"
},
{
"code": null,
"e": 3092,
"s": 3007,
"text": "Retrieves the CMonthCalCtrl object associated with the date and time picker control."
},
{
"code": null,
"e": 3108,
"s": 3092,
"text": "GetMonthCalFont"
},
{
"code": null,
"e": 3210,
"s": 3108,
"text": "Retrieves the font currently used by the date and time picker control's child month calendar control."
},
{
"code": null,
"e": 3227,
"s": 3210,
"text": "GetMonthCalStyle"
},
{
"code": null,
"e": 3287,
"s": 3227,
"text": "Gets the style of the current date and time picker control."
},
{
"code": null,
"e": 3296,
"s": 3287,
"text": "GetRange"
},
{
"code": null,
"e": 3395,
"s": 3296,
"text": "Retrieves the current minimum and maximum allowed system times for a date and time picker control."
},
{
"code": null,
"e": 3403,
"s": 3395,
"text": "GetTime"
},
{
"code": null,
"e": 3526,
"s": 3403,
"text": "Retrieves the currently selected time from a date and time picker control and puts it in a specified SYSTEMTIME structure."
},
{
"code": null,
"e": 3536,
"s": 3526,
"text": "SetFormat"
},
{
"code": null,
"e": 3629,
"s": 3536,
"text": "Sets the display of a date and time picker control in accordance with a given format string."
},
{
"code": null,
"e": 3646,
"s": 3629,
"text": "SetMonthCalColor"
},
{
"code": null,
"e": 3742,
"s": 3646,
"text": "Sets the color for a given portion of the month calendar within a date and time picker control."
},
{
"code": null,
"e": 3758,
"s": 3742,
"text": "SetMonthCalFont"
},
{
"code": null,
"e": 3851,
"s": 3758,
"text": "Sets the font that the date and time picker control's child month calendar control will use."
},
{
"code": null,
"e": 3868,
"s": 3851,
"text": "SetMonthCalStyle"
},
{
"code": null,
"e": 3928,
"s": 3868,
"text": "Sets the style of the current date and time picker control."
},
{
"code": null,
"e": 3937,
"s": 3928,
"text": "SetRange"
},
{
"code": null,
"e": 3997,
"s": 3937,
"text": "Sets the style of the current date and time picker control."
},
{
"code": null,
"e": 4005,
"s": 3997,
"text": "SetTime"
},
{
"code": null,
"e": 4054,
"s": 4005,
"text": "Sets the time in a date and time picker control."
},
{
"code": null,
"e": 4123,
"s": 4054,
"text": "Let us look into a simple example by creating a new MFC application."
},
{
"code": null,
"e": 4185,
"s": 4123,
"text": "Step 1 − Remove the Caption and set its ID to IDC_STATIC_TXT."
},
{
"code": null,
"e": 4235,
"s": 4185,
"text": "Step 2 − Add the value variable for text control."
},
{
"code": null,
"e": 4279,
"s": 4235,
"text": "Step 3 − Drag the Date Time Picker control."
},
{
"code": null,
"e": 4333,
"s": 4279,
"text": "Step 4 − Add a control variable for Date Time Picker."
},
{
"code": null,
"e": 4386,
"s": 4333,
"text": "Step 5 − Add the Event handler for Date Time Picker."
},
{
"code": null,
"e": 4441,
"s": 4386,
"text": "Step 6 − Here is the implementation of event handler."
},
{
"code": null,
"e": 4786,
"s": 4441,
"text": "void CMFCDateAndTimePickerDlg::OnDtnDatetimechangeDatetimepicker1(NMHDR *pNMHDR, LRESULT *pResult){ \n LPNMDATETIMECHANGE pDTChange = reinterpret_cast <LPNMDATETIMECHANGE>(pNMHDR); \n // TODO: Add your control notification handler code here \n \n GetDlgItemText(IDC_DATETIMEPICKER1, m_strValue); \n UpdateData(FALSE); \n *pResult = 0; \n} "
},
{
"code": null,
"e": 4922,
"s": 4786,
"text": "Step 7 − When you run the above application, you see the following output. Select any date, it will display on the Static Text Control."
},
{
"code": null,
"e": 4929,
"s": 4922,
"text": " Print"
},
{
"code": null,
"e": 4940,
"s": 4929,
"text": " Add Notes"
}
] |
Diagonal of a Regular Hexagon - GeeksforGeeks | 17 Mar, 2021
Given an integer a which is the side of a regular hexagon, the task is to find and print the length of its diagonal.Examples:
Input: a = 6 Output: 10.38Input: a = 9 Output: 15.57
Approach: We know that the sum of interior angles of a polygon = (n – 2) * 180 where, n is the number of sides of the polygon. So, sum of interior angles of a hexagon = 4 * 180 = 720 and each interior angle will be 120. Now, we have to find BC = 2 * x. If we draw a perpendicular AO on BC, we will see that the perpendicular bisects BC in BO and OC, as triangles AOB and AOC are congruent to each other. So, in triangle AOB, sin(60) = x / a i.e. x = 0.866 * a Therefore, diagonal length will be 2 * x i.e. 1.73 * a.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find the diagonal// of a regular hexagon#include <bits/stdc++.h>using namespace std; // Function to find the diagonal// of a regular hexagonfloat hexDiagonal(float a){ // Side cannot be negative if (a < 0) return -1; // Length of the diagonal float d = 1.73 * a; return d;} // Driver codeint main(){ float a = 9; cout << hexDiagonal(a) << endl; return 0;}
// Java Program to find the diagonal// of a regular hexagon public class GFG{ // Function to find the diagonal // of a regular hexagon static double hexDiagonal(float a) { // Side cannot be negative if (a < 0) return -1; // Length of the diagonal double d = (double)1.73 * a; return d; } // Driver code public static void main(String []args) { float a = 9; System.out.println(hexDiagonal(a)) ; } // This code is contributed by Ryuga}
# Python3 Program to find the diagonal# of a regular hexagon # Function to find the diagonal# of a regular hexagondef hexDiagonal(a): # Side cannot be negative if (a < 0): return -1; # Length of the diagonal d = 1.73 * a; return d; # Driver codea = 9;print(hexDiagonal(a)); # This code is contributed# by Akanksha Rai
// C# Program to find the diagonal // of a regular hexagonusing System ;public class GFG{ // Function to find the diagonal // of a regular hexagon static double hexDiagonal(float a) { // Side cannot be negative if (a < 0) return -1; // Length of the diagonal double d = (double)1.73 * a; return d; } // Driver code public static void Main() { float a = 9; Console.WriteLine(hexDiagonal(a)) ; } // This code is contributed by Subhadeep}
<?php// PHP Program to find the diagonal// of a regular hexagon // Function to find the diagonal// of a regular hexagonfunction hexDiagonal($a){ // Side cannot be negative if ($a < 0) return -1; // Length of the diagonal $d = 1.73 * $a; return $d;} // Driver code$a = 9;echo hexDiagonal($a), "\n"; // This code is contributed// by akt_mit?>
<script>// javascript Program to find the diagonal// of a regular hexagon // Function to find the diagonal// of a regular hexagonfunction hexDiagonal(a){ // Side cannot be negative if (a < 0) return -1; // Length of the diagonal var d = 1.73 * a; return d;} // Driver codevar a = 9;document.write(hexDiagonal(a)) ; // This code contributed by Princi Singh</script>
15.57
ankthon
tufan_gupta2000
jit_t
Akanksha_Rai
princi singh
C++ Programs
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program for QuickSort
cin in C++
delete keyword in C++
CSV file management using C++
Shallow Copy and Deep Copy in C++
Closest Pair of Points using Divide and Conquer algorithm
How to check if two given line segments intersect?
How to check if a given point lies inside or outside a polygon?
Find if two rectangles overlap
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) | [
{
"code": null,
"e": 24920,
"s": 24892,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 25048,
"s": 24920,
"text": "Given an integer a which is the side of a regular hexagon, the task is to find and print the length of its diagonal.Examples: "
},
{
"code": null,
"e": 25103,
"s": 25048,
"text": "Input: a = 6 Output: 10.38Input: a = 9 Output: 15.57 "
},
{
"code": null,
"e": 25675,
"s": 25107,
"text": "Approach: We know that the sum of interior angles of a polygon = (n – 2) * 180 where, n is the number of sides of the polygon. So, sum of interior angles of a hexagon = 4 * 180 = 720 and each interior angle will be 120. Now, we have to find BC = 2 * x. If we draw a perpendicular AO on BC, we will see that the perpendicular bisects BC in BO and OC, as triangles AOB and AOC are congruent to each other. So, in triangle AOB, sin(60) = x / a i.e. x = 0.866 * a Therefore, diagonal length will be 2 * x i.e. 1.73 * a.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25679,
"s": 25675,
"text": "C++"
},
{
"code": null,
"e": 25684,
"s": 25679,
"text": "Java"
},
{
"code": null,
"e": 25692,
"s": 25684,
"text": "Python3"
},
{
"code": null,
"e": 25695,
"s": 25692,
"text": "C#"
},
{
"code": null,
"e": 25699,
"s": 25695,
"text": "PHP"
},
{
"code": null,
"e": 25710,
"s": 25699,
"text": "Javascript"
},
{
"code": "// C++ Program to find the diagonal// of a regular hexagon#include <bits/stdc++.h>using namespace std; // Function to find the diagonal// of a regular hexagonfloat hexDiagonal(float a){ // Side cannot be negative if (a < 0) return -1; // Length of the diagonal float d = 1.73 * a; return d;} // Driver codeint main(){ float a = 9; cout << hexDiagonal(a) << endl; return 0;}",
"e": 26117,
"s": 25710,
"text": null
},
{
"code": "// Java Program to find the diagonal// of a regular hexagon public class GFG{ // Function to find the diagonal // of a regular hexagon static double hexDiagonal(float a) { // Side cannot be negative if (a < 0) return -1; // Length of the diagonal double d = (double)1.73 * a; return d; } // Driver code public static void main(String []args) { float a = 9; System.out.println(hexDiagonal(a)) ; } // This code is contributed by Ryuga}",
"e": 26657,
"s": 26117,
"text": null
},
{
"code": "# Python3 Program to find the diagonal# of a regular hexagon # Function to find the diagonal# of a regular hexagondef hexDiagonal(a): # Side cannot be negative if (a < 0): return -1; # Length of the diagonal d = 1.73 * a; return d; # Driver codea = 9;print(hexDiagonal(a)); # This code is contributed# by Akanksha Rai",
"e": 27000,
"s": 26657,
"text": null
},
{
"code": "// C# Program to find the diagonal // of a regular hexagonusing System ;public class GFG{ // Function to find the diagonal // of a regular hexagon static double hexDiagonal(float a) { // Side cannot be negative if (a < 0) return -1; // Length of the diagonal double d = (double)1.73 * a; return d; } // Driver code public static void Main() { float a = 9; Console.WriteLine(hexDiagonal(a)) ; } // This code is contributed by Subhadeep}",
"e": 27566,
"s": 27000,
"text": null
},
{
"code": "<?php// PHP Program to find the diagonal// of a regular hexagon // Function to find the diagonal// of a regular hexagonfunction hexDiagonal($a){ // Side cannot be negative if ($a < 0) return -1; // Length of the diagonal $d = 1.73 * $a; return $d;} // Driver code$a = 9;echo hexDiagonal($a), \"\\n\"; // This code is contributed// by akt_mit?>",
"e": 27931,
"s": 27566,
"text": null
},
{
"code": "<script>// javascript Program to find the diagonal// of a regular hexagon // Function to find the diagonal// of a regular hexagonfunction hexDiagonal(a){ // Side cannot be negative if (a < 0) return -1; // Length of the diagonal var d = 1.73 * a; return d;} // Driver codevar a = 9;document.write(hexDiagonal(a)) ; // This code contributed by Princi Singh</script>",
"e": 28328,
"s": 27931,
"text": null
},
{
"code": null,
"e": 28334,
"s": 28328,
"text": "15.57"
},
{
"code": null,
"e": 28344,
"s": 28336,
"text": "ankthon"
},
{
"code": null,
"e": 28360,
"s": 28344,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 28366,
"s": 28360,
"text": "jit_t"
},
{
"code": null,
"e": 28379,
"s": 28366,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28392,
"s": 28379,
"text": "princi singh"
},
{
"code": null,
"e": 28405,
"s": 28392,
"text": "C++ Programs"
},
{
"code": null,
"e": 28415,
"s": 28405,
"text": "Geometric"
},
{
"code": null,
"e": 28428,
"s": 28415,
"text": "Mathematical"
},
{
"code": null,
"e": 28441,
"s": 28428,
"text": "Mathematical"
},
{
"code": null,
"e": 28451,
"s": 28441,
"text": "Geometric"
},
{
"code": null,
"e": 28549,
"s": 28451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28575,
"s": 28549,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 28586,
"s": 28575,
"text": "cin in C++"
},
{
"code": null,
"e": 28608,
"s": 28586,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 28638,
"s": 28608,
"text": "CSV file management using C++"
},
{
"code": null,
"e": 28672,
"s": 28638,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 28730,
"s": 28672,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 28781,
"s": 28730,
"text": "How to check if two given line segments intersect?"
},
{
"code": null,
"e": 28845,
"s": 28781,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 28876,
"s": 28845,
"text": "Find if two rectangles overlap"
}
] |
Delete Alternate Nodes | Practice | GeeksforGeeks | Given a Singly Linked List of size N, delete all alternate nodes of the list.
Example 1:
Input:
LinkedList: 1->2->3->4->5->6
Output: 1->3->5
Explanation: Deleting alternate nodes
results in the linked list with elements
1->3->5.
Example 2:
Input:
LinkedList: 99->59->42->20
Output: 99->42
Your Task:
Your task is to complete the function deleteAlt() which takes the head of the linked list in the input parameter and modifies the given linked list accordingly.
Constraints:
1<=N<=100
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
0
neelasatyasai933 days ago
#PYTHON def deleteAlt(self, head): temp=head while temp!=None: if temp.next !=None: temp.next=temp.next.next temp=temp.next else: return head return head
0
navins3 days ago
Python Code:
def deleteAlt(self, head): #add code here temp=head count=1 while temp is not None: if temp.next is not None: temp.next=temp.next.next temp=temp.next else: return head return head
0
rohanpandey7491 month ago
Simple C++ solution:
void deleteAlt(struct Node *head){
// Code here
Node *temp=head;
while(temp && temp->next){
temp->next=temp->next->next;
temp=temp->next;
}
}
0
gupta2411sumit1 month ago
// Easy Java Solution
public void deleteAlternate (Node head){ //Write your code here Node p = head ; if(head == null) return ; while(p != null) { if( p==null || p.next == null) return ; p.next = p.next.next ; p = p.next ; } }
0
yasirkhan2012371 month ago
void deleteAlt(struct Node *head){ // Code here if(head == NULL||head->next == NULL){ return; } Node*prev = head; while (prev!=NULL &&prev->next!=NULL ){ Node* t = prev->next; prev->next= prev->next->next; prev = prev->next; delete t; }}
0
0niharika22 months ago
while(head && head->next){
Node *store = head->next;
head->next = head->next->next;
delete store;
head = head->next;
}
0
0niharika22 months ago
void deleteAlt(struct Node *head){
while(head && head->next){
head->next = head->next->next;
head = head->next;
}
}
0
owaischem2 months ago
PYTHON SOLUTION:
TIME TAKEN:0.0/1.0
class Solution: def deleteAlt(self, head): n=head head=n if n.next==None: return head while n!=None: n.next=n.next.next n=n.next if n==None: break elif n.next==None: break return head
+1
mayank20212 months ago
C++void deleteAlt(struct Node *head){ Node *temp=head; while(temp) { if( temp->next ) { temp->next=temp->next->next; temp=temp->next; } else break; } }
0
sobhitraj1002 months ago
method 1
def deleteAlt(self, head): # count=1 # c=1 #prev=None #curr=head #while curr!=None : # curr=curr.next # c+=1 # curr=head # while count!=c: # count+=1 # if count%2==0: # prev=curr # curr=curr.next # if curr is not None: # prev.next=curr.next # else: # pass # else: # prev=curr # curr=curr.next method 2 for i in range(math.floor(n/2)): head.next=head.next.next head=head.next return
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": 316,
"s": 238,
"text": "Given a Singly Linked List of size N, delete all alternate nodes of the list."
},
{
"code": null,
"e": 327,
"s": 316,
"text": "Example 1:"
},
{
"code": null,
"e": 468,
"s": 327,
"text": "Input:\nLinkedList: 1->2->3->4->5->6\nOutput: 1->3->5\nExplanation: Deleting alternate nodes\nresults in the linked list with elements\n1->3->5.\n"
},
{
"code": null,
"e": 481,
"s": 470,
"text": "Example 2:"
},
{
"code": null,
"e": 531,
"s": 481,
"text": "Input:\nLinkedList: 99->59->42->20\nOutput: 99->42\n"
},
{
"code": null,
"e": 544,
"s": 533,
"text": "Your Task:"
},
{
"code": null,
"e": 705,
"s": 544,
"text": "Your task is to complete the function deleteAlt() which takes the head of the linked list in the input parameter and modifies the given linked list accordingly."
},
{
"code": null,
"e": 730,
"s": 707,
"text": "Constraints:\n1<=N<=100"
},
{
"code": null,
"e": 796,
"s": 732,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 798,
"s": 796,
"text": "0"
},
{
"code": null,
"e": 824,
"s": 798,
"text": "neelasatyasai933 days ago"
},
{
"code": null,
"e": 1053,
"s": 824,
"text": " #PYTHON def deleteAlt(self, head): temp=head while temp!=None: if temp.next !=None: temp.next=temp.next.next temp=temp.next else: return head return head "
},
{
"code": null,
"e": 1055,
"s": 1053,
"text": "0"
},
{
"code": null,
"e": 1072,
"s": 1055,
"text": "navins3 days ago"
},
{
"code": null,
"e": 1085,
"s": 1072,
"text": "Python Code:"
},
{
"code": null,
"e": 1364,
"s": 1085,
"text": "def deleteAlt(self, head): #add code here temp=head count=1 while temp is not None: if temp.next is not None: temp.next=temp.next.next temp=temp.next else: return head return head"
},
{
"code": null,
"e": 1368,
"s": 1366,
"text": "0"
},
{
"code": null,
"e": 1394,
"s": 1368,
"text": "rohanpandey7491 month ago"
},
{
"code": null,
"e": 1416,
"s": 1394,
"text": "Simple C++ solution: "
},
{
"code": null,
"e": 1590,
"s": 1416,
"text": "void deleteAlt(struct Node *head){\n // Code here\n Node *temp=head;\n while(temp && temp->next){\n temp->next=temp->next->next;\n temp=temp->next;\n }\n}"
},
{
"code": null,
"e": 1592,
"s": 1590,
"text": "0"
},
{
"code": null,
"e": 1618,
"s": 1592,
"text": "gupta2411sumit1 month ago"
},
{
"code": null,
"e": 1641,
"s": 1618,
"text": "// Easy Java Solution "
},
{
"code": null,
"e": 1997,
"s": 1641,
"text": "public void deleteAlternate (Node head){ //Write your code here Node p = head ; if(head == null) return ; while(p != null) { if( p==null || p.next == null) return ; p.next = p.next.next ; p = p.next ; } }"
},
{
"code": null,
"e": 1999,
"s": 1997,
"text": "0"
},
{
"code": null,
"e": 2026,
"s": 1999,
"text": "yasirkhan2012371 month ago"
},
{
"code": null,
"e": 2306,
"s": 2026,
"text": "void deleteAlt(struct Node *head){ // Code here if(head == NULL||head->next == NULL){ return; } Node*prev = head; while (prev!=NULL &&prev->next!=NULL ){ Node* t = prev->next; prev->next= prev->next->next; prev = prev->next; delete t; }}"
},
{
"code": null,
"e": 2308,
"s": 2306,
"text": "0"
},
{
"code": null,
"e": 2331,
"s": 2308,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 2486,
"s": 2331,
"text": "while(head && head->next){\n Node *store = head->next;\n head->next = head->next->next;\n delete store;\n head = head->next;\n }"
},
{
"code": null,
"e": 2488,
"s": 2486,
"text": "0"
},
{
"code": null,
"e": 2511,
"s": 2488,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 2651,
"s": 2511,
"text": "void deleteAlt(struct Node *head){\n while(head && head->next){\n head->next = head->next->next;\n head = head->next;\n }\n}"
},
{
"code": null,
"e": 2653,
"s": 2651,
"text": "0"
},
{
"code": null,
"e": 2675,
"s": 2653,
"text": "owaischem2 months ago"
},
{
"code": null,
"e": 2692,
"s": 2675,
"text": "PYTHON SOLUTION:"
},
{
"code": null,
"e": 2711,
"s": 2692,
"text": "TIME TAKEN:0.0/1.0"
},
{
"code": null,
"e": 3019,
"s": 2713,
"text": "class Solution: def deleteAlt(self, head): n=head head=n if n.next==None: return head while n!=None: n.next=n.next.next n=n.next if n==None: break elif n.next==None: break return head"
},
{
"code": null,
"e": 3022,
"s": 3019,
"text": "+1"
},
{
"code": null,
"e": 3045,
"s": 3022,
"text": "mayank20212 months ago"
},
{
"code": null,
"e": 3283,
"s": 3045,
"text": "C++void deleteAlt(struct Node *head){ Node *temp=head; while(temp) { if( temp->next ) { temp->next=temp->next->next; temp=temp->next; } else break; } }"
},
{
"code": null,
"e": 3285,
"s": 3283,
"text": "0"
},
{
"code": null,
"e": 3310,
"s": 3285,
"text": "sobhitraj1002 months ago"
},
{
"code": null,
"e": 3319,
"s": 3310,
"text": "method 1"
},
{
"code": null,
"e": 4053,
"s": 3319,
"text": "def deleteAlt(self, head): # count=1 # c=1 #prev=None #curr=head #while curr!=None : # curr=curr.next # c+=1 # curr=head # while count!=c: # count+=1 # if count%2==0: # prev=curr # curr=curr.next # if curr is not None: # prev.next=curr.next # else: # pass # else: # prev=curr # curr=curr.next method 2 for i in range(math.floor(n/2)): head.next=head.next.next head=head.next return"
},
{
"code": null,
"e": 4199,
"s": 4053,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4235,
"s": 4199,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4245,
"s": 4235,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4255,
"s": 4245,
"text": "\nContest\n"
},
{
"code": null,
"e": 4318,
"s": 4255,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4466,
"s": 4318,
"text": "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."
},
{
"code": null,
"e": 4674,
"s": 4466,
"text": "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."
},
{
"code": null,
"e": 4780,
"s": 4674,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
What are Base and Derived Classes in C#? | A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.
For example, Vehicle Base class with the following Derived Classes.
Truck
Bus
Motobike
The derived class inherits the base class member variables and member methods.
In the same way, the derived class for Shape class can be Rectangle as in the following example.
Live Demo
using System;
namespace Program {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape {
public int getArea() {
return (width * height);
}
}
class Demo {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
Total area: 35 | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces."
},
{
"code": null,
"e": 1285,
"s": 1217,
"text": "For example, Vehicle Base class with the following Derived Classes."
},
{
"code": null,
"e": 1304,
"s": 1285,
"text": "Truck\nBus\nMotobike"
},
{
"code": null,
"e": 1383,
"s": 1304,
"text": "The derived class inherits the base class member variables and member methods."
},
{
"code": null,
"e": 1480,
"s": 1383,
"text": "In the same way, the derived class for Shape class can be Rectangle as in the following example."
},
{
"code": null,
"e": 1491,
"s": 1480,
"text": " Live Demo"
},
{
"code": null,
"e": 2158,
"s": 1491,
"text": "using System;\nnamespace Program {\n class Shape {\n public void setWidth(int w) {\n width = w;\n }\n public void setHeight(int h) {\n height = h;\n }\n protected int width;\n protected int height;\n }\n // Derived class\n class Rectangle: Shape {\n public int getArea() {\n return (width * height);\n }\n }\n class Demo {\n static void Main(string[] args) {\n Rectangle Rect = new Rectangle();\n Rect.setWidth(5);\n Rect.setHeight(7);\n // Print the area of the object.\n Console.WriteLine(\"Total area: {0}\", Rect.getArea());\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2173,
"s": 2158,
"text": "Total area: 35"
}
] |
Program to print all the numbers divisible by 3 and 5 in C++ | In this tutorial, we will be discussing a program to print all the numbers divisible by 3
and 5 less than the given number.
For this we will be given with a number say N. Our task is to print all the numbers less than N which are divisible by both 3 and 5.
Live Demo
#include <iostream>
using namespace std;
//printing the numbers divisible by 3 and 5
void print_div(int N){
for (int num = 0; num < N; num++){
if (num % 3 == 0 && num % 5 == 0)
cout << num << " ";
}
}
int main(){
int N = 70;
print_div(N);
return 0;
}
0 15 30 45 60 | [
{
"code": null,
"e": 1186,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to print all the numbers divisible by 3\nand 5 less than the given number."
},
{
"code": null,
"e": 1319,
"s": 1186,
"text": "For this we will be given with a number say N. Our task is to print all the numbers less than N which are divisible by both 3 and 5."
},
{
"code": null,
"e": 1330,
"s": 1319,
"text": " Live Demo"
},
{
"code": null,
"e": 1608,
"s": 1330,
"text": "#include <iostream>\nusing namespace std;\n//printing the numbers divisible by 3 and 5\nvoid print_div(int N){\n for (int num = 0; num < N; num++){\n if (num % 3 == 0 && num % 5 == 0)\n cout << num << \" \";\n }\n}\nint main(){\n int N = 70;\n print_div(N);\n return 0;\n}"
},
{
"code": null,
"e": 1622,
"s": 1608,
"text": "0 15 30 45 60"
}
] |
Set-up of a personal GPU server for Machine Learning with Ubuntu 20.04 | by Gleb Lukicov | Towards Data Science | The benefit of using GPUs for your ML workflow has been discussed previously. The goal of this article is to summarise the steps in setting up a machine for personal ML projects. I followed a similar guide from 2017 and found that a lot of steps have changed since then — for the better — in 2020. Additionally, I will suggest a few procedures that will make your remote workflow more straightforward and more secure, based on my experience working with the DAQ systems during my PhD.
By the end of the article, you will be able to launch a remote JupyterLab session running on the GPU-host machine, from your laptop. Moreover, you will be able to remotely switch-on the machine from anywhere and mount its filesystem directly on your laptop.
Installing and setting Ubuntu 20.04 (stand-alone/dual-boot/WLS2)Setting remote access (ssh, WOL, DNS configuration, port-forwarding)Taking care of NVIDIA drivers and libraries (CUDA, cuDNN)Creating a Python environment for ML (TensorFlow, JupyterLab)Ease-of-life tools: mounting remote directories with SSHFS, setting some commonly-used commands as bash aliases
Installing and setting Ubuntu 20.04 (stand-alone/dual-boot/WLS2)
Setting remote access (ssh, WOL, DNS configuration, port-forwarding)
Taking care of NVIDIA drivers and libraries (CUDA, cuDNN)
Creating a Python environment for ML (TensorFlow, JupyterLab)
Ease-of-life tools: mounting remote directories with SSHFS, setting some commonly-used commands as bash aliases
Laptop/Desktop PC on which you usually work. I use MacBook Pro 2015 running macOS 10.15.A machine with a GPU, this can be your current gaming PC, for example. You do not need to blow your budget on an expensive GPU to get started with training your DNNs! My hardware is currently rather modest:CPU: AMD Ryzen 5 2600X (3.6 GHz, six-core)GPU: NVIDIA GTX 1660 (6GB VRAM)RAM: 16 GB (DDR4 3200 MHz)Storage: 512 GB NVMe M.2 (SSD), 512 GB HDDPSU: 700 W You will also need a monitor, keyboard and mouse until we are done with setting remote access.Admin-level access to the settings of your router (optional)Some familiarity with Linux and terminal
Laptop/Desktop PC on which you usually work. I use MacBook Pro 2015 running macOS 10.15.
A machine with a GPU, this can be your current gaming PC, for example. You do not need to blow your budget on an expensive GPU to get started with training your DNNs! My hardware is currently rather modest:CPU: AMD Ryzen 5 2600X (3.6 GHz, six-core)GPU: NVIDIA GTX 1660 (6GB VRAM)RAM: 16 GB (DDR4 3200 MHz)Storage: 512 GB NVMe M.2 (SSD), 512 GB HDDPSU: 700 W You will also need a monitor, keyboard and mouse until we are done with setting remote access.
Admin-level access to the settings of your router (optional)
Some familiarity with Linux and terminal
Windows OS is no good — in my opinion and that of others — for doing any ML development or networking work. Therefore, we will set-up a Linux OS for that purpose. Ubuntu Desktop 20.04 (download here) is an ideal choice for that, as a lot of functionally works out-of-the-box, allowing us to save on the set-up time as compared to the other Linux distributions. You have three options to proceed:
Install Ubuntu only.Dual-booting Ubuntu alongside an existing Windows OS. Follow the instruction here (recommended option).Use WSL2 (Windows Subsystem for Linux); this is discussed here. Warning: I have never tested this option (you are on your own here!).
Install Ubuntu only.
Dual-booting Ubuntu alongside an existing Windows OS. Follow the instruction here (recommended option).
Use WSL2 (Windows Subsystem for Linux); this is discussed here. Warning: I have never tested this option (you are on your own here!).
I recommend option #2, to preserve access to Windows (e.g. for gaming-related purposes). Make sure to connect your machine to the internet during the installation to get the latest updates and drivers.
After the installation, login and update and install necessary packages, e.g.
sudo apt-get update &&sudo apt-get -y upgrade &&sudo apt-get -y install build-essential gcc g++ make binutils &&sudo apt-get -y install software-properties-common git &&sudo apt-get install build-essential cmake git pkg-config
In this section, we will set-up a secure way to remotely log in to the machine. Option to access the GPU machine from any network is also discussed.
For now, login into Ubuntu, open the terminal and install the ssh-server:
sudo apt update &&sudo apt install openssh-server
After that, verify the ssh-server was installed correctly
sudo systemctl status ssh
and open the firewall
sudo ufw allow ssh
Test your ssh connection by running, from your laptop (which is assumed to be connected to the same network as your GPU machine)
ssh user@<local-ip-address>
where user is your Ubuntu username, while your local IP address on Ubuntu (e.g. 172.148.0.14) can be found with ip add, yielding (e.g.)
link/ether b3:21:88:6k:17:24 brd ff:ff:ff:ff:ff:ffinet 172.148.0.14/32 scope global noprefixroute enp7s3
Make a note of your MAC address (e.g. b3:21:88:6k:17:24) and network card name (e.g. enp7s3), for later.
Next, set-up ssh keys for password-less login as described here. After that, assuming you will only ever want to login to your machine from this laptop, disable the option to log in with a password altogether. This will only allow for ssh connections from devices with the ssh-key pair already exchanged, improving on security. Edit /etc/ssh/sshd_config (with sudo-privileges) on Ubuntu to add
#only ssh-key logins PermitRootLogin noChallengeResponseAuthentication noPasswordAuthentication noUsePAM noAllowUsers userPubkeyAuthentication yes# keep ssh connection alive ClientAliveInterval 60TCPKeepAlive yesClientAliveCountMax 10000
Don’t forget to restart ssh-service for it to pick-up on the changes with
sudo restart ssh
If you want to ssh to your machine from outside your home network, you will need to establish a permanent DNS ‘hostname’ that is independent of your machine’s global IP addresses, which your ISP can change at any time. I have personally used free service from no-IP (link here, to get started use “Create Your Free Hostname Now” from Ubuntu’s browser); alternative DNS services exist like FreeDNS, Dynu etc. Be creative with your hostname; I cannot believe mlgpu.ddns.net is not yet taken. This hostname will be used as an example in this article.
After that, install the Dynamic Update Client (DUC) as described here. This ensures that when your global IP does change, it is re-linked to your hostname (i.e. mlgpu.ddns.net). To ensure DUC is started every time with Ubuntu, add a new cronjob with sudo crontab -e (i.e. add this line to the end of the file)
@reboot su -l user && sudo noip2
and reboot your machine.
ssh by default uses port 22 for the connection. We need to open this port (for both TCP and UDP protocols) through the router to be able to ssh to the machine from an outside network (you still want to submit those GPU-intensive jobs from a coffee shop, right?). This setting is usually found under “Advanced/Security” tab. Below is a screenshot of my router settings
Optional: While digging through your router settings, add your Ubuntu’s network card MAC address and local IP to the reserved list (‘Add reserved rule’), and save your router settings to a file (in case you need to reload this at a later date).
Finally, on your laptop, edit ~/.ssh/config replacing user with your Ubuntu's user name, and HostName with your DNS hostname
# keep ssh connection aliveTCPKeepAlive yesServerAliveInterval 60# assign a 'shortcut' for hostname and enable graphical display over ssh (X11) Host mlgpuHostName mlgpu.ddns.netGSSAPIAuthentication yesUser userForwardX11Trusted yesForwardX11 yesGSSAPIDelegateCredentials yes
This will allow you ssh to your machine quickly and test that the DNS and port-forwarding are working with
ssh mlgpu
This should NOT ask you for the password, and you can now ssh to your GPU machine from any network!
Imagine a scenario where you are at a conference (before 2020 those took place at a remote location other than your home — bizarre, I know!) and you want to train your DNN on your GPU machine. But wait, you turned it off before leaving your house — oh dear!
This is where WAL and magic packets come in!
On Ubuntu, edit /etc/systemd/system/[email protected]
[Unit]Description=Wake-on-LAN for %iRequires=network.targetAfter=network.target[Service]ExecStart=/sbin/ethtool -s %i wol gType=oneshot[Install]WantedBy=multi-user.target
After that, enable WOL service via
sudo systemctl enable wol@enp7s3 && systemctl is-enabled wol@np7s3
This should return ‘enabled’; enp7s3 is the network card name returned with ip add command. Finally, check your BIOS setting for "wake-on-lan" = enabled.
Now, on your laptop, install wakeonlan via
brew install wakeonlan
To test WOL is working, shutdown Ubuntu and issue the following command from your laptop using your DNS hostname (or IP address) and MAC address
wakeonlan -i mlgpu.ddns.net -p 22 b3:21:88:6k:17:24
This should wake-up your GPU-machine from sleep or powered-off state (make sure it’s still connected to power, of course!). If you went for the dual-boot option, and Ubuntu is not the first OS in the boot menu, adjust this with the GRUB.
That’s it: unplug your monitor, keyboard, and mouse from your GPU machine, from here we will issue all the commands from a remote ssh session running on Ubuntu from your laptop — neat!
More good news ahead. Ubuntu 20.04 should automatically install Nvidia drivers for you (instead of the nouveau ones). Let’s verify this with nvidia-smi
This is not the latest version of the drivers. However, we might want to keep them to install CUDA and cuDNN from the standard Ubuntu repositories.
Simply install CUDA
sudo apt update &&sudo apt install nvidia-cuda-toolkit
Verify with nvcc --version
Finally, build your first CUDA ‘Hello World’ example using the file from here
nvcc -o hello hello.cu &&./hello
‘Max error: 0.000000’ means your CUDA libraries are working as expected!
Finally, download the cuDNN v7.6.5 (November 5th, 2019) for CUDA 10.1 (or for the version of your CUDA release from nvcc --version). You need to register a free account with the NVIDIA Developer programme to download cuDNN.
From the unpacked tarball copy the libraries using:
sudo cp cuda/include/cudnn.h /usr/lib/cuda/include/ &&sudo cp cuda/lib64/libcudnn* /usr/lib/cuda/lib64/ &&sudo chmod a+r /usr/lib/cuda/include/cudnn.h /usr/lib/cuda/lib64/libcudnn*
and export the libraries to $LD_LIBRARY_PATH
echo 'export LD_LIBRARY_PATH=/usr/lib/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrc &&echo 'export LD_LIBRARY_PATH=/usr/lib/cuda/include:$LD_LIBRARY_PATH' >> ~/.bashrc &&source ~/.bashrc
Job’s done!
On Linux and macOS, my personal preference is to use pip instead of conda to manage Python packages and environments. Below are instructions to set your ML Python3 environment:
First of all, get the latest Python3
sudo apt update &&sudo apt install python3-pip python3-dev
Then, upgrade pip and install the environment manager
sudo -H pip3 install --upgrade pipsudo -H pip3 install virtualenv
Next, we will create a new directory for our GPU-based projects
mkdir ~/gpu_ml &&cd ~/gpu_ml
and instantiate a new Python environment there
virtualenv gpu_ml_env
This will allow us to install packages directly in that environment, as opposed to the ‘global’ installation. This environment needs to be activated (each login) with
source ~/gpu_ml/bin/activate
You should see (gpu_ml_env) in your terminal. Now, let's install Python packages in that environment (pip == pip3 in that environment)
pip install jupyterlab &&pip install tensorflow &&pip install tensorflow-gpu
Any other Python packages you need can be installed similarly.
There are some commands I recommend adding to your ~/.bash_aliases in Ubuntu. They will activate the gpu_ml environment on each login, as well as adding some helpful "terminal shortcuts" (life is too short to type 'jupyter lab' instead of 'jlab', right!?). The commands are below (alternative link)
On your laptop, you might want to add those lines to your ~/.profile, replacing ML with your DNS hostname (or IP address) and using your MAC address from step #2. The commands are below (alternative link)
Install FUSE for macOS from here, adjust the following script whereremotedir="user@$ML:/home/user/", and mountdir="/Users/user/Documents/Ubuntu_mount" is the directory on your macOS where the files on Ubuntu will be mounted. The script is below (alternative link)
Run the script with
. ./mount.sh
and navigate to /Users/user/Documents/Ubuntu_mount(or simply type cd_ML)on your macOS to see Ubuntu files as "local files". You can now open and edit remote Ubuntu files with your favourite editor from your laptop, and much more — neat!
Let’s do the final test of this set-up (fingers crossed!). From your laptop
sg
which stands forssh -L 8899:localhost:8899 mlgpu.ddns.net from our 'bash shortcuts'. This should open an ssh-tunnel on port 8899, and log in to the Ubuntu, from that session type
jlab
which is the bash shortcut for jupyter lab --port=8899 .
Now, open your favourite web browser on your laptop and navigate tohttp://localhost:8899/lab . The first time, you will need to paste a token from your terminal into the browser (e.g. The Jupyter Notebook is running at:http://localhost:8899/?token=583049XXYZ... )
In JupyterLab, sanity-check that we are indeed running this notebook from Linux
import platformplatform.system()
and that Tensorflow detects the GPU
import tensorflow as tftf.config.list_physical_devices(‘GPU’)
From here you are ready to implement your DNN training etc. using a GPU. If you followed all the steps in sections #1 to #5, your workflow is rather simple:
1. ssh and open an ssh-tunnel to your GPU server with sg 2. Start JupyterLab on the GPU server with jlab 3. Open a web browser on your laptop and go to http://localhost:8899/lab 4. Happy training — the real work begins here!
I hope you found this article useful in helping you to set-up your remote GPU server for your ML needs. If you find any improvements to the procedures in this article, please let me know, and I will do my best to add them here. | [
{
"code": null,
"e": 656,
"s": 171,
"text": "The benefit of using GPUs for your ML workflow has been discussed previously. The goal of this article is to summarise the steps in setting up a machine for personal ML projects. I followed a similar guide from 2017 and found that a lot of steps have changed since then — for the better — in 2020. Additionally, I will suggest a few procedures that will make your remote workflow more straightforward and more secure, based on my experience working with the DAQ systems during my PhD."
},
{
"code": null,
"e": 914,
"s": 656,
"text": "By the end of the article, you will be able to launch a remote JupyterLab session running on the GPU-host machine, from your laptop. Moreover, you will be able to remotely switch-on the machine from anywhere and mount its filesystem directly on your laptop."
},
{
"code": null,
"e": 1276,
"s": 914,
"text": "Installing and setting Ubuntu 20.04 (stand-alone/dual-boot/WLS2)Setting remote access (ssh, WOL, DNS configuration, port-forwarding)Taking care of NVIDIA drivers and libraries (CUDA, cuDNN)Creating a Python environment for ML (TensorFlow, JupyterLab)Ease-of-life tools: mounting remote directories with SSHFS, setting some commonly-used commands as bash aliases"
},
{
"code": null,
"e": 1341,
"s": 1276,
"text": "Installing and setting Ubuntu 20.04 (stand-alone/dual-boot/WLS2)"
},
{
"code": null,
"e": 1410,
"s": 1341,
"text": "Setting remote access (ssh, WOL, DNS configuration, port-forwarding)"
},
{
"code": null,
"e": 1468,
"s": 1410,
"text": "Taking care of NVIDIA drivers and libraries (CUDA, cuDNN)"
},
{
"code": null,
"e": 1530,
"s": 1468,
"text": "Creating a Python environment for ML (TensorFlow, JupyterLab)"
},
{
"code": null,
"e": 1642,
"s": 1530,
"text": "Ease-of-life tools: mounting remote directories with SSHFS, setting some commonly-used commands as bash aliases"
},
{
"code": null,
"e": 2283,
"s": 1642,
"text": "Laptop/Desktop PC on which you usually work. I use MacBook Pro 2015 running macOS 10.15.A machine with a GPU, this can be your current gaming PC, for example. You do not need to blow your budget on an expensive GPU to get started with training your DNNs! My hardware is currently rather modest:CPU: AMD Ryzen 5 2600X (3.6 GHz, six-core)GPU: NVIDIA GTX 1660 (6GB VRAM)RAM: 16 GB (DDR4 3200 MHz)Storage: 512 GB NVMe M.2 (SSD), 512 GB HDDPSU: 700 W You will also need a monitor, keyboard and mouse until we are done with setting remote access.Admin-level access to the settings of your router (optional)Some familiarity with Linux and terminal"
},
{
"code": null,
"e": 2372,
"s": 2283,
"text": "Laptop/Desktop PC on which you usually work. I use MacBook Pro 2015 running macOS 10.15."
},
{
"code": null,
"e": 2825,
"s": 2372,
"text": "A machine with a GPU, this can be your current gaming PC, for example. You do not need to blow your budget on an expensive GPU to get started with training your DNNs! My hardware is currently rather modest:CPU: AMD Ryzen 5 2600X (3.6 GHz, six-core)GPU: NVIDIA GTX 1660 (6GB VRAM)RAM: 16 GB (DDR4 3200 MHz)Storage: 512 GB NVMe M.2 (SSD), 512 GB HDDPSU: 700 W You will also need a monitor, keyboard and mouse until we are done with setting remote access."
},
{
"code": null,
"e": 2886,
"s": 2825,
"text": "Admin-level access to the settings of your router (optional)"
},
{
"code": null,
"e": 2927,
"s": 2886,
"text": "Some familiarity with Linux and terminal"
},
{
"code": null,
"e": 3323,
"s": 2927,
"text": "Windows OS is no good — in my opinion and that of others — for doing any ML development or networking work. Therefore, we will set-up a Linux OS for that purpose. Ubuntu Desktop 20.04 (download here) is an ideal choice for that, as a lot of functionally works out-of-the-box, allowing us to save on the set-up time as compared to the other Linux distributions. You have three options to proceed:"
},
{
"code": null,
"e": 3580,
"s": 3323,
"text": "Install Ubuntu only.Dual-booting Ubuntu alongside an existing Windows OS. Follow the instruction here (recommended option).Use WSL2 (Windows Subsystem for Linux); this is discussed here. Warning: I have never tested this option (you are on your own here!)."
},
{
"code": null,
"e": 3601,
"s": 3580,
"text": "Install Ubuntu only."
},
{
"code": null,
"e": 3705,
"s": 3601,
"text": "Dual-booting Ubuntu alongside an existing Windows OS. Follow the instruction here (recommended option)."
},
{
"code": null,
"e": 3839,
"s": 3705,
"text": "Use WSL2 (Windows Subsystem for Linux); this is discussed here. Warning: I have never tested this option (you are on your own here!)."
},
{
"code": null,
"e": 4041,
"s": 3839,
"text": "I recommend option #2, to preserve access to Windows (e.g. for gaming-related purposes). Make sure to connect your machine to the internet during the installation to get the latest updates and drivers."
},
{
"code": null,
"e": 4119,
"s": 4041,
"text": "After the installation, login and update and install necessary packages, e.g."
},
{
"code": null,
"e": 4346,
"s": 4119,
"text": "sudo apt-get update &&sudo apt-get -y upgrade &&sudo apt-get -y install build-essential gcc g++ make binutils &&sudo apt-get -y install software-properties-common git &&sudo apt-get install build-essential cmake git pkg-config"
},
{
"code": null,
"e": 4495,
"s": 4346,
"text": "In this section, we will set-up a secure way to remotely log in to the machine. Option to access the GPU machine from any network is also discussed."
},
{
"code": null,
"e": 4569,
"s": 4495,
"text": "For now, login into Ubuntu, open the terminal and install the ssh-server:"
},
{
"code": null,
"e": 4619,
"s": 4569,
"text": "sudo apt update &&sudo apt install openssh-server"
},
{
"code": null,
"e": 4677,
"s": 4619,
"text": "After that, verify the ssh-server was installed correctly"
},
{
"code": null,
"e": 4703,
"s": 4677,
"text": "sudo systemctl status ssh"
},
{
"code": null,
"e": 4725,
"s": 4703,
"text": "and open the firewall"
},
{
"code": null,
"e": 4744,
"s": 4725,
"text": "sudo ufw allow ssh"
},
{
"code": null,
"e": 4873,
"s": 4744,
"text": "Test your ssh connection by running, from your laptop (which is assumed to be connected to the same network as your GPU machine)"
},
{
"code": null,
"e": 4901,
"s": 4873,
"text": "ssh user@<local-ip-address>"
},
{
"code": null,
"e": 5037,
"s": 4901,
"text": "where user is your Ubuntu username, while your local IP address on Ubuntu (e.g. 172.148.0.14) can be found with ip add, yielding (e.g.)"
},
{
"code": null,
"e": 5142,
"s": 5037,
"text": "link/ether b3:21:88:6k:17:24 brd ff:ff:ff:ff:ff:ffinet 172.148.0.14/32 scope global noprefixroute enp7s3"
},
{
"code": null,
"e": 5247,
"s": 5142,
"text": "Make a note of your MAC address (e.g. b3:21:88:6k:17:24) and network card name (e.g. enp7s3), for later."
},
{
"code": null,
"e": 5641,
"s": 5247,
"text": "Next, set-up ssh keys for password-less login as described here. After that, assuming you will only ever want to login to your machine from this laptop, disable the option to log in with a password altogether. This will only allow for ssh connections from devices with the ssh-key pair already exchanged, improving on security. Edit /etc/ssh/sshd_config (with sudo-privileges) on Ubuntu to add"
},
{
"code": null,
"e": 5879,
"s": 5641,
"text": "#only ssh-key logins PermitRootLogin noChallengeResponseAuthentication noPasswordAuthentication noUsePAM noAllowUsers userPubkeyAuthentication yes# keep ssh connection alive ClientAliveInterval 60TCPKeepAlive yesClientAliveCountMax 10000"
},
{
"code": null,
"e": 5953,
"s": 5879,
"text": "Don’t forget to restart ssh-service for it to pick-up on the changes with"
},
{
"code": null,
"e": 5970,
"s": 5953,
"text": "sudo restart ssh"
},
{
"code": null,
"e": 6518,
"s": 5970,
"text": "If you want to ssh to your machine from outside your home network, you will need to establish a permanent DNS ‘hostname’ that is independent of your machine’s global IP addresses, which your ISP can change at any time. I have personally used free service from no-IP (link here, to get started use “Create Your Free Hostname Now” from Ubuntu’s browser); alternative DNS services exist like FreeDNS, Dynu etc. Be creative with your hostname; I cannot believe mlgpu.ddns.net is not yet taken. This hostname will be used as an example in this article."
},
{
"code": null,
"e": 6828,
"s": 6518,
"text": "After that, install the Dynamic Update Client (DUC) as described here. This ensures that when your global IP does change, it is re-linked to your hostname (i.e. mlgpu.ddns.net). To ensure DUC is started every time with Ubuntu, add a new cronjob with sudo crontab -e (i.e. add this line to the end of the file)"
},
{
"code": null,
"e": 6861,
"s": 6828,
"text": "@reboot su -l user && sudo noip2"
},
{
"code": null,
"e": 6886,
"s": 6861,
"text": "and reboot your machine."
},
{
"code": null,
"e": 7254,
"s": 6886,
"text": "ssh by default uses port 22 for the connection. We need to open this port (for both TCP and UDP protocols) through the router to be able to ssh to the machine from an outside network (you still want to submit those GPU-intensive jobs from a coffee shop, right?). This setting is usually found under “Advanced/Security” tab. Below is a screenshot of my router settings"
},
{
"code": null,
"e": 7499,
"s": 7254,
"text": "Optional: While digging through your router settings, add your Ubuntu’s network card MAC address and local IP to the reserved list (‘Add reserved rule’), and save your router settings to a file (in case you need to reload this at a later date)."
},
{
"code": null,
"e": 7624,
"s": 7499,
"text": "Finally, on your laptop, edit ~/.ssh/config replacing user with your Ubuntu's user name, and HostName with your DNS hostname"
},
{
"code": null,
"e": 7966,
"s": 7624,
"text": "# keep ssh connection aliveTCPKeepAlive yesServerAliveInterval 60# assign a 'shortcut' for hostname and enable graphical display over ssh (X11) Host mlgpuHostName mlgpu.ddns.netGSSAPIAuthentication yesUser userForwardX11Trusted yesForwardX11 yesGSSAPIDelegateCredentials yes"
},
{
"code": null,
"e": 8073,
"s": 7966,
"text": "This will allow you ssh to your machine quickly and test that the DNS and port-forwarding are working with"
},
{
"code": null,
"e": 8083,
"s": 8073,
"text": "ssh mlgpu"
},
{
"code": null,
"e": 8183,
"s": 8083,
"text": "This should NOT ask you for the password, and you can now ssh to your GPU machine from any network!"
},
{
"code": null,
"e": 8441,
"s": 8183,
"text": "Imagine a scenario where you are at a conference (before 2020 those took place at a remote location other than your home — bizarre, I know!) and you want to train your DNN on your GPU machine. But wait, you turned it off before leaving your house — oh dear!"
},
{
"code": null,
"e": 8486,
"s": 8441,
"text": "This is where WAL and magic packets come in!"
},
{
"code": null,
"e": 8535,
"s": 8486,
"text": "On Ubuntu, edit /etc/systemd/system/[email protected]"
},
{
"code": null,
"e": 8706,
"s": 8535,
"text": "[Unit]Description=Wake-on-LAN for %iRequires=network.targetAfter=network.target[Service]ExecStart=/sbin/ethtool -s %i wol gType=oneshot[Install]WantedBy=multi-user.target"
},
{
"code": null,
"e": 8741,
"s": 8706,
"text": "After that, enable WOL service via"
},
{
"code": null,
"e": 8808,
"s": 8741,
"text": "sudo systemctl enable wol@enp7s3 && systemctl is-enabled wol@np7s3"
},
{
"code": null,
"e": 8962,
"s": 8808,
"text": "This should return ‘enabled’; enp7s3 is the network card name returned with ip add command. Finally, check your BIOS setting for \"wake-on-lan\" = enabled."
},
{
"code": null,
"e": 9005,
"s": 8962,
"text": "Now, on your laptop, install wakeonlan via"
},
{
"code": null,
"e": 9028,
"s": 9005,
"text": "brew install wakeonlan"
},
{
"code": null,
"e": 9173,
"s": 9028,
"text": "To test WOL is working, shutdown Ubuntu and issue the following command from your laptop using your DNS hostname (or IP address) and MAC address"
},
{
"code": null,
"e": 9225,
"s": 9173,
"text": "wakeonlan -i mlgpu.ddns.net -p 22 b3:21:88:6k:17:24"
},
{
"code": null,
"e": 9463,
"s": 9225,
"text": "This should wake-up your GPU-machine from sleep or powered-off state (make sure it’s still connected to power, of course!). If you went for the dual-boot option, and Ubuntu is not the first OS in the boot menu, adjust this with the GRUB."
},
{
"code": null,
"e": 9648,
"s": 9463,
"text": "That’s it: unplug your monitor, keyboard, and mouse from your GPU machine, from here we will issue all the commands from a remote ssh session running on Ubuntu from your laptop — neat!"
},
{
"code": null,
"e": 9800,
"s": 9648,
"text": "More good news ahead. Ubuntu 20.04 should automatically install Nvidia drivers for you (instead of the nouveau ones). Let’s verify this with nvidia-smi"
},
{
"code": null,
"e": 9948,
"s": 9800,
"text": "This is not the latest version of the drivers. However, we might want to keep them to install CUDA and cuDNN from the standard Ubuntu repositories."
},
{
"code": null,
"e": 9968,
"s": 9948,
"text": "Simply install CUDA"
},
{
"code": null,
"e": 10023,
"s": 9968,
"text": "sudo apt update &&sudo apt install nvidia-cuda-toolkit"
},
{
"code": null,
"e": 10050,
"s": 10023,
"text": "Verify with nvcc --version"
},
{
"code": null,
"e": 10128,
"s": 10050,
"text": "Finally, build your first CUDA ‘Hello World’ example using the file from here"
},
{
"code": null,
"e": 10161,
"s": 10128,
"text": "nvcc -o hello hello.cu &&./hello"
},
{
"code": null,
"e": 10234,
"s": 10161,
"text": "‘Max error: 0.000000’ means your CUDA libraries are working as expected!"
},
{
"code": null,
"e": 10458,
"s": 10234,
"text": "Finally, download the cuDNN v7.6.5 (November 5th, 2019) for CUDA 10.1 (or for the version of your CUDA release from nvcc --version). You need to register a free account with the NVIDIA Developer programme to download cuDNN."
},
{
"code": null,
"e": 10510,
"s": 10458,
"text": "From the unpacked tarball copy the libraries using:"
},
{
"code": null,
"e": 10692,
"s": 10510,
"text": "sudo cp cuda/include/cudnn.h /usr/lib/cuda/include/ &&sudo cp cuda/lib64/libcudnn* /usr/lib/cuda/lib64/ &&sudo chmod a+r /usr/lib/cuda/include/cudnn.h /usr/lib/cuda/lib64/libcudnn*"
},
{
"code": null,
"e": 10737,
"s": 10692,
"text": "and export the libraries to $LD_LIBRARY_PATH"
},
{
"code": null,
"e": 10920,
"s": 10737,
"text": "echo 'export LD_LIBRARY_PATH=/usr/lib/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrc &&echo 'export LD_LIBRARY_PATH=/usr/lib/cuda/include:$LD_LIBRARY_PATH' >> ~/.bashrc &&source ~/.bashrc"
},
{
"code": null,
"e": 10932,
"s": 10920,
"text": "Job’s done!"
},
{
"code": null,
"e": 11109,
"s": 10932,
"text": "On Linux and macOS, my personal preference is to use pip instead of conda to manage Python packages and environments. Below are instructions to set your ML Python3 environment:"
},
{
"code": null,
"e": 11146,
"s": 11109,
"text": "First of all, get the latest Python3"
},
{
"code": null,
"e": 11205,
"s": 11146,
"text": "sudo apt update &&sudo apt install python3-pip python3-dev"
},
{
"code": null,
"e": 11259,
"s": 11205,
"text": "Then, upgrade pip and install the environment manager"
},
{
"code": null,
"e": 11325,
"s": 11259,
"text": "sudo -H pip3 install --upgrade pipsudo -H pip3 install virtualenv"
},
{
"code": null,
"e": 11389,
"s": 11325,
"text": "Next, we will create a new directory for our GPU-based projects"
},
{
"code": null,
"e": 11418,
"s": 11389,
"text": "mkdir ~/gpu_ml &&cd ~/gpu_ml"
},
{
"code": null,
"e": 11465,
"s": 11418,
"text": "and instantiate a new Python environment there"
},
{
"code": null,
"e": 11487,
"s": 11465,
"text": "virtualenv gpu_ml_env"
},
{
"code": null,
"e": 11654,
"s": 11487,
"text": "This will allow us to install packages directly in that environment, as opposed to the ‘global’ installation. This environment needs to be activated (each login) with"
},
{
"code": null,
"e": 11683,
"s": 11654,
"text": "source ~/gpu_ml/bin/activate"
},
{
"code": null,
"e": 11818,
"s": 11683,
"text": "You should see (gpu_ml_env) in your terminal. Now, let's install Python packages in that environment (pip == pip3 in that environment)"
},
{
"code": null,
"e": 11895,
"s": 11818,
"text": "pip install jupyterlab &&pip install tensorflow &&pip install tensorflow-gpu"
},
{
"code": null,
"e": 11958,
"s": 11895,
"text": "Any other Python packages you need can be installed similarly."
},
{
"code": null,
"e": 12257,
"s": 11958,
"text": "There are some commands I recommend adding to your ~/.bash_aliases in Ubuntu. They will activate the gpu_ml environment on each login, as well as adding some helpful \"terminal shortcuts\" (life is too short to type 'jupyter lab' instead of 'jlab', right!?). The commands are below (alternative link)"
},
{
"code": null,
"e": 12462,
"s": 12257,
"text": "On your laptop, you might want to add those lines to your ~/.profile, replacing ML with your DNS hostname (or IP address) and using your MAC address from step #2. The commands are below (alternative link)"
},
{
"code": null,
"e": 12726,
"s": 12462,
"text": "Install FUSE for macOS from here, adjust the following script whereremotedir=\"user@$ML:/home/user/\", and mountdir=\"/Users/user/Documents/Ubuntu_mount\" is the directory on your macOS where the files on Ubuntu will be mounted. The script is below (alternative link)"
},
{
"code": null,
"e": 12746,
"s": 12726,
"text": "Run the script with"
},
{
"code": null,
"e": 12759,
"s": 12746,
"text": ". ./mount.sh"
},
{
"code": null,
"e": 12996,
"s": 12759,
"text": "and navigate to /Users/user/Documents/Ubuntu_mount(or simply type cd_ML)on your macOS to see Ubuntu files as \"local files\". You can now open and edit remote Ubuntu files with your favourite editor from your laptop, and much more — neat!"
},
{
"code": null,
"e": 13072,
"s": 12996,
"text": "Let’s do the final test of this set-up (fingers crossed!). From your laptop"
},
{
"code": null,
"e": 13075,
"s": 13072,
"text": "sg"
},
{
"code": null,
"e": 13254,
"s": 13075,
"text": "which stands forssh -L 8899:localhost:8899 mlgpu.ddns.net from our 'bash shortcuts'. This should open an ssh-tunnel on port 8899, and log in to the Ubuntu, from that session type"
},
{
"code": null,
"e": 13259,
"s": 13254,
"text": "jlab"
},
{
"code": null,
"e": 13316,
"s": 13259,
"text": "which is the bash shortcut for jupyter lab --port=8899 ."
},
{
"code": null,
"e": 13580,
"s": 13316,
"text": "Now, open your favourite web browser on your laptop and navigate tohttp://localhost:8899/lab . The first time, you will need to paste a token from your terminal into the browser (e.g. The Jupyter Notebook is running at:http://localhost:8899/?token=583049XXYZ... )"
},
{
"code": null,
"e": 13660,
"s": 13580,
"text": "In JupyterLab, sanity-check that we are indeed running this notebook from Linux"
},
{
"code": null,
"e": 13693,
"s": 13660,
"text": "import platformplatform.system()"
},
{
"code": null,
"e": 13729,
"s": 13693,
"text": "and that Tensorflow detects the GPU"
},
{
"code": null,
"e": 13791,
"s": 13729,
"text": "import tensorflow as tftf.config.list_physical_devices(‘GPU’)"
},
{
"code": null,
"e": 13948,
"s": 13791,
"text": "From here you are ready to implement your DNN training etc. using a GPU. If you followed all the steps in sections #1 to #5, your workflow is rather simple:"
},
{
"code": null,
"e": 14173,
"s": 13948,
"text": "1. ssh and open an ssh-tunnel to your GPU server with sg 2. Start JupyterLab on the GPU server with jlab 3. Open a web browser on your laptop and go to http://localhost:8899/lab 4. Happy training — the real work begins here!"
}
] |
Digit - Product - Sequence - GeeksforGeeks | 25 Aug, 2021
Given a number N, the task is to print the sequence up to N. The sequence is : 1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122, 126, 138, 162 and so on... This sequence is known as Digit – Product – Sequence. In this series, we take every non-zero digits of the number, multiply them and add the product to the number itself.
Examples:
Input : N = 10
Output :1 2 4 8 16 22 26 38 62 74
Input : N = 7
Output :1 2 4 8 16 22 26
Explanation:
1 + (1 * 1) = 1 + 1 = 2
2 + (2 * 1) = 2 + 2 = 4
4 + (4 * 1) = 4 + 4 = 8
8 + (8 * 1) = 8 + 8 = 16
16 + (1 * 6) = 16 + 6 = 22
22 + (2 * 2) = 22 + 4 = 26
26 + (2 * 6) = 26 + 12 = 38
38 + (3 * 8) = 38 + 24 = 62
62 + (6 * 2) = 62 + 12 = 74
and so on...
C++
Java
Python3
C#
PHP
Javascript
// CPP program for Digit Product Sequence#include <bits/stdc++.h>using namespace std; // function to produce and print Digit// Product Sequencevoid digit_product_Sum(int N){ // Array which store sequence int a[N]; // Temporary variable to store product int product = 1; // Initialize first element of the // array with 1 a[0] = 1; // Run a loop from 1 to N. Check if // previous number is single digit or // not. If yes then product = 1 else // take modulus. Then again check if // previous number is single digit or // not if yes then store previous number, // else store its first value Then for // every i store value in the array. for (int i = 1; i <= N; i++) { product = a[i - 1] / 10; if (product == 0) product = 1; else product = a[i - 1] % 10; int val = a[i - 1] / 10; if (val == 0) val = a[i - 1]; a[i] = a[i - 1] + (val * product); } // Print sequence for (int i = 0; i < N; i++) cout << a[i] << " ";} // Driver Codeint main(){ // Value of N int N = 10; // Calling function digit_product_Sum(N); return 0;}
// Java program for Digit Product Sequence // function to produce and print Digit// Product Sequenceimport java.lang.*;import java.io.*; class GFG{ public static void digit_product_Sum(int N) { // Array which store sequence int a[] = new int[N+1] ; // Temporary variable to store product int product = 1; // Initialize first element of the // array with 1 a[0] = 1; // Run a loop from 1 to N. Check if // previous number is single digit or // not. If yes then product = 1 else // take modulus. Then again check if // previous number is single digit or // not if yes then store previous number, // else store its first value Then for // every i store value in the array. for (int i = 1; i <= N; i++) { product = a[i - 1] / 10; if (product == 0) product = 1; else product = a[i - 1] % 10; int val = a[i - 1] / 10; if (val == 0) val = a[i - 1]; a[i] = a[i - 1] + (val * product); } // Print sequence for (int i = 0; i < N; i++) System.out.print(a[i] + " "); } // Driver Code public static void main(String[] args) { // Value of N int N = 10; // Calling function digit_product_Sum(N); }}// Code contributed by Mohit Gupta_OMG <(0_o)>
# Python3 program for# Digit Product Sequence # function to produce and# print Digit Product Sequence def digit_product_Sum(N): # Array which store sequence a = [0] * (N + 1); # Temporary variable # to store product product = 1; # Initialize first element # of the array with 1 a[0] = 1; # Run a loop from 1 to N. # Check if previous number # is single digit or not. # If yes then product = 1 # else take modulus. Then # again check if previous # number is single digit or # not if yes then store # previous number, else store # its first value Then for # every i store value in # the array. for i in range(1, N + 1): product = int(a[i - 1] / 10); if (product == 0): product = 1; else: product = a[i - 1] % 10; val = int(a[i - 1] / 10); if (val == 0): val = a[i - 1]; a[i] = a[i - 1] + (val * product); # Print sequence for i in range(N): print(a[i], end = " "); # Driver Code # Value of NN = 10; # Calling functiondigit_product_Sum(N); # This Code is contributed# by mits.
// C# program for Digit Product Sequence// function to produce and print Digit// Product Sequenceusing System; class GFG{ public static void digit_product_Sum(int N) { // Array which store sequence int []a = new int[N + 1] ; // Temporary variable to store product int product = 1; // Initialize first element of the // array with 1 a[0] = 1; // Run a loop from 1 to N. Check if // previous number is single digit or // not. If yes then product = 1 else // take modulus. Then again check if // previous number is single digit or // not if yes then store previous number, // else store its first value Then for // every i store value in the array. for (int i = 1; i <= N; i++) { product = a[i - 1] / 10; if (product == 0) product = 1; else product = a[i - 1] % 10; int val = a[i - 1] / 10; if (val == 0) val = a[i - 1]; a[i] = a[i - 1] + (val * product); } // Print sequence for (int i = 0; i < N; i++) Console.Write(a[i] + " "); } // Driver Code public static void Main() { // Value of N int N = 10; // Calling function digit_product_Sum(N); }}// This Code is contributed by vt_m.
<?php// PHP program for Digit// Product Sequence // function to produce// and print Digit// Product Sequencefunction digit_product_Sum($N){ // Array which // store sequence $a = array_fill(0, $N, 0); // Temporary variable // to store product $product = 1; // Initialize first // element of the // array with 1 $a[0] = 1; // Run a loop from 1 to // N. Check if previous // number is single digit // or not. If yes then // product = 1 else take // modulus. Then again check // if previous number is single // digit or not if yes then // store previous number, // else store its first value // Then for every i store value // in the array. for ($i = 1; $i <= $N; $i++) { $product = (int)($a[$i - 1] / 10); if ($product == 0) $product = 1; else $product = $a[$i - 1] % 10; $val = (int)($a[$i - 1] / 10); if ($val == 0) $val = $a[$i - 1]; $a[$i] = $a[$i - 1] + ($val * $product); } // Print sequence for ($i = 0; $i < $N; $i++) echo $a[$i]." ";} // Driver Code // Value of N$N = 10; // Calling functiondigit_product_Sum($N); // This Code is contributed// by mits. ?>
<script> // JavaScript program for Digit // Product Sequence // function to produce and print Digit // Product Sequence function digit_product_Sum(N) { // Array which store sequence var a = [...Array(N)]; // Temporary variable to store product var product = 1; // Initialize first element of the // array with 1 a[0] = 1; // Run a loop from 1 to N. Check if // previous number is single digit or // not. If yes then product = 1 else // take modulus. Then again check if // previous number is single digit or // not if yes then store previous number, // else store its first value Then for // every i store value in the array. for (var i = 1; i <= N; i++) { product = parseInt(a[i - 1] / 10); if (product == 0) product = 1; else product = a[i - 1] % 10; var val = parseInt(a[i - 1] / 10); if (val == 0) val = a[i - 1]; a[i] = a[i - 1] + val * product; } // Print sequence for (var i = 0; i < N; i++) document.write(a[i] + " "); } // Driver Code // Value of N var N = 10; // Calling function digit_product_Sum(N); </script>
Output:
1 2 4 8 16 22 26 38 62 74
This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
rdtank
rs1686740
number-digits
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
Interfaces in Java | [
{
"code": null,
"e": 24646,
"s": 24618,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 24984,
"s": 24646,
"text": "Given a number N, the task is to print the sequence up to N. The sequence is : 1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122, 126, 138, 162 and so on... This sequence is known as Digit – Product – Sequence. In this series, we take every non-zero digits of the number, multiply them and add the product to the number itself."
},
{
"code": null,
"e": 24995,
"s": 24984,
"text": "Examples: "
},
{
"code": null,
"e": 25084,
"s": 24995,
"text": "Input : N = 10\nOutput :1 2 4 8 16 22 26 38 62 74\n\nInput : N = 7\nOutput :1 2 4 8 16 22 26"
},
{
"code": null,
"e": 25098,
"s": 25084,
"text": "Explanation: "
},
{
"code": null,
"e": 25354,
"s": 25098,
"text": "1 + (1 * 1) = 1 + 1 = 2\n2 + (2 * 1) = 2 + 2 = 4\n4 + (4 * 1) = 4 + 4 = 8\n8 + (8 * 1) = 8 + 8 = 16\n16 + (1 * 6) = 16 + 6 = 22\n22 + (2 * 2) = 22 + 4 = 26\n26 + (2 * 6) = 26 + 12 = 38\n38 + (3 * 8) = 38 + 24 = 62\n62 + (6 * 2) = 62 + 12 = 74\nand so on..."
},
{
"code": null,
"e": 25358,
"s": 25354,
"text": "C++"
},
{
"code": null,
"e": 25363,
"s": 25358,
"text": "Java"
},
{
"code": null,
"e": 25371,
"s": 25363,
"text": "Python3"
},
{
"code": null,
"e": 25374,
"s": 25371,
"text": "C#"
},
{
"code": null,
"e": 25378,
"s": 25374,
"text": "PHP"
},
{
"code": null,
"e": 25389,
"s": 25378,
"text": "Javascript"
},
{
"code": "// CPP program for Digit Product Sequence#include <bits/stdc++.h>using namespace std; // function to produce and print Digit// Product Sequencevoid digit_product_Sum(int N){ // Array which store sequence int a[N]; // Temporary variable to store product int product = 1; // Initialize first element of the // array with 1 a[0] = 1; // Run a loop from 1 to N. Check if // previous number is single digit or // not. If yes then product = 1 else // take modulus. Then again check if // previous number is single digit or // not if yes then store previous number, // else store its first value Then for // every i store value in the array. for (int i = 1; i <= N; i++) { product = a[i - 1] / 10; if (product == 0) product = 1; else product = a[i - 1] % 10; int val = a[i - 1] / 10; if (val == 0) val = a[i - 1]; a[i] = a[i - 1] + (val * product); } // Print sequence for (int i = 0; i < N; i++) cout << a[i] << \" \";} // Driver Codeint main(){ // Value of N int N = 10; // Calling function digit_product_Sum(N); return 0;}",
"e": 26585,
"s": 25389,
"text": null
},
{
"code": "// Java program for Digit Product Sequence // function to produce and print Digit// Product Sequenceimport java.lang.*;import java.io.*; class GFG{ public static void digit_product_Sum(int N) { // Array which store sequence int a[] = new int[N+1] ; // Temporary variable to store product int product = 1; // Initialize first element of the // array with 1 a[0] = 1; // Run a loop from 1 to N. Check if // previous number is single digit or // not. If yes then product = 1 else // take modulus. Then again check if // previous number is single digit or // not if yes then store previous number, // else store its first value Then for // every i store value in the array. for (int i = 1; i <= N; i++) { product = a[i - 1] / 10; if (product == 0) product = 1; else product = a[i - 1] % 10; int val = a[i - 1] / 10; if (val == 0) val = a[i - 1]; a[i] = a[i - 1] + (val * product); } // Print sequence for (int i = 0; i < N; i++) System.out.print(a[i] + \" \"); } // Driver Code public static void main(String[] args) { // Value of N int N = 10; // Calling function digit_product_Sum(N); }}// Code contributed by Mohit Gupta_OMG <(0_o)>",
"e": 28033,
"s": 26585,
"text": null
},
{
"code": "# Python3 program for# Digit Product Sequence # function to produce and# print Digit Product Sequence def digit_product_Sum(N): # Array which store sequence a = [0] * (N + 1); # Temporary variable # to store product product = 1; # Initialize first element # of the array with 1 a[0] = 1; # Run a loop from 1 to N. # Check if previous number # is single digit or not. # If yes then product = 1 # else take modulus. Then # again check if previous # number is single digit or # not if yes then store # previous number, else store # its first value Then for # every i store value in # the array. for i in range(1, N + 1): product = int(a[i - 1] / 10); if (product == 0): product = 1; else: product = a[i - 1] % 10; val = int(a[i - 1] / 10); if (val == 0): val = a[i - 1]; a[i] = a[i - 1] + (val * product); # Print sequence for i in range(N): print(a[i], end = \" \"); # Driver Code # Value of NN = 10; # Calling functiondigit_product_Sum(N); # This Code is contributed# by mits.",
"e": 29200,
"s": 28033,
"text": null
},
{
"code": "// C# program for Digit Product Sequence// function to produce and print Digit// Product Sequenceusing System; class GFG{ public static void digit_product_Sum(int N) { // Array which store sequence int []a = new int[N + 1] ; // Temporary variable to store product int product = 1; // Initialize first element of the // array with 1 a[0] = 1; // Run a loop from 1 to N. Check if // previous number is single digit or // not. If yes then product = 1 else // take modulus. Then again check if // previous number is single digit or // not if yes then store previous number, // else store its first value Then for // every i store value in the array. for (int i = 1; i <= N; i++) { product = a[i - 1] / 10; if (product == 0) product = 1; else product = a[i - 1] % 10; int val = a[i - 1] / 10; if (val == 0) val = a[i - 1]; a[i] = a[i - 1] + (val * product); } // Print sequence for (int i = 0; i < N; i++) Console.Write(a[i] + \" \"); } // Driver Code public static void Main() { // Value of N int N = 10; // Calling function digit_product_Sum(N); }}// This Code is contributed by vt_m.",
"e": 30598,
"s": 29200,
"text": null
},
{
"code": "<?php// PHP program for Digit// Product Sequence // function to produce// and print Digit// Product Sequencefunction digit_product_Sum($N){ // Array which // store sequence $a = array_fill(0, $N, 0); // Temporary variable // to store product $product = 1; // Initialize first // element of the // array with 1 $a[0] = 1; // Run a loop from 1 to // N. Check if previous // number is single digit // or not. If yes then // product = 1 else take // modulus. Then again check // if previous number is single // digit or not if yes then // store previous number, // else store its first value // Then for every i store value // in the array. for ($i = 1; $i <= $N; $i++) { $product = (int)($a[$i - 1] / 10); if ($product == 0) $product = 1; else $product = $a[$i - 1] % 10; $val = (int)($a[$i - 1] / 10); if ($val == 0) $val = $a[$i - 1]; $a[$i] = $a[$i - 1] + ($val * $product); } // Print sequence for ($i = 0; $i < $N; $i++) echo $a[$i].\" \";} // Driver Code // Value of N$N = 10; // Calling functiondigit_product_Sum($N); // This Code is contributed// by mits. ?>",
"e": 31862,
"s": 30598,
"text": null
},
{
"code": "<script> // JavaScript program for Digit // Product Sequence // function to produce and print Digit // Product Sequence function digit_product_Sum(N) { // Array which store sequence var a = [...Array(N)]; // Temporary variable to store product var product = 1; // Initialize first element of the // array with 1 a[0] = 1; // Run a loop from 1 to N. Check if // previous number is single digit or // not. If yes then product = 1 else // take modulus. Then again check if // previous number is single digit or // not if yes then store previous number, // else store its first value Then for // every i store value in the array. for (var i = 1; i <= N; i++) { product = parseInt(a[i - 1] / 10); if (product == 0) product = 1; else product = a[i - 1] % 10; var val = parseInt(a[i - 1] / 10); if (val == 0) val = a[i - 1]; a[i] = a[i - 1] + val * product; } // Print sequence for (var i = 0; i < N; i++) document.write(a[i] + \" \"); } // Driver Code // Value of N var N = 10; // Calling function digit_product_Sum(N); </script>",
"e": 33163,
"s": 31862,
"text": null
},
{
"code": null,
"e": 33173,
"s": 33163,
"text": "Output: "
},
{
"code": null,
"e": 33199,
"s": 33173,
"text": "1 2 4 8 16 22 26 38 62 74"
},
{
"code": null,
"e": 33620,
"s": 33199,
"text": "This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33633,
"s": 33620,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 33640,
"s": 33633,
"text": "rdtank"
},
{
"code": null,
"e": 33650,
"s": 33640,
"text": "rs1686740"
},
{
"code": null,
"e": 33664,
"s": 33650,
"text": "number-digits"
},
{
"code": null,
"e": 33671,
"s": 33664,
"text": "series"
},
{
"code": null,
"e": 33684,
"s": 33671,
"text": "Mathematical"
},
{
"code": null,
"e": 33703,
"s": 33684,
"text": "School Programming"
},
{
"code": null,
"e": 33716,
"s": 33703,
"text": "Mathematical"
},
{
"code": null,
"e": 33723,
"s": 33716,
"text": "series"
},
{
"code": null,
"e": 33821,
"s": 33723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33845,
"s": 33821,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33888,
"s": 33845,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33902,
"s": 33888,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33951,
"s": 33902,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33985,
"s": 33951,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 34003,
"s": 33985,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34019,
"s": 34003,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34044,
"s": 34019,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34063,
"s": 34044,
"text": "Inheritance in C++"
}
] |
Remove Consecutive Duplicates in Python | Suppose we have a string s, this string consisting of "R" and "L", we have to remove the
minimum number of characters such that there's no consecutive "R" and no consecutive "L".
So, if the input is like "LLLRLRR", then the output will be "LRLR"
To solve this, we will follow these steps −
seen := first character of s
ans := first character of s
for each character i from index 1 to end of s, doif i is not same as seen, thenans := ans + iseen := i
if i is not same as seen, thenans := ans + iseen := i
ans := ans + i
seen := i
return ans
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, s):
seen = s[0]
ans = s[0]
for i in s[1:]:
if i != seen:
ans += i
seen = i
return ans
ob = Solution()
print(ob.solve("LLLRLRR"))
"LLLRLRR"
LRLR | [
{
"code": null,
"e": 1241,
"s": 1062,
"text": "Suppose we have a string s, this string consisting of \"R\" and \"L\", we have to remove the\nminimum number of characters such that there's no consecutive \"R\" and no consecutive \"L\"."
},
{
"code": null,
"e": 1308,
"s": 1241,
"text": "So, if the input is like \"LLLRLRR\", then the output will be \"LRLR\""
},
{
"code": null,
"e": 1352,
"s": 1308,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1381,
"s": 1352,
"text": "seen := first character of s"
},
{
"code": null,
"e": 1409,
"s": 1381,
"text": "ans := first character of s"
},
{
"code": null,
"e": 1512,
"s": 1409,
"text": "for each character i from index 1 to end of s, doif i is not same as seen, thenans := ans + iseen := i"
},
{
"code": null,
"e": 1566,
"s": 1512,
"text": "if i is not same as seen, thenans := ans + iseen := i"
},
{
"code": null,
"e": 1581,
"s": 1566,
"text": "ans := ans + i"
},
{
"code": null,
"e": 1591,
"s": 1581,
"text": "seen := i"
},
{
"code": null,
"e": 1602,
"s": 1591,
"text": "return ans"
},
{
"code": null,
"e": 1672,
"s": 1602,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1683,
"s": 1672,
"text": " Live Demo"
},
{
"code": null,
"e": 1904,
"s": 1683,
"text": "class Solution:\n def solve(self, s):\n seen = s[0]\n ans = s[0]\n for i in s[1:]:\n if i != seen:\n ans += i\n seen = i\n return ans\nob = Solution()\nprint(ob.solve(\"LLLRLRR\"))"
},
{
"code": null,
"e": 1914,
"s": 1904,
"text": "\"LLLRLRR\""
},
{
"code": null,
"e": 1919,
"s": 1914,
"text": "LRLR"
}
] |
Java 12 - String methods | Java 12 introduces following new methods to String for easy formatting.
Adjust the indention of each line of string based on argument passed.
string.indent(n)
n > 0 - insert space at the begining of each line.
n > 0 - insert space at the begining of each line.
n < 0 - remove space at the begining of each line.
n < 0 - remove space at the begining of each line.
n < 0 and n < available spaces - remove all leading space of each line.
n < 0 and n < available spaces - remove all leading space of each line.
n = 0 - no change.
n = 0 - no change.
Transforms a string to give result as R.
String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
Returns Optional Object containing description of String instance.
Optional<String> optional = message.describeConstable();
Returns descriptor instance string of given string.
String constantDesc = message.resolveConstantDesc(MethodHandles.lookup());
Consider the following example −
ApiTester.java
import java.lang.invoke.MethodHandles;
import java.util.Optional;
public class APITester {
public static void main(String[] args) {
String str = "Welcome \nto Tutorialspoint!";
System.out.println(str.indent(0));
System.out.println(str.indent(3));
String text = "Java";
String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());
System.out.println(transformed);
Optional<String> optional = text.describeConstable();
System.out.println(optional);
String cDescription = text.resolveConstantDesc(MethodHandles.lookup());
System.out.println(cDescription);
}
}
Welcome
to Tutorialspoint!
Welcome
to Tutorialspoint!
avaJ
Optional[Java]
Java
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1986,
"s": 1914,
"text": "Java 12 introduces following new methods to String for easy formatting."
},
{
"code": null,
"e": 2056,
"s": 1986,
"text": "Adjust the indention of each line of string based on argument passed."
},
{
"code": null,
"e": 2074,
"s": 2056,
"text": "string.indent(n)\n"
},
{
"code": null,
"e": 2125,
"s": 2074,
"text": "n > 0 - insert space at the begining of each line."
},
{
"code": null,
"e": 2176,
"s": 2125,
"text": "n > 0 - insert space at the begining of each line."
},
{
"code": null,
"e": 2227,
"s": 2176,
"text": "n < 0 - remove space at the begining of each line."
},
{
"code": null,
"e": 2278,
"s": 2227,
"text": "n < 0 - remove space at the begining of each line."
},
{
"code": null,
"e": 2350,
"s": 2278,
"text": "n < 0 and n < available spaces - remove all leading space of each line."
},
{
"code": null,
"e": 2422,
"s": 2350,
"text": "n < 0 and n < available spaces - remove all leading space of each line."
},
{
"code": null,
"e": 2441,
"s": 2422,
"text": "n = 0 - no change."
},
{
"code": null,
"e": 2460,
"s": 2441,
"text": "n = 0 - no change."
},
{
"code": null,
"e": 2501,
"s": 2460,
"text": "Transforms a string to give result as R."
},
{
"code": null,
"e": 2595,
"s": 2501,
"text": "String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());\n"
},
{
"code": null,
"e": 2662,
"s": 2595,
"text": "Returns Optional Object containing description of String instance."
},
{
"code": null,
"e": 2720,
"s": 2662,
"text": "Optional<String> optional = message.describeConstable();\n"
},
{
"code": null,
"e": 2772,
"s": 2720,
"text": "Returns descriptor instance string of given string."
},
{
"code": null,
"e": 2848,
"s": 2772,
"text": "String constantDesc = message.resolveConstantDesc(MethodHandles.lookup());\n"
},
{
"code": null,
"e": 2881,
"s": 2848,
"text": "Consider the following example −"
},
{
"code": null,
"e": 2896,
"s": 2881,
"text": "ApiTester.java"
},
{
"code": null,
"e": 3555,
"s": 2896,
"text": "import java.lang.invoke.MethodHandles;\nimport java.util.Optional;\n\npublic class APITester {\n public static void main(String[] args) {\n String str = \"Welcome \\nto Tutorialspoint!\";\n System.out.println(str.indent(0));\n System.out.println(str.indent(3));\n\n String text = \"Java\";\n String transformed = text.transform(value -> new StringBuilder(value).reverse().toString());\n System.out.println(transformed);\n\n Optional<String> optional = text.describeConstable();\n System.out.println(optional);\n\n String cDescription = text.resolveConstantDesc(MethodHandles.lookup());\n System.out.println(cDescription);\n }\n}"
},
{
"code": null,
"e": 3645,
"s": 3555,
"text": "Welcome \nto Tutorialspoint!\n\n Welcome \n to Tutorialspoint!\n\navaJ\nOptional[Java]\nJava\n"
},
{
"code": null,
"e": 3678,
"s": 3645,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3694,
"s": 3678,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3727,
"s": 3694,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3743,
"s": 3727,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3778,
"s": 3743,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3792,
"s": 3778,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3826,
"s": 3792,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3840,
"s": 3826,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3877,
"s": 3840,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3892,
"s": 3877,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3925,
"s": 3892,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3944,
"s": 3925,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3951,
"s": 3944,
"text": " Print"
},
{
"code": null,
"e": 3962,
"s": 3951,
"text": " Add Notes"
}
] |
MySQL SELECT query to return records with specific month and year | For specific month, use MONTH() and for year, use YEAR() method. Let us first create a table −
mysql> create table DemoTable
(
StudentName varchar(40),
StudentAdmissionDate date
);
Query OK, 0 rows affected (0.67 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris','2019-01-21');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Robert','2018-09-05');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Mike','2019-09-05');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('David','2019-10-04');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+----------------------+
| StudentName | StudentAdmissionDate |
+-------------+----------------------+
| Chris | 2019-01-21 |
| Robert | 2018-09-05 |
| Mike | 2019-09-05 |
| David | 2019-10-04 |
+-------------+----------------------+
4 rows in set (0.00 sec)
Following is the query to return records with specific month and year −
mysql> select *from DemoTable where month(StudentAdmissionDate)=09 and year(StudentAdmissionDate)=2019;
This will produce the following output −
+-------------+----------------------+
| StudentName | StudentAdmissionDate |
+-------------+----------------------+
| Mike | 2019-09-05 |
+-------------+----------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "For specific month, use MONTH() and for year, use YEAR() method. Let us first create a table −"
},
{
"code": null,
"e": 1286,
"s": 1157,
"text": "mysql> create table DemoTable\n(\n StudentName varchar(40),\n StudentAdmissionDate date\n);\nQuery OK, 0 rows affected (0.67 sec)"
},
{
"code": null,
"e": 1342,
"s": 1286,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1722,
"s": 1342,
"text": "mysql> insert into DemoTable values('Chris','2019-01-21');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values('Robert','2018-09-05');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('Mike','2019-09-05');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable values('David','2019-10-04');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1782,
"s": 1722,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1813,
"s": 1782,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1854,
"s": 1813,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2191,
"s": 1854,
"text": "+-------------+----------------------+\n| StudentName | StudentAdmissionDate |\n+-------------+----------------------+\n| Chris | 2019-01-21 |\n| Robert | 2018-09-05 |\n| Mike | 2019-09-05 |\n| David | 2019-10-04 |\n+-------------+----------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2263,
"s": 2191,
"text": "Following is the query to return records with specific month and year −"
},
{
"code": null,
"e": 2367,
"s": 2263,
"text": "mysql> select *from DemoTable where month(StudentAdmissionDate)=09 and year(StudentAdmissionDate)=2019;"
},
{
"code": null,
"e": 2408,
"s": 2367,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2627,
"s": 2408,
"text": "+-------------+----------------------+\n| StudentName | StudentAdmissionDate |\n+-------------+----------------------+\n| Mike | 2019-09-05 |\n+-------------+----------------------+\n1 row in set (0.00 sec)"
}
] |
Pascal - Variable Scope | A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable cannot be accessed. There are three places, where variables can be declared in Pascal programming language −
Inside a subprogram or a block which is called local variables
Inside a subprogram or a block which is called local variables
Outside of all subprograms which is called global variables
Outside of all subprograms which is called global variables
In the definition of subprogram parameters which is called formal parameters
In the definition of subprogram parameters which is called formal parameters
Let us explain what are local and global variables and formal parameters.
Variables that are declared inside a subprogram or block are called local variables. They can be used only by statements that are inside that subprogram or block of code. Local variables are not known to subprograms outside their own. Following is the example using local variables. Here, all the variables a, b and c are local to program named exLocal.
program exLocal;
var
a, b, c: integer;
begin
(* actual initialization *)
a := 10;
b := 20;
c := a + b;
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
end.
When the above code is compiled and executed, it produces the following result −
value of a = 10 b = 20 c = 30
Now, let us extend the program little more, let us create a procedure named display, which will have its own set of variables a, b and c and display their values, right from the program exLocal.
program exLocal;
var
a, b, c: integer;
procedure display;
var
a, b, c: integer;
begin
(* local variables *)
a := 10;
b := 20;
c := a + b;
writeln('Winthin the procedure display');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
end;
begin
a:= 100;
b:= 200;
c:= a + b;
writeln('Winthin the program exlocal');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
display();
end.
When the above code is compiled and executed, it produces the following result −
Within the program exlocal
value of a = 100 b = 200 c = 300
Within the procedure display
value of a = 10 b = 20 c = 30
Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is an example using global and local variables −
program exGlobal;
var
a, b, c: integer;
procedure display;
var
x, y, z: integer;
begin
(* local variables *)
x := 10;
y := 20;
z := x + y;
(*global variables *)
a := 30;
b:= 40;
c:= a + b;
writeln('Winthin the procedure display');
writeln(' Displaying the global variables a, b, and c');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
writeln('Displaying the local variables x, y, and z');
writeln('value of x = ', x , ' y = ', y, ' and z = ', z);
end;
begin
a:= 100;
b:= 200;
c:= 300;
writeln('Winthin the program exlocal');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
display();
end.
When the above code is compiled and executed, it produces the following result −
Within the program exlocal
value of a = 100 b = 200 c = 300
Within the procedure display
Displaying the global variables a, b, and c
value of a = 30 b = 40 c = 70
Displaying the local variables x, y, and z
value of x = 10 y = 20 z = 30
Please note that the procedure display has access to the variables a, b and c, which are global variables with respect to display as well as its own local variables. A program can have same name for local and global variables but value of local variable inside a function will take preference.
Let us change the previous example a little, now the local variables for the procedure display has same names as a, b, c −
program exGlobal;
var
a, b, c: integer;
procedure display;
var
a, b, c: integer;
begin
(* local variables *)
a := 10;
b := 20;
c := a + b;
writeln('Winthin the procedure display');
writeln(' Displaying the global variables a, b, and c');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
writeln('Displaying the local variables a, b, and c');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
end;
begin
a:= 100;
b:= 200;
c:= 300;
writeln('Winthin the program exlocal');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
display();
end.
When the above code is compiled and executed, it produces the following result −
Within the program exlocal
value of a = 100 b = 200 c = 300
Within the procedure display
Displaying the global variables a, b, and c
value of a = 10 b = 20 c = 30
Displaying the local variables a, b, and c
value of a = 10 b = 20 c = 30
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2319,
"s": 2083,
"text": "A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable cannot be accessed. There are three places, where variables can be declared in Pascal programming language −"
},
{
"code": null,
"e": 2382,
"s": 2319,
"text": "Inside a subprogram or a block which is called local variables"
},
{
"code": null,
"e": 2445,
"s": 2382,
"text": "Inside a subprogram or a block which is called local variables"
},
{
"code": null,
"e": 2505,
"s": 2445,
"text": "Outside of all subprograms which is called global variables"
},
{
"code": null,
"e": 2565,
"s": 2505,
"text": "Outside of all subprograms which is called global variables"
},
{
"code": null,
"e": 2642,
"s": 2565,
"text": "In the definition of subprogram parameters which is called formal parameters"
},
{
"code": null,
"e": 2719,
"s": 2642,
"text": "In the definition of subprogram parameters which is called formal parameters"
},
{
"code": null,
"e": 2793,
"s": 2719,
"text": "Let us explain what are local and global variables and formal parameters."
},
{
"code": null,
"e": 3148,
"s": 2793,
"text": "Variables that are declared inside a subprogram or block are called local variables. They can be used only by statements that are inside that subprogram or block of code. Local variables are not known to subprograms outside their own. Following is the example using local variables. Here, all the variables a, b and c are local to program named exLocal."
},
{
"code": null,
"e": 3340,
"s": 3148,
"text": "program exLocal; \nvar\n a, b, c: integer;\n\nbegin\n (* actual initialization *)\n a := 10;\n b := 20;\n c := a + b;\n \n writeln('value of a = ', a , ' b = ', b, ' and c = ', c);\nend."
},
{
"code": null,
"e": 3421,
"s": 3340,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3452,
"s": 3421,
"text": "value of a = 10 b = 20 c = 30\n"
},
{
"code": null,
"e": 3647,
"s": 3452,
"text": "Now, let us extend the program little more, let us create a procedure named display, which will have its own set of variables a, b and c and display their values, right from the program exLocal."
},
{
"code": null,
"e": 4095,
"s": 3647,
"text": "program exLocal;\nvar\n a, b, c: integer;\nprocedure display;\n\nvar\n a, b, c: integer;\nbegin\n (* local variables *)\n a := 10;\n b := 20;\n c := a + b;\n \n writeln('Winthin the procedure display');\n writeln('value of a = ', a , ' b = ', b, ' and c = ', c);\nend;\n\nbegin\n a:= 100;\n b:= 200;\n c:= a + b;\n \n writeln('Winthin the program exlocal');\n writeln('value of a = ', a , ' b = ', b, ' and c = ', c);\n display();\nend."
},
{
"code": null,
"e": 4176,
"s": 4095,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4296,
"s": 4176,
"text": "Within the program exlocal\nvalue of a = 100 b = 200 c = 300\nWithin the procedure display\nvalue of a = 10 b = 20 c = 30\n"
},
{
"code": null,
"e": 4540,
"s": 4296,
"text": "Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program."
},
{
"code": null,
"e": 4752,
"s": 4540,
"text": "A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is an example using global and local variables −"
},
{
"code": null,
"e": 5458,
"s": 4752,
"text": "program exGlobal;\nvar\n a, b, c: integer;\nprocedure display;\nvar\n x, y, z: integer;\n\nbegin\n (* local variables *)\n x := 10;\n y := 20;\n z := x + y;\n \n (*global variables *)\n a := 30;\n b:= 40;\n c:= a + b;\n \n writeln('Winthin the procedure display');\n writeln(' Displaying the global variables a, b, and c');\n \n writeln('value of a = ', a , ' b = ', b, ' and c = ', c);\n writeln('Displaying the local variables x, y, and z');\n \n writeln('value of x = ', x , ' y = ', y, ' and z = ', z);\nend;\n\nbegin\n a:= 100;\n b:= 200;\n c:= 300;\n \n writeln('Winthin the program exlocal');\n writeln('value of a = ', a , ' b = ', b, ' and c = ', c);\n \n display();\nend."
},
{
"code": null,
"e": 5539,
"s": 5458,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5776,
"s": 5539,
"text": "Within the program exlocal\nvalue of a = 100 b = 200 c = 300\nWithin the procedure display\nDisplaying the global variables a, b, and c\nvalue of a = 30 b = 40 c = 70\nDisplaying the local variables x, y, and z\nvalue of x = 10 y = 20 z = 30\n"
},
{
"code": null,
"e": 6070,
"s": 5776,
"text": "Please note that the procedure display has access to the variables a, b and c, which are global variables with respect to display as well as its own local variables. A program can have same name for local and global variables but value of local variable inside a function will take preference."
},
{
"code": null,
"e": 6193,
"s": 6070,
"text": "Let us change the previous example a little, now the local variables for the procedure display has same names as a, b, c −"
},
{
"code": null,
"e": 6837,
"s": 6193,
"text": "program exGlobal;\nvar\n a, b, c: integer;\nprocedure display;\n\nvar\n a, b, c: integer;\n\nbegin\n (* local variables *)\n a := 10;\n b := 20;\n c := a + b;\n \n writeln('Winthin the procedure display');\n writeln(' Displaying the global variables a, b, and c');\n \n writeln('value of a = ', a , ' b = ', b, ' and c = ', c);\n writeln('Displaying the local variables a, b, and c');\n \n writeln('value of a = ', a , ' b = ', b, ' and c = ', c);\nend;\n\nbegin\n a:= 100;\n b:= 200;\n c:= 300;\n \n writeln('Winthin the program exlocal');\n writeln('value of a = ', a , ' b = ', b, ' and c = ', c); \n \n display();\nend."
},
{
"code": null,
"e": 6918,
"s": 6837,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7155,
"s": 6918,
"text": "Within the program exlocal\nvalue of a = 100 b = 200 c = 300\nWithin the procedure display\nDisplaying the global variables a, b, and c\nvalue of a = 10 b = 20 c = 30\nDisplaying the local variables a, b, and c\nvalue of a = 10 b = 20 c = 30\n"
},
{
"code": null,
"e": 7190,
"s": 7155,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7213,
"s": 7190,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 7220,
"s": 7213,
"text": " Print"
},
{
"code": null,
"e": 7231,
"s": 7220,
"text": " Add Notes"
}
] |
What is White Box Testing? Techniques, Example, Types & Tools | White Box Testing is a software examining technique that involves testing the product's underlying structure, design, and coding in order to verify input-output flow and improve design, usability, and security. White box testing is also known as Clear box testing, Open box testing, transparent box testing, Code-based testing, and Glass box testing since the code is visible to the testers.
It's one of two components of the software testing approach known as Box Testing. Blackbox testing, on the other hand, entails testing from an external or end-user perspective. White box testing, on the other hand, is focused on the inner workings of an application and revolves around internal testing.
Because of the see-through box concept, the term "WhiteBox" was coined. The name "clear box" or "WhiteBox" refers to the ability to see into the software's inner workings through its exterior shell (or "box"). Similarly, the "black box" in "Black Box Testing" denotes the inability to observe the software's inner workings, allowing only the end-user experience to be assessed.
White box testing entails putting the software code to the test for the following −
Internal flaws in security
Internal flaws in security
Paths in the coding process that are broken or poorly structured
Paths in the coding process that are broken or poorly structured
The path is taken by specified inputs through the program.
The path is taken by specified inputs through the program.
Expected results
Expected results
Conditional loops are useful in a variety of situations.
Conditional loops are useful in a variety of situations.
Individualized testing of each statement, object, and function
Individualized testing of each statement, object, and function
Software development might include testing at the system, integration, and unit levels. One of the primary aims of white-box testing is to ensure that an application's operating flow is correct. It entails comparing a set of predetermined inputs to
expected or desired outputs, with the goal of identifying bugs when one of the inputs fails to provide the expected outcome.
We've broken down white box testing into two simple phases to make it easier to understand. When utilizing the white box testing technique to test an application, testers do the following −
The source code of the program is generally the first thing a tester learns and understands. Because white box testing entails testing an application's inner workings, the tester must be well-versed in the programming languages used in the applications under test. Furthermore, the tester must be well-versed in secure coding techniques.
One of the main goals of software testing is to ensure that it is secure. The tester should be able to detect security flaws and prevent assaults from hackers and naive users who may purposefully or unknowingly inject dangerous code into the program.
The application's source code is tested for correct flow and structure in the second
fundamental step of white box testing. One method is to write more code to test the source code of the application. For each step or sequence of processes in the application, the tester will create little tests. This method necessitates the tester's
extensive understanding of the code and is frequently carried out by the developer. Manual testing, trial, and error testing, and the usage of testing tools are some of the other methods that will be discussed later in this article.
Code −
Printme (int a, int b) {------------ it is a function
int result = a+ b;
If (result > 0)
Print ("Positive", result)
Else
Print ("Negative", result)
} ----------- End of the code
WhiteBox testing in software engineering aims to make sure that all decision branches, loops, and statements in the code are correct.
WhiteBox test cases would be used to put the statements in the preceding white box testing example to the test.
A = 1; B = 1
A = -1, B = -3
Code Coverage Analysis is a popular White box testing technique. A Test Case suite's holes are filled through Code Coverage analysis. It identifies parts of a program that aren't put to the test in a collection of test cases. You write test cases to check untested areas of the code once the holes have been detected, thereby improving the quality of the software product.
Code coverage analysis can be performed using automated technologies. A box tester can employ the following coverage analysis techniques −
Statement Coverage − During the software engineering testing process, this technique mandates that every possible statement in the code be tested at least once.
Statement Coverage − During the software engineering testing process, this technique mandates that every possible statement in the code be tested at least once.
Branch Coverage − This technique examines every conceivable path of a software application (if-else and other conditional loops).
Branch Coverage − This technique examines every conceivable path of a software application (if-else and other conditional loops).
Aside from the aforementioned coverage kinds, there is a slew of others, including Condition Coverage, Multiple Condition Coverage, Path Coverage, and Function Coverage. Each method has its own set of advantages and aims to test (cover) all aspects of software code. You can typically achieve 80-90 percent code coverage using Statement and Branch coverage, which is sufficient.
Following are some of the important WhiteBox Testing Techniquess −
Statement Coverage
Decision Coverage
Branch Coverage
Condition Coverage
Multiple Condition Coverage
Finite State Machine Coverage
Path Coverage
Control flow testing
Data flow testing
To make certain −
That each module's independent pathways have been tested at least once.
That each module's independent pathways have been tested at least once.
All logical decisions were tested to see if they were true or untrue.
All logical decisions were tested to see if they were true or untrue.
Internal data structures validity is ensured by all loops that are executed at their boundaries and within their operational constraints.
Internal data structures validity is ensured by all loops that are executed at their boundaries and within their operational constraints.
To find the types of bugs listed below −
When we create and implement functions, conditions, or controls that are not part of the program, we are more likely to make logical errors.
When we create and implement functions, conditions, or controls that are not part of the program, we are more likely to make logical errors.
Design flaws resulting from a mismatch between the program's logical flow and its actual execution
Design flaws resulting from a mismatch between the program's logical flow and its actual execution
Checking for grammatical and syntactic mistakes
Checking for grammatical and syntactic mistakes
White box testing refers to a variety of testing methods that are used to assess the usability of an application, a piece of code, or a specific software package. The following is a list −
Unit testing − Unit testing is frequently the first type of application testing performed. As each unit or block of code is developed, it is subjected to unit testing. The programmer is primarily responsible for unit testing. As a software developer, you write a few lines of code, a single function, or an object, then test it to ensure it works before moving on to the next step. Early in the software development lifecycle, unit testing helps in the detection of the majority of issues. Bugs discovered at this stage are less expensive and easier to fix.
Unit testing − Unit testing is frequently the first type of application testing performed. As each unit or block of code is developed, it is subjected to unit testing. The programmer is primarily responsible for unit testing. As a software developer, you write a few lines of code, a single function, or an object, then test it to ensure it works before moving on to the next step. Early in the software development lifecycle, unit testing helps in the detection of the majority of issues. Bugs discovered at this stage are less expensive and easier to fix.
Testing for Memory Leaks − Memory leaks are one of the most common reasons for slow-running apps. When you have a slow-running software application, you need a QA professional who is skilled in detecting memory leaks. Apart from the aforementioned, both black box and white box testing include a few forms of testing. Below is a list of them.
Testing for Memory Leaks − Memory leaks are one of the most common reasons for slow-running apps. When you have a slow-running software application, you need a QA professional who is skilled in detecting memory leaks. Apart from the aforementioned, both black box and white box testing include a few forms of testing. Below is a list of them.
White Box Penetration Testing − In this type of testing, the tester/developer has access to the entire source code of the program, as well as extensive network information, IP addresses involved, and all server information. The goal is to attack the code from several aspects in order to expose security flaws.
White Box Penetration Testing − In this type of testing, the tester/developer has access to the entire source code of the program, as well as extensive network information, IP addresses involved, and all server information. The goal is to attack the code from several aspects in order to expose security flaws.
White Box Mutation Testing − White box mutation testing is frequently used to determine the optimum coding strategies for growing a software solution.
White Box Mutation Testing − White box mutation testing is frequently used to determine the optimum coding strategies for growing a software solution.
Code optimization through the detection of hidden defects.
Code optimization through the detection of hidden defects.
Cases for white-box tests are simple to automate.
Cases for white-box tests are simple to automate.
Because all code paths are usually covered, testing is more thorough.
Because all code paths are usually covered, testing is more thorough.
Even if a GUI is not accessible, testing can begin early in the SDLC.
Even if a GUI is not accessible, testing can begin early in the SDLC.
White box testing can be time-consuming and costly.
White box testing can be time-consuming and costly.
It irritates developers who are used to running white box test scenarios. Developers' lack of detail in white box testing can lead to production problems.
It irritates developers who are used to running white box test scenarios. Developers' lack of detail in white box testing can lead to production problems.
Professional resources with a thorough understanding of programming and implementation are required for white box testing.
Professional resources with a thorough understanding of programming and implementation are required for white box testing.
White-box testing takes time, and larger programming applications require more time to thoroughly test.
White-box testing takes time, and larger programming applications require more time to thoroughly test.
White box testing is a difficult task. The application being tested has a lot to do with the difficulty involved. White box testing a small application that performs a single simple task can take minutes, whereas larger programming programs might take days, weeks, or even months to completely test.
Software testing should be performed on a software application when it is being developed, after it has been written, and again after each modification. | [
{
"code": null,
"e": 1454,
"s": 1062,
"text": "White Box Testing is a software examining technique that involves testing the product's underlying structure, design, and coding in order to verify input-output flow and improve design, usability, and security. White box testing is also known as Clear box testing, Open box testing, transparent box testing, Code-based testing, and Glass box testing since the code is visible to the testers."
},
{
"code": null,
"e": 1758,
"s": 1454,
"text": "It's one of two components of the software testing approach known as Box Testing. Blackbox testing, on the other hand, entails testing from an external or end-user perspective. White box testing, on the other hand, is focused on the inner workings of an application and revolves around internal testing."
},
{
"code": null,
"e": 2136,
"s": 1758,
"text": "Because of the see-through box concept, the term \"WhiteBox\" was coined. The name \"clear box\" or \"WhiteBox\" refers to the ability to see into the software's inner workings through its exterior shell (or \"box\"). Similarly, the \"black box\" in \"Black Box Testing\" denotes the inability to observe the software's inner workings, allowing only the end-user experience to be assessed."
},
{
"code": null,
"e": 2220,
"s": 2136,
"text": "White box testing entails putting the software code to the test for the following −"
},
{
"code": null,
"e": 2247,
"s": 2220,
"text": "Internal flaws in security"
},
{
"code": null,
"e": 2274,
"s": 2247,
"text": "Internal flaws in security"
},
{
"code": null,
"e": 2339,
"s": 2274,
"text": "Paths in the coding process that are broken or poorly structured"
},
{
"code": null,
"e": 2404,
"s": 2339,
"text": "Paths in the coding process that are broken or poorly structured"
},
{
"code": null,
"e": 2463,
"s": 2404,
"text": "The path is taken by specified inputs through the program."
},
{
"code": null,
"e": 2522,
"s": 2463,
"text": "The path is taken by specified inputs through the program."
},
{
"code": null,
"e": 2539,
"s": 2522,
"text": "Expected results"
},
{
"code": null,
"e": 2556,
"s": 2539,
"text": "Expected results"
},
{
"code": null,
"e": 2613,
"s": 2556,
"text": "Conditional loops are useful in a variety of situations."
},
{
"code": null,
"e": 2670,
"s": 2613,
"text": "Conditional loops are useful in a variety of situations."
},
{
"code": null,
"e": 2733,
"s": 2670,
"text": "Individualized testing of each statement, object, and function"
},
{
"code": null,
"e": 2796,
"s": 2733,
"text": "Individualized testing of each statement, object, and function"
},
{
"code": null,
"e": 3170,
"s": 2796,
"text": "Software development might include testing at the system, integration, and unit levels. One of the primary aims of white-box testing is to ensure that an application's operating flow is correct. It entails comparing a set of predetermined inputs to\nexpected or desired outputs, with the goal of identifying bugs when one of the inputs fails to provide the expected outcome."
},
{
"code": null,
"e": 3360,
"s": 3170,
"text": "We've broken down white box testing into two simple phases to make it easier to understand. When utilizing the white box testing technique to test an application, testers do the following −"
},
{
"code": null,
"e": 3698,
"s": 3360,
"text": "The source code of the program is generally the first thing a tester learns and understands. Because white box testing entails testing an application's inner workings, the tester must be well-versed in the programming languages used in the applications under test. Furthermore, the tester must be well-versed in secure coding techniques."
},
{
"code": null,
"e": 3949,
"s": 3698,
"text": "One of the main goals of software testing is to ensure that it is secure. The tester should be able to detect security flaws and prevent assaults from hackers and naive users who may purposefully or unknowingly inject dangerous code into the program."
},
{
"code": null,
"e": 4517,
"s": 3949,
"text": "The application's source code is tested for correct flow and structure in the second\nfundamental step of white box testing. One method is to write more code to test the source code of the application. For each step or sequence of processes in the application, the tester will create little tests. This method necessitates the tester's\nextensive understanding of the code and is frequently carried out by the developer. Manual testing, trial, and error testing, and the usage of testing tools are some of the other methods that will be discussed later in this article."
},
{
"code": null,
"e": 4524,
"s": 4517,
"text": "Code −"
},
{
"code": null,
"e": 4723,
"s": 4524,
"text": "Printme (int a, int b) {------------ it is a function\n int result = a+ b;\n If (result > 0)\n Print (\"Positive\", result)\n Else\n Print (\"Negative\", result)\n} ----------- End of the code"
},
{
"code": null,
"e": 4857,
"s": 4723,
"text": "WhiteBox testing in software engineering aims to make sure that all decision branches, loops, and statements in the code are correct."
},
{
"code": null,
"e": 4969,
"s": 4857,
"text": "WhiteBox test cases would be used to put the statements in the preceding white box testing example to the test."
},
{
"code": null,
"e": 4982,
"s": 4969,
"text": "A = 1; B = 1"
},
{
"code": null,
"e": 4997,
"s": 4982,
"text": "A = -1, B = -3"
},
{
"code": null,
"e": 5370,
"s": 4997,
"text": "Code Coverage Analysis is a popular White box testing technique. A Test Case suite's holes are filled through Code Coverage analysis. It identifies parts of a program that aren't put to the test in a collection of test cases. You write test cases to check untested areas of the code once the holes have been detected, thereby improving the quality of the software product."
},
{
"code": null,
"e": 5509,
"s": 5370,
"text": "Code coverage analysis can be performed using automated technologies. A box tester can employ the following coverage analysis techniques −"
},
{
"code": null,
"e": 5670,
"s": 5509,
"text": "Statement Coverage − During the software engineering testing process, this technique mandates that every possible statement in the code be tested at least once."
},
{
"code": null,
"e": 5831,
"s": 5670,
"text": "Statement Coverage − During the software engineering testing process, this technique mandates that every possible statement in the code be tested at least once."
},
{
"code": null,
"e": 5961,
"s": 5831,
"text": "Branch Coverage − This technique examines every conceivable path of a software application (if-else and other conditional loops)."
},
{
"code": null,
"e": 6091,
"s": 5961,
"text": "Branch Coverage − This technique examines every conceivable path of a software application (if-else and other conditional loops)."
},
{
"code": null,
"e": 6470,
"s": 6091,
"text": "Aside from the aforementioned coverage kinds, there is a slew of others, including Condition Coverage, Multiple Condition Coverage, Path Coverage, and Function Coverage. Each method has its own set of advantages and aims to test (cover) all aspects of software code. You can typically achieve 80-90 percent code coverage using Statement and Branch coverage, which is sufficient."
},
{
"code": null,
"e": 6537,
"s": 6470,
"text": "Following are some of the important WhiteBox Testing Techniquess −"
},
{
"code": null,
"e": 6556,
"s": 6537,
"text": "Statement Coverage"
},
{
"code": null,
"e": 6574,
"s": 6556,
"text": "Decision Coverage"
},
{
"code": null,
"e": 6590,
"s": 6574,
"text": "Branch Coverage"
},
{
"code": null,
"e": 6609,
"s": 6590,
"text": "Condition Coverage"
},
{
"code": null,
"e": 6637,
"s": 6609,
"text": "Multiple Condition Coverage"
},
{
"code": null,
"e": 6667,
"s": 6637,
"text": "Finite State Machine Coverage"
},
{
"code": null,
"e": 6681,
"s": 6667,
"text": "Path Coverage"
},
{
"code": null,
"e": 6702,
"s": 6681,
"text": "Control flow testing"
},
{
"code": null,
"e": 6720,
"s": 6702,
"text": "Data flow testing"
},
{
"code": null,
"e": 6738,
"s": 6720,
"text": "To make certain −"
},
{
"code": null,
"e": 6810,
"s": 6738,
"text": "That each module's independent pathways have been tested at least once."
},
{
"code": null,
"e": 6882,
"s": 6810,
"text": "That each module's independent pathways have been tested at least once."
},
{
"code": null,
"e": 6952,
"s": 6882,
"text": "All logical decisions were tested to see if they were true or untrue."
},
{
"code": null,
"e": 7022,
"s": 6952,
"text": "All logical decisions were tested to see if they were true or untrue."
},
{
"code": null,
"e": 7160,
"s": 7022,
"text": "Internal data structures validity is ensured by all loops that are executed at their boundaries and within their operational constraints."
},
{
"code": null,
"e": 7298,
"s": 7160,
"text": "Internal data structures validity is ensured by all loops that are executed at their boundaries and within their operational constraints."
},
{
"code": null,
"e": 7339,
"s": 7298,
"text": "To find the types of bugs listed below −"
},
{
"code": null,
"e": 7480,
"s": 7339,
"text": "When we create and implement functions, conditions, or controls that are not part of the program, we are more likely to make logical errors."
},
{
"code": null,
"e": 7621,
"s": 7480,
"text": "When we create and implement functions, conditions, or controls that are not part of the program, we are more likely to make logical errors."
},
{
"code": null,
"e": 7720,
"s": 7621,
"text": "Design flaws resulting from a mismatch between the program's logical flow and its actual execution"
},
{
"code": null,
"e": 7819,
"s": 7720,
"text": "Design flaws resulting from a mismatch between the program's logical flow and its actual execution"
},
{
"code": null,
"e": 7867,
"s": 7819,
"text": "Checking for grammatical and syntactic mistakes"
},
{
"code": null,
"e": 7915,
"s": 7867,
"text": "Checking for grammatical and syntactic mistakes"
},
{
"code": null,
"e": 8104,
"s": 7915,
"text": "White box testing refers to a variety of testing methods that are used to assess the usability of an application, a piece of code, or a specific software package. The following is a list −"
},
{
"code": null,
"e": 8662,
"s": 8104,
"text": "Unit testing − Unit testing is frequently the first type of application testing performed. As each unit or block of code is developed, it is subjected to unit testing. The programmer is primarily responsible for unit testing. As a software developer, you write a few lines of code, a single function, or an object, then test it to ensure it works before moving on to the next step. Early in the software development lifecycle, unit testing helps in the detection of the majority of issues. Bugs discovered at this stage are less expensive and easier to fix."
},
{
"code": null,
"e": 9220,
"s": 8662,
"text": "Unit testing − Unit testing is frequently the first type of application testing performed. As each unit or block of code is developed, it is subjected to unit testing. The programmer is primarily responsible for unit testing. As a software developer, you write a few lines of code, a single function, or an object, then test it to ensure it works before moving on to the next step. Early in the software development lifecycle, unit testing helps in the detection of the majority of issues. Bugs discovered at this stage are less expensive and easier to fix."
},
{
"code": null,
"e": 9563,
"s": 9220,
"text": "Testing for Memory Leaks − Memory leaks are one of the most common reasons for slow-running apps. When you have a slow-running software application, you need a QA professional who is skilled in detecting memory leaks. Apart from the aforementioned, both black box and white box testing include a few forms of testing. Below is a list of them."
},
{
"code": null,
"e": 9906,
"s": 9563,
"text": "Testing for Memory Leaks − Memory leaks are one of the most common reasons for slow-running apps. When you have a slow-running software application, you need a QA professional who is skilled in detecting memory leaks. Apart from the aforementioned, both black box and white box testing include a few forms of testing. Below is a list of them."
},
{
"code": null,
"e": 10217,
"s": 9906,
"text": "White Box Penetration Testing − In this type of testing, the tester/developer has access to the entire source code of the program, as well as extensive network information, IP addresses involved, and all server information. The goal is to attack the code from several aspects in order to expose security flaws."
},
{
"code": null,
"e": 10528,
"s": 10217,
"text": "White Box Penetration Testing − In this type of testing, the tester/developer has access to the entire source code of the program, as well as extensive network information, IP addresses involved, and all server information. The goal is to attack the code from several aspects in order to expose security flaws."
},
{
"code": null,
"e": 10679,
"s": 10528,
"text": "White Box Mutation Testing − White box mutation testing is frequently used to determine the optimum coding strategies for growing a software solution."
},
{
"code": null,
"e": 10830,
"s": 10679,
"text": "White Box Mutation Testing − White box mutation testing is frequently used to determine the optimum coding strategies for growing a software solution."
},
{
"code": null,
"e": 10889,
"s": 10830,
"text": "Code optimization through the detection of hidden defects."
},
{
"code": null,
"e": 10948,
"s": 10889,
"text": "Code optimization through the detection of hidden defects."
},
{
"code": null,
"e": 10998,
"s": 10948,
"text": "Cases for white-box tests are simple to automate."
},
{
"code": null,
"e": 11048,
"s": 10998,
"text": "Cases for white-box tests are simple to automate."
},
{
"code": null,
"e": 11118,
"s": 11048,
"text": "Because all code paths are usually covered, testing is more thorough."
},
{
"code": null,
"e": 11188,
"s": 11118,
"text": "Because all code paths are usually covered, testing is more thorough."
},
{
"code": null,
"e": 11258,
"s": 11188,
"text": "Even if a GUI is not accessible, testing can begin early in the SDLC."
},
{
"code": null,
"e": 11328,
"s": 11258,
"text": "Even if a GUI is not accessible, testing can begin early in the SDLC."
},
{
"code": null,
"e": 11380,
"s": 11328,
"text": "White box testing can be time-consuming and costly."
},
{
"code": null,
"e": 11432,
"s": 11380,
"text": "White box testing can be time-consuming and costly."
},
{
"code": null,
"e": 11587,
"s": 11432,
"text": "It irritates developers who are used to running white box test scenarios. Developers' lack of detail in white box testing can lead to production problems."
},
{
"code": null,
"e": 11742,
"s": 11587,
"text": "It irritates developers who are used to running white box test scenarios. Developers' lack of detail in white box testing can lead to production problems."
},
{
"code": null,
"e": 11865,
"s": 11742,
"text": "Professional resources with a thorough understanding of programming and implementation are required for white box testing."
},
{
"code": null,
"e": 11988,
"s": 11865,
"text": "Professional resources with a thorough understanding of programming and implementation are required for white box testing."
},
{
"code": null,
"e": 12092,
"s": 11988,
"text": "White-box testing takes time, and larger programming applications require more time to thoroughly test."
},
{
"code": null,
"e": 12196,
"s": 12092,
"text": "White-box testing takes time, and larger programming applications require more time to thoroughly test."
},
{
"code": null,
"e": 12496,
"s": 12196,
"text": "White box testing is a difficult task. The application being tested has a lot to do with the difficulty involved. White box testing a small application that performs a single simple task can take minutes, whereas larger programming programs might take days, weeks, or even months to completely test."
},
{
"code": null,
"e": 12649,
"s": 12496,
"text": "Software testing should be performed on a software application when it is being developed, after it has been written, and again after each modification."
}
] |
Adapter Pattern - GeeksforGeeks | 01 Sep, 2021
This pattern is easy to understand as the real world is full of adapters. For example consider a USB to Ethernet adapter. We need this when we have an Ethernet interface on one end and USB on the other. Since they are incompatible with each other. we use an adapter that converts one to other. This example is pretty analogous to Object Oriented Adapters. In design, adapters are used when we have a class (Client) expecting some type of object and we have an object (Adaptee) offering the same features but exposing a different interface.
To use an adapter:
The client makes a request to the adapter by calling a method on it using the target interface.The adapter translates that request on the adaptee using the adaptee interface.Client receive the results of the call and is unaware of adapter’s presence.
The client makes a request to the adapter by calling a method on it using the target interface.
The adapter translates that request on the adaptee using the adaptee interface.
Client receive the results of the call and is unaware of adapter’s presence.
Definition:
The adapter pattern convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Class Diagram:
The client sees only the target interface and not the adapter. The adapter implements the target interface. Adapter delegates all requests to Adaptee.
Example:
Suppose you have a Bird class with fly() , and makeSound()methods. And also a ToyDuck class with squeak() method. Let’s assume that you are short on ToyDuck objects and you would like to use Bird objects in their place. Birds have some similar functionality but implement a different interface, so we can’t use them directly. So we will use adapter pattern. Here our client would be ToyDuck and adaptee would be Bird.
Below is Java implementation of it.
// Java implementation of Adapter pattern interface Bird{ // birds implement Bird interface that allows // them to fly and make sounds adaptee interface public void fly(); public void makeSound();} class Sparrow implements Bird{ // a concrete implementation of bird public void fly() { System.out.println("Flying"); } public void makeSound() { System.out.println("Chirp Chirp"); }} interface ToyDuck{ // target interface // toyducks dont fly they just make // squeaking sound public void squeak();} class PlasticToyDuck implements ToyDuck{ public void squeak() { System.out.println("Squeak"); }} class BirdAdapter implements ToyDuck{ // You need to implement the interface your // client expects to use. Bird bird; public BirdAdapter(Bird bird) { // we need reference to the object we // are adapting this.bird = bird; } public void squeak() { // translate the methods appropriately bird.makeSound(); }} class Main{ public static void main(String args[]) { Sparrow sparrow = new Sparrow(); ToyDuck toyDuck = new PlasticToyDuck(); // Wrap a bird in a birdAdapter so that it // behaves like toy duck ToyDuck birdAdapter = new BirdAdapter(sparrow); System.out.println("Sparrow..."); sparrow.fly(); sparrow.makeSound(); System.out.println("ToyDuck..."); toyDuck.squeak(); // toy duck behaving like a bird System.out.println("BirdAdapter..."); birdAdapter.squeak(); }}
Output:
Sparrow...
Flying
Chirp Chirp
ToyDuck...
Squeak
BirdAdapter...
Chirp Chirp
Explanation :Suppose we have a bird that can makeSound(), and we have a plastic toy duck that can squeak(). Now suppose our client changes the requirement and he wants the toyDuck to makeSound than ?Simple solution is that we will just change the implementation class to the new adapter class and tell the client to pass the instance of the bird(which wants to squeak()) to that class.Before : ToyDuck toyDuck = new PlasticToyDuck();After : ToyDuck toyDuck = new BirdAdapter(sparrow);You can see that by changing just one line the toyDuck can now do Chirp Chirp !!
Object Adapter Vs Class AdapterThe adapter pattern we have implemented above is called Object Adapter Pattern because the adapter holds an instance of adaptee. There is also another type called Class Adapter Pattern which use inheritance instead of composition but you require multiple inheritance to implement it.Class diagram of Class Adapter Pattern:
Here instead of having an adaptee object inside adapter (composition) to make use of its functionality adapter inherits the adaptee.
Since multiple inheritance is not supported by many languages including java and is associated with many problems we have not shown implementation using class adapter pattern.
Advantages:
Helps achieve reusability and flexibility.
Client class is not complicated by having to use a different interface and can use polymorphism to swap between different implementations of adapters.
Disadvantages:
All requests are forwarded, so there is a slight increase in the overhead.
Sometimes many adaptations are required along an adapter chain to reach the type which is required.
Further Read: Adapter Method in Python
References:Head First Design Patterns ( Book )
This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sanchit_Shah
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Unified Modeling Language (UML) | An Introduction
Observer Pattern | Set 1 (Introduction)
Composite Design Pattern
Unified Modeling Language (UML) | State Diagrams
Abstract Factory Pattern
How to design a parking lot using object-oriented principles?
Monolithic vs Microservices architecture
Singleton Design Pattern | Introduction
Unified Modeling Language (UML) | Class Diagrams
Design a movie ticket booking system like Bookmyshow | [
{
"code": null,
"e": 24167,
"s": 24139,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 24709,
"s": 24167,
"text": "This pattern is easy to understand as the real world is full of adapters. For example consider a USB to Ethernet adapter. We need this when we have an Ethernet interface on one end and USB on the other. Since they are incompatible with each other. we use an adapter that converts one to other. This example is pretty analogous to Object Oriented Adapters. In design, adapters are used when we have a class (Client) expecting some type of object and we have an object (Adaptee) offering the same features but exposing a different interface."
},
{
"code": null,
"e": 24728,
"s": 24709,
"text": "To use an adapter:"
},
{
"code": null,
"e": 24979,
"s": 24728,
"text": "The client makes a request to the adapter by calling a method on it using the target interface.The adapter translates that request on the adaptee using the adaptee interface.Client receive the results of the call and is unaware of adapter’s presence."
},
{
"code": null,
"e": 25075,
"s": 24979,
"text": "The client makes a request to the adapter by calling a method on it using the target interface."
},
{
"code": null,
"e": 25155,
"s": 25075,
"text": "The adapter translates that request on the adaptee using the adaptee interface."
},
{
"code": null,
"e": 25232,
"s": 25155,
"text": "Client receive the results of the call and is unaware of adapter’s presence."
},
{
"code": null,
"e": 25244,
"s": 25232,
"text": "Definition:"
},
{
"code": null,
"e": 25431,
"s": 25244,
"text": "The adapter pattern convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces."
},
{
"code": null,
"e": 25446,
"s": 25431,
"text": "Class Diagram:"
},
{
"code": null,
"e": 25597,
"s": 25446,
"text": "The client sees only the target interface and not the adapter. The adapter implements the target interface. Adapter delegates all requests to Adaptee."
},
{
"code": null,
"e": 25606,
"s": 25597,
"text": "Example:"
},
{
"code": null,
"e": 26024,
"s": 25606,
"text": "Suppose you have a Bird class with fly() , and makeSound()methods. And also a ToyDuck class with squeak() method. Let’s assume that you are short on ToyDuck objects and you would like to use Bird objects in their place. Birds have some similar functionality but implement a different interface, so we can’t use them directly. So we will use adapter pattern. Here our client would be ToyDuck and adaptee would be Bird."
},
{
"code": null,
"e": 26060,
"s": 26024,
"text": "Below is Java implementation of it."
},
{
"code": "// Java implementation of Adapter pattern interface Bird{ // birds implement Bird interface that allows // them to fly and make sounds adaptee interface public void fly(); public void makeSound();} class Sparrow implements Bird{ // a concrete implementation of bird public void fly() { System.out.println(\"Flying\"); } public void makeSound() { System.out.println(\"Chirp Chirp\"); }} interface ToyDuck{ // target interface // toyducks dont fly they just make // squeaking sound public void squeak();} class PlasticToyDuck implements ToyDuck{ public void squeak() { System.out.println(\"Squeak\"); }} class BirdAdapter implements ToyDuck{ // You need to implement the interface your // client expects to use. Bird bird; public BirdAdapter(Bird bird) { // we need reference to the object we // are adapting this.bird = bird; } public void squeak() { // translate the methods appropriately bird.makeSound(); }} class Main{ public static void main(String args[]) { Sparrow sparrow = new Sparrow(); ToyDuck toyDuck = new PlasticToyDuck(); // Wrap a bird in a birdAdapter so that it // behaves like toy duck ToyDuck birdAdapter = new BirdAdapter(sparrow); System.out.println(\"Sparrow...\"); sparrow.fly(); sparrow.makeSound(); System.out.println(\"ToyDuck...\"); toyDuck.squeak(); // toy duck behaving like a bird System.out.println(\"BirdAdapter...\"); birdAdapter.squeak(); }}",
"e": 27679,
"s": 26060,
"text": null
},
{
"code": null,
"e": 27687,
"s": 27679,
"text": "Output:"
},
{
"code": null,
"e": 27762,
"s": 27687,
"text": "Sparrow...\nFlying\nChirp Chirp\nToyDuck...\nSqueak\nBirdAdapter...\nChirp Chirp"
},
{
"code": null,
"e": 28327,
"s": 27762,
"text": "Explanation :Suppose we have a bird that can makeSound(), and we have a plastic toy duck that can squeak(). Now suppose our client changes the requirement and he wants the toyDuck to makeSound than ?Simple solution is that we will just change the implementation class to the new adapter class and tell the client to pass the instance of the bird(which wants to squeak()) to that class.Before : ToyDuck toyDuck = new PlasticToyDuck();After : ToyDuck toyDuck = new BirdAdapter(sparrow);You can see that by changing just one line the toyDuck can now do Chirp Chirp !!"
},
{
"code": null,
"e": 28681,
"s": 28327,
"text": "Object Adapter Vs Class AdapterThe adapter pattern we have implemented above is called Object Adapter Pattern because the adapter holds an instance of adaptee. There is also another type called Class Adapter Pattern which use inheritance instead of composition but you require multiple inheritance to implement it.Class diagram of Class Adapter Pattern:"
},
{
"code": null,
"e": 28814,
"s": 28681,
"text": "Here instead of having an adaptee object inside adapter (composition) to make use of its functionality adapter inherits the adaptee."
},
{
"code": null,
"e": 28990,
"s": 28814,
"text": "Since multiple inheritance is not supported by many languages including java and is associated with many problems we have not shown implementation using class adapter pattern."
},
{
"code": null,
"e": 29002,
"s": 28990,
"text": "Advantages:"
},
{
"code": null,
"e": 29045,
"s": 29002,
"text": "Helps achieve reusability and flexibility."
},
{
"code": null,
"e": 29196,
"s": 29045,
"text": "Client class is not complicated by having to use a different interface and can use polymorphism to swap between different implementations of adapters."
},
{
"code": null,
"e": 29211,
"s": 29196,
"text": "Disadvantages:"
},
{
"code": null,
"e": 29286,
"s": 29211,
"text": "All requests are forwarded, so there is a slight increase in the overhead."
},
{
"code": null,
"e": 29386,
"s": 29286,
"text": "Sometimes many adaptations are required along an adapter chain to reach the type which is required."
},
{
"code": null,
"e": 29425,
"s": 29386,
"text": "Further Read: Adapter Method in Python"
},
{
"code": null,
"e": 29472,
"s": 29425,
"text": "References:Head First Design Patterns ( Book )"
},
{
"code": null,
"e": 29739,
"s": 29472,
"text": "This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29863,
"s": 29739,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 29876,
"s": 29863,
"text": "Sanchit_Shah"
},
{
"code": null,
"e": 29891,
"s": 29876,
"text": "Design Pattern"
},
{
"code": null,
"e": 29989,
"s": 29891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29998,
"s": 29989,
"text": "Comments"
},
{
"code": null,
"e": 30011,
"s": 29998,
"text": "Old Comments"
},
{
"code": null,
"e": 30061,
"s": 30011,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 30101,
"s": 30061,
"text": "Observer Pattern | Set 1 (Introduction)"
},
{
"code": null,
"e": 30126,
"s": 30101,
"text": "Composite Design Pattern"
},
{
"code": null,
"e": 30175,
"s": 30126,
"text": "Unified Modeling Language (UML) | State Diagrams"
},
{
"code": null,
"e": 30200,
"s": 30175,
"text": "Abstract Factory Pattern"
},
{
"code": null,
"e": 30262,
"s": 30200,
"text": "How to design a parking lot using object-oriented principles?"
},
{
"code": null,
"e": 30303,
"s": 30262,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 30343,
"s": 30303,
"text": "Singleton Design Pattern | Introduction"
},
{
"code": null,
"e": 30392,
"s": 30343,
"text": "Unified Modeling Language (UML) | Class Diagrams"
}
] |
fmt Package in GoLang - GeeksforGeeks | 25 Aug, 2020
Prerequisite: Packages in GoLang and Import in GoLang
Technically defining, a package is essentially a container of source code for some specific purpose. Packages are very essential as in all programs ranging from the most basic programs to high-level complex codes, these are used. A package ensures that no code is repeated and that the main code is as concise as possible in a well-structured manner. Go provides various in-built packages to users so they can ease into coding with pre-defined basic functionality packages. One of such packages in the “fmt” package. fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console, or write into a file using a writer or even print customized fancy error messages. This package is all about formatting input and output.
Irrespective of what system you’ve installed Go on, find your $GOPATH, and then visit “$GOPATH/src/fmt/” on your system. You will find the following package-files in this particular directory. Well, we can say that these files all fall under the fmt package.
The image shows all the files situated in the “$GOPATH/src/fmt/” directory on your PC
Let’s look at the functions it provides to its users along with a brief description of each function:
FUNCTIONS
DESCRIPTION
Print
Print simply prints whatever input it receives as it is on theoutput console screen, beginning from the current cursor positionwithout appending any space or newlines unless explicitly coded.Apart from printing, it returns two values: the no of bytes writtenand error message in case any write error is encountered.
Printf
Printf formats the input string as the user’s choice and then printsthe formatted string onto the output console beginning from thecurrent cursor position without appending any space or newlinesunless explicitly coded. Apart from printing, it returns two values:the number of bytes written and error message in case any erroris encountered.
Println
Println works the same as print function except that it appends newline at the end of the input string and so whatever the output is, in the end, the cursor will move to the next line. Also in case, any variables are added to the input string then this function will ensure that the variables are separated by a space in between. Apart from printing, it returns two values: the no of bytes written and error message in case any write error is encountered.
Sprint
Sprint functions the same way as Print does. The only differenceis that Sprint returns the input string instead of printingon the output console.
Sprintf
Sprintln
Sprintln functions the same way as Println does. the only difference is that Sprintln returns the input stringinstead of printing on the output console.
Fprint
Unlike other print functions, the Fprint does not read or print anything on the console. Fprint formats the input string as per the default formatting and writes the formatted input string into the input file. Whenever two variables are encountered, space is automatically added in between by fprint. Apart from writing into the file, fprint returns two values: no. of bytes written& error message (if any error occurs).
Fprintf
Just similar to fprint but one difference that draws a line between the two is that fprintf formats according to the specified format and does not format according to the default formatting.Fprintf then writes the formatted input string into the file using. Apart from writing into the file, fprintf returns two values: no. of bytes are written and an error message (if any error occurs).
Fprintln
Scan
Scanf
Scanln
Sscan
Sscanf
Sscanln
Fscan
Fscanf
Fscanln
Errorf
Apart from the functions, Go has some in-built interfaces in its packages. The “fmt” package consists of the following interfaces. The following description has been referred from the official site of Go, you may click here to find out more.
TYPES
DESCRIPTION
Formatter
GoStringer
ScanState
Scanner
State
Stringer
So basically, in Go to implement any interface, we have just learned that we don’t have to do anything explicitly. Instead calling specific methods automatically implement the interfaces for the user. And it is through the implementation of the methods in interfaces that enable a particular value to take multiple forms. This is simply termed as polymorphism. Summing all this up, Interfaces in go are implemented implicitly when its methods are called and interfaces contribute to the concept of polymorphism.
1. Printing functions
Go
// Go code to visualise the differences// between various print functions in fmt package main import "fmt" func main() { // NOTE: // 1. Print(arg) prints arg as // it is on the console screen fmt.Print("Hello, welcome!") // OUTPUT: "Hello, welcome!" // Some variables to use in our code const x, id = "Ashika", 22 // 2. Printf(arg) first formats arg // and then prints on the console screen fmt.Printf("\n1. Name %q and ID %d found!\n", x, id) // OUTPUT: // 1. Name "Ashika" and ID 22 found! // 3. Println(arg) does not format arg // It simply prints arg, appends any values // mentioned after arg and appends spaces in // between and also appends a new line at the end fmt.Println("2. Name %q and ID %d found!", x, id) // OUTPUT: 2. Name %q and ID %d found! Ashika 22 // Print(arg) does not format, does not add // any spaces and does not append any newlines fmt.Print("3. Name %q and ID %d found!", x, id) // OUTPUT: 3. Name %q and ID %d found!Ashika22 // 4. Sprint(arg) works similar to Print(arg) // The key difference is: Sprint returns arg as // it is as mentioned in the paranthesis and // Print(arg) prints on console screen. res := fmt.Sprint("\n4. Name %q and ID %d found!", x, id) fmt.Println(res) // OUTPUT: // 4. Name %q and ID %d found!Ashika22 // 5. Sprintf(arg) works similar to Printf(arg) // The key difference is: Sprintf returns arg as // a formatted string as mentioned in the paranthesis // and Printf prints formatted arg on console screen res = fmt.Sprintf("5. Name %q and ID %d found!", x, id) fmt.Println(res) // OUTPUT: 5. Name "Ashika" and ID 22 found! // 6. Sprintln(arg) works similar to Println(arg) // The key difference is: Sprintln returns arg as // it is as mentioned in paranthesis and adds spaces // between variables and appends a newline to arg & // returns arg value while Println directly prints arg // onto the console screen. res = fmt.Sprintln("6. Name %q and ID %d found!", x, id) fmt.Print(res) // OUTPUT: 6. Name %q and ID %d found! Ashika 22 fmt.Print("Goodbye!") // OUTPUT: "Goodbye!"}
Output:
Hello, welcome!
1. Name "Ashika" and ID 22 found!
2. Name %q and ID %d found! Ashika 22
3. Name %q and ID %d found!Ashika22
4. Name %q and ID %d found!Ashika22
5. Name "Ashika" and ID 22 found!
6. Name %q and ID %d found! Ashika 22
Goodbye!
2. Scanning functions
Go
// Go code to demonstrate use & differences// between various scan functions in fmt package package main import "fmt" // Main functionfunc main() { fmt.Print("Hello, welcome!\n") var y, z, age int var name string // Scan function will collect input // until a space is encountered // from console and stores it in y fmt.Scan(&y) fmt.Printf("Scan: Y = %d\n", y) // Scanf collects user input in // the specified format and stores it // in name and age respectively fmt.Scanf("%s", &name) fmt.Scanf("%d", &age) fmt.Printf("Scanf: Name = %s , Age = %d\n", name, age) // Scanln will not do nothing if // a newline is encountered else // it stores input value in z fmt.Scanln(&z) // In our case after entering age we press // enter so this Scanln gets skipped and // thus 0 is stored in z as 0 is the // default value of int variable in Go fmt.Printf("Scanln: Z = %d\n", z) var a string var g int // GFG is stored in a // 10 is stored in g // In case of any error, error message // is stored in err1 // Number of values encountered is stored in res1 res1, err1 := fmt.Sscan("GFG 10", &a, &g) // In case of any error, this block will execute if err1 != nil { panic(err1) } fmt.Printf("Sscan -> n = %d , string = %s %d \n", res1, a, g) // GFG is stored in a // 5 is stored in g // In case of any error, error message // is stored in err2 // Number of values encountered is stored in res2 res2, err2 := fmt.Sscanf("String is GFG with 5 iterations", "String is %s with %d iterations", &a, &g) // In case of any error, this block will execute if err2 != nil { panic(err2) } fmt.Printf("Sscanf -> n = %d , string = %s %d \n", res2, a, g) // GFG is stored in a // 17 is stored in g // In case a newline is encountered, // then Sscanln will raise a newline // panic error message // In case of any error, error message // is stored in err3 // Number of values encountered is stored in res3 res3, err3 := fmt.Sscanln("GFG 17", &a, &g) // In case of any error, this block will execute if err3 != nil { panic(err3) } fmt.Printf("Sscanln -> n = %d , string = %s %d \n", res3, a, g) fmt.Println("Goodbye!")}
Input:
10
Ashika
20
Output:
Hello, welcome!
Scan: Y = 10
Scanf: Name = Ashika , Age = 20
Scanln: Z = 0
Sscan -> n =2 , string = GFG 10
Sscanf -> n = 2 , string = GFG 5
Sscanln -> n = 2 , string = GFG 17
Goodbye!
3. Errorf function demo
Go
// Go code to demonstrate// the use of errorf function// in fmt packagepackage main import "fmt" // Main functionfunc main() { const lazy = "I'm very lazy today" // Errorf formats according to the format specifier and // returns the string as a value that satisfies the error // and this error string are stored in err err := fmt.Errorf("Throwing error because: %q", lazy) // err.Error() will return the error message // and Println will print it on the output console fmt.Println(err.Error())}
Output:
Throwing error because: "I'm very lazy today"
Output of printing functions sample code
Note: The scanln value is showing 0 as an output. It is so because scanln could even collect the user input, the newline from previous input has forced scanln to stop collecting input from the user. And default value in Go for int is a 0 thus the value 0 for Z.
Output of scanning functions sample code
Output of errorf function sample code
Golang-Packages
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Formatting in Golang
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Arrays in Go
Slices in Golang
Golang Maps
How to convert a string in lower case in Golang?
Inheritance in GoLang
How to Trim a String in Golang? | [
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 24851,
"s": 24796,
"text": "Prerequisite: Packages in GoLang and Import in GoLang "
},
{
"code": null,
"e": 25661,
"s": 24851,
"text": "Technically defining, a package is essentially a container of source code for some specific purpose. Packages are very essential as in all programs ranging from the most basic programs to high-level complex codes, these are used. A package ensures that no code is repeated and that the main code is as concise as possible in a well-structured manner. Go provides various in-built packages to users so they can ease into coding with pre-defined basic functionality packages. One of such packages in the “fmt” package. fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console, or write into a file using a writer or even print customized fancy error messages. This package is all about formatting input and output."
},
{
"code": null,
"e": 25920,
"s": 25661,
"text": "Irrespective of what system you’ve installed Go on, find your $GOPATH, and then visit “$GOPATH/src/fmt/” on your system. You will find the following package-files in this particular directory. Well, we can say that these files all fall under the fmt package."
},
{
"code": null,
"e": 26006,
"s": 25920,
"text": "The image shows all the files situated in the “$GOPATH/src/fmt/” directory on your PC"
},
{
"code": null,
"e": 26108,
"s": 26006,
"text": "Let’s look at the functions it provides to its users along with a brief description of each function:"
},
{
"code": null,
"e": 26127,
"s": 26108,
"text": " FUNCTIONS "
},
{
"code": null,
"e": 26139,
"s": 26127,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 26145,
"s": 26139,
"text": "Print"
},
{
"code": null,
"e": 26461,
"s": 26145,
"text": "Print simply prints whatever input it receives as it is on theoutput console screen, beginning from the current cursor positionwithout appending any space or newlines unless explicitly coded.Apart from printing, it returns two values: the no of bytes writtenand error message in case any write error is encountered."
},
{
"code": null,
"e": 26468,
"s": 26461,
"text": "Printf"
},
{
"code": null,
"e": 26809,
"s": 26468,
"text": "Printf formats the input string as the user’s choice and then printsthe formatted string onto the output console beginning from thecurrent cursor position without appending any space or newlinesunless explicitly coded. Apart from printing, it returns two values:the number of bytes written and error message in case any erroris encountered."
},
{
"code": null,
"e": 26817,
"s": 26809,
"text": "Println"
},
{
"code": null,
"e": 27273,
"s": 26817,
"text": "Println works the same as print function except that it appends newline at the end of the input string and so whatever the output is, in the end, the cursor will move to the next line. Also in case, any variables are added to the input string then this function will ensure that the variables are separated by a space in between. Apart from printing, it returns two values: the no of bytes written and error message in case any write error is encountered."
},
{
"code": null,
"e": 27280,
"s": 27273,
"text": "Sprint"
},
{
"code": null,
"e": 27426,
"s": 27280,
"text": "Sprint functions the same way as Print does. The only differenceis that Sprint returns the input string instead of printingon the output console."
},
{
"code": null,
"e": 27434,
"s": 27426,
"text": "Sprintf"
},
{
"code": null,
"e": 27443,
"s": 27434,
"text": "Sprintln"
},
{
"code": null,
"e": 27596,
"s": 27443,
"text": "Sprintln functions the same way as Println does. the only difference is that Sprintln returns the input stringinstead of printing on the output console."
},
{
"code": null,
"e": 27603,
"s": 27596,
"text": "Fprint"
},
{
"code": null,
"e": 28024,
"s": 27603,
"text": "Unlike other print functions, the Fprint does not read or print anything on the console. Fprint formats the input string as per the default formatting and writes the formatted input string into the input file. Whenever two variables are encountered, space is automatically added in between by fprint. Apart from writing into the file, fprint returns two values: no. of bytes written& error message (if any error occurs)."
},
{
"code": null,
"e": 28032,
"s": 28024,
"text": "Fprintf"
},
{
"code": null,
"e": 28421,
"s": 28032,
"text": "Just similar to fprint but one difference that draws a line between the two is that fprintf formats according to the specified format and does not format according to the default formatting.Fprintf then writes the formatted input string into the file using. Apart from writing into the file, fprintf returns two values: no. of bytes are written and an error message (if any error occurs)."
},
{
"code": null,
"e": 28430,
"s": 28421,
"text": "Fprintln"
},
{
"code": null,
"e": 28435,
"s": 28430,
"text": "Scan"
},
{
"code": null,
"e": 28441,
"s": 28435,
"text": "Scanf"
},
{
"code": null,
"e": 28448,
"s": 28441,
"text": "Scanln"
},
{
"code": null,
"e": 28454,
"s": 28448,
"text": "Sscan"
},
{
"code": null,
"e": 28461,
"s": 28454,
"text": "Sscanf"
},
{
"code": null,
"e": 28469,
"s": 28461,
"text": "Sscanln"
},
{
"code": null,
"e": 28475,
"s": 28469,
"text": "Fscan"
},
{
"code": null,
"e": 28482,
"s": 28475,
"text": "Fscanf"
},
{
"code": null,
"e": 28490,
"s": 28482,
"text": "Fscanln"
},
{
"code": null,
"e": 28497,
"s": 28490,
"text": "Errorf"
},
{
"code": null,
"e": 28739,
"s": 28497,
"text": "Apart from the functions, Go has some in-built interfaces in its packages. The “fmt” package consists of the following interfaces. The following description has been referred from the official site of Go, you may click here to find out more."
},
{
"code": null,
"e": 28761,
"s": 28739,
"text": " TYPES "
},
{
"code": null,
"e": 28773,
"s": 28761,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 28783,
"s": 28773,
"text": "Formatter"
},
{
"code": null,
"e": 28794,
"s": 28783,
"text": "GoStringer"
},
{
"code": null,
"e": 28804,
"s": 28794,
"text": "ScanState"
},
{
"code": null,
"e": 28812,
"s": 28804,
"text": "Scanner"
},
{
"code": null,
"e": 28818,
"s": 28812,
"text": "State"
},
{
"code": null,
"e": 28827,
"s": 28818,
"text": "Stringer"
},
{
"code": null,
"e": 29339,
"s": 28827,
"text": "So basically, in Go to implement any interface, we have just learned that we don’t have to do anything explicitly. Instead calling specific methods automatically implement the interfaces for the user. And it is through the implementation of the methods in interfaces that enable a particular value to take multiple forms. This is simply termed as polymorphism. Summing all this up, Interfaces in go are implemented implicitly when its methods are called and interfaces contribute to the concept of polymorphism."
},
{
"code": null,
"e": 29361,
"s": 29339,
"text": "1. Printing functions"
},
{
"code": null,
"e": 29364,
"s": 29361,
"text": "Go"
},
{
"code": "// Go code to visualise the differences// between various print functions in fmt package main import \"fmt\" func main() { // NOTE: // 1. Print(arg) prints arg as // it is on the console screen fmt.Print(\"Hello, welcome!\") // OUTPUT: \"Hello, welcome!\" // Some variables to use in our code const x, id = \"Ashika\", 22 // 2. Printf(arg) first formats arg // and then prints on the console screen fmt.Printf(\"\\n1. Name %q and ID %d found!\\n\", x, id) // OUTPUT: // 1. Name \"Ashika\" and ID 22 found! // 3. Println(arg) does not format arg // It simply prints arg, appends any values // mentioned after arg and appends spaces in // between and also appends a new line at the end fmt.Println(\"2. Name %q and ID %d found!\", x, id) // OUTPUT: 2. Name %q and ID %d found! Ashika 22 // Print(arg) does not format, does not add // any spaces and does not append any newlines fmt.Print(\"3. Name %q and ID %d found!\", x, id) // OUTPUT: 3. Name %q and ID %d found!Ashika22 // 4. Sprint(arg) works similar to Print(arg) // The key difference is: Sprint returns arg as // it is as mentioned in the paranthesis and // Print(arg) prints on console screen. res := fmt.Sprint(\"\\n4. Name %q and ID %d found!\", x, id) fmt.Println(res) // OUTPUT: // 4. Name %q and ID %d found!Ashika22 // 5. Sprintf(arg) works similar to Printf(arg) // The key difference is: Sprintf returns arg as // a formatted string as mentioned in the paranthesis // and Printf prints formatted arg on console screen res = fmt.Sprintf(\"5. Name %q and ID %d found!\", x, id) fmt.Println(res) // OUTPUT: 5. Name \"Ashika\" and ID 22 found! // 6. Sprintln(arg) works similar to Println(arg) // The key difference is: Sprintln returns arg as // it is as mentioned in paranthesis and adds spaces // between variables and appends a newline to arg & // returns arg value while Println directly prints arg // onto the console screen. res = fmt.Sprintln(\"6. Name %q and ID %d found!\", x, id) fmt.Print(res) // OUTPUT: 6. Name %q and ID %d found! Ashika 22 fmt.Print(\"Goodbye!\") // OUTPUT: \"Goodbye!\"}",
"e": 31596,
"s": 29364,
"text": null
},
{
"code": null,
"e": 31604,
"s": 31596,
"text": "Output:"
},
{
"code": null,
"e": 31846,
"s": 31604,
"text": "Hello, welcome!\n1. Name \"Ashika\" and ID 22 found!\n2. Name %q and ID %d found! Ashika 22\n3. Name %q and ID %d found!Ashika22\n4. Name %q and ID %d found!Ashika22\n5. Name \"Ashika\" and ID 22 found!\n6. Name %q and ID %d found! Ashika 22\nGoodbye!\n"
},
{
"code": null,
"e": 31868,
"s": 31846,
"text": "2. Scanning functions"
},
{
"code": null,
"e": 31871,
"s": 31868,
"text": "Go"
},
{
"code": "// Go code to demonstrate use & differences// between various scan functions in fmt package package main import \"fmt\" // Main functionfunc main() { fmt.Print(\"Hello, welcome!\\n\") var y, z, age int var name string // Scan function will collect input // until a space is encountered // from console and stores it in y fmt.Scan(&y) fmt.Printf(\"Scan: Y = %d\\n\", y) // Scanf collects user input in // the specified format and stores it // in name and age respectively fmt.Scanf(\"%s\", &name) fmt.Scanf(\"%d\", &age) fmt.Printf(\"Scanf: Name = %s , Age = %d\\n\", name, age) // Scanln will not do nothing if // a newline is encountered else // it stores input value in z fmt.Scanln(&z) // In our case after entering age we press // enter so this Scanln gets skipped and // thus 0 is stored in z as 0 is the // default value of int variable in Go fmt.Printf(\"Scanln: Z = %d\\n\", z) var a string var g int // GFG is stored in a // 10 is stored in g // In case of any error, error message // is stored in err1 // Number of values encountered is stored in res1 res1, err1 := fmt.Sscan(\"GFG 10\", &a, &g) // In case of any error, this block will execute if err1 != nil { panic(err1) } fmt.Printf(\"Sscan -> n = %d , string = %s %d \\n\", res1, a, g) // GFG is stored in a // 5 is stored in g // In case of any error, error message // is stored in err2 // Number of values encountered is stored in res2 res2, err2 := fmt.Sscanf(\"String is GFG with 5 iterations\", \"String is %s with %d iterations\", &a, &g) // In case of any error, this block will execute if err2 != nil { panic(err2) } fmt.Printf(\"Sscanf -> n = %d , string = %s %d \\n\", res2, a, g) // GFG is stored in a // 17 is stored in g // In case a newline is encountered, // then Sscanln will raise a newline // panic error message // In case of any error, error message // is stored in err3 // Number of values encountered is stored in res3 res3, err3 := fmt.Sscanln(\"GFG 17\", &a, &g) // In case of any error, this block will execute if err3 != nil { panic(err3) } fmt.Printf(\"Sscanln -> n = %d , string = %s %d \\n\", res3, a, g) fmt.Println(\"Goodbye!\")}",
"e": 34223,
"s": 31871,
"text": null
},
{
"code": null,
"e": 34230,
"s": 34223,
"text": "Input:"
},
{
"code": null,
"e": 34244,
"s": 34230,
"text": "10\nAshika\n20\n"
},
{
"code": null,
"e": 34252,
"s": 34244,
"text": "Output:"
},
{
"code": null,
"e": 34437,
"s": 34252,
"text": "Hello, welcome!\nScan: Y = 10\nScanf: Name = Ashika , Age = 20\nScanln: Z = 0\nSscan -> n =2 , string = GFG 10\nSscanf -> n = 2 , string = GFG 5\nSscanln -> n = 2 , string = GFG 17\nGoodbye!\n"
},
{
"code": null,
"e": 34461,
"s": 34437,
"text": "3. Errorf function demo"
},
{
"code": null,
"e": 34464,
"s": 34461,
"text": "Go"
},
{
"code": "// Go code to demonstrate// the use of errorf function// in fmt packagepackage main import \"fmt\" // Main functionfunc main() { const lazy = \"I'm very lazy today\" // Errorf formats according to the format specifier and // returns the string as a value that satisfies the error // and this error string are stored in err err := fmt.Errorf(\"Throwing error because: %q\", lazy) // err.Error() will return the error message // and Println will print it on the output console fmt.Println(err.Error())}",
"e": 34993,
"s": 34464,
"text": null
},
{
"code": null,
"e": 35001,
"s": 34993,
"text": "Output:"
},
{
"code": null,
"e": 35048,
"s": 35001,
"text": "Throwing error because: \"I'm very lazy today\"\n"
},
{
"code": null,
"e": 35089,
"s": 35048,
"text": "Output of printing functions sample code"
},
{
"code": null,
"e": 35353,
"s": 35091,
"text": "Note: The scanln value is showing 0 as an output. It is so because scanln could even collect the user input, the newline from previous input has forced scanln to stop collecting input from the user. And default value in Go for int is a 0 thus the value 0 for Z."
},
{
"code": null,
"e": 35394,
"s": 35353,
"text": "Output of scanning functions sample code"
},
{
"code": null,
"e": 35432,
"s": 35394,
"text": "Output of errorf function sample code"
},
{
"code": null,
"e": 35448,
"s": 35432,
"text": "Golang-Packages"
},
{
"code": null,
"e": 35460,
"s": 35448,
"text": "Go Language"
},
{
"code": null,
"e": 35558,
"s": 35460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35584,
"s": 35558,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 35635,
"s": 35584,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 35682,
"s": 35635,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 35715,
"s": 35682,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 35728,
"s": 35715,
"text": "Arrays in Go"
},
{
"code": null,
"e": 35745,
"s": 35728,
"text": "Slices in Golang"
},
{
"code": null,
"e": 35757,
"s": 35745,
"text": "Golang Maps"
},
{
"code": null,
"e": 35806,
"s": 35757,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 35828,
"s": 35806,
"text": "Inheritance in GoLang"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.